<?php

session_start();

if(!isset($_SESSION['user_id'])){
    header("Location:login.php");
    exit;
}

require_once "config.php";

$id = $_GET['id'] ?? 0;

$stmt = $pdo->prepare("SELECT * FROM expense_items WHERE id=?");
$stmt->execute([$id]);
$item = $stmt->fetch();

if(!$item){
    die("Item not found");
}

$stmt = $pdo->prepare("
SELECT
COUNT(*) records,
COALESCE(SUM(total),0) total
FROM expenses
WHERE item_id=?
");
$stmt->execute([$id]);
$summary = $stmt->fetch();

$stmt = $pdo->prepare("
SELECT
expenses.*,
vendors.vendor_name,
expense_categories.category_name

FROM expenses

LEFT JOIN vendors
ON expenses.vendor_id=vendors.id

LEFT JOIN expense_categories
ON expenses.category_id=expense_categories.id

WHERE expenses.item_id=?

ORDER BY expense_date DESC
");

$stmt->execute([$id]);
$expenses = $stmt->fetchAll();

?>
<!DOCTYPE html>
<html>
<head>

<meta charset="UTF-8">

<title>Expense Statement</title>

<style>

body{

font-family:Arial,sans-serif;

margin:30px;

font-size:14px;

}

h1,h2{

text-align:center;

}

table{

width:100%;

border-collapse:collapse;

margin-top:20px;

}

th{

background:#065f46;

color:white;

padding:10px;

border:1px solid #999;

}

td{

padding:8px;

border:1px solid #999;

}

.summary{

margin:20px 0;

}

.print{

margin-top:20px;

text-align:center;

}

button{

padding:10px 20px;

font-size:15px;

cursor:pointer;

}

@media print{

.print{

display:none;

}

}

</style>

</head>

<body>

<h1>Expense Statement</h1>

<h2><?=htmlspecialchars($item['item_name'])?></h2>

<?php if(!empty($item['registration_no'])){ ?>

<p><strong>Registration:</strong>
<?=htmlspecialchars($item['registration_no'])?>
</p>

<?php } ?>

<div class="summary">

<p><strong>Total Transactions:</strong>
<?=$summary['records']?>
</p>

<p><strong>Total Spent:</strong>
MWK <?=number_format($summary['total'],2)?>
</p>

<p><strong>Printed:</strong>
<?=date("d M Y H:i")?>
</p>

</div>

<table>

<tr>

<th>Date</th>

<th>Category</th>

<th>Vendor</th>

<th>Description</th>

<th>Payment</th>

<th>Total</th>

</tr>

<?php foreach($expenses as $row){ ?>

<tr>

<td><?=date("d M Y",strtotime($row['expense_date']))?></td>

<td><?=htmlspecialchars($row['category_name'])?></td>

<td><?=htmlspecialchars($row['vendor_name'] ?? 'Unknown')?></td>

<td><?=htmlspecialchars($row['description'])?></td>

<td><?=htmlspecialchars($row['payment_method'])?></td>

<td style="text-align:right;">
MWK <?=number_format($row['total'],2)?>
</td>

</tr>

<?php } ?>

</table>

<div class="print">

<button onclick="window.print()">

🖨 Print

</button>

</div>

<script>

window.onload=function(){

window.print();

};

</script>

</body>

</html>