<?php
// hps_payment_report.php
require "db.php";

/* -----------------------------
   DATE FILTER
------------------------------*/
$from = $_GET['from'] ?? "";
$to   = $_GET['to'] ?? "";

$where = [];
if ($from) $where[] = "p.pay_date >= '$from'";
if ($to)   $where[] = "p.pay_date <= '$to'";

$whereSql = $where ? "WHERE " . implode(" AND ", $where) : "";

/* -----------------------------
   FETCH PAYMENTS
------------------------------*/
$sql = "
SELECT 
    p.pay_date,
    p.pay_type,
    p.amount,
    p.remarks,
    s.sale_no,
    c.name AS customer
FROM hps_payments p
JOIN hps_sales s ON s.id = p.sale_id
JOIN hps_customers c ON c.id = s.customer_id
$whereSql
ORDER BY p.pay_date DESC, p.id DESC
";

$res = mysqli_query($conn, $sql);

/* -----------------------------
   TOTAL
------------------------------*/
$total = 0;
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Payment Report</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">

<style>
@media print {
    .no-print { display:none; }
}
</style>
</head>
<body>

<div class="container py-3">

<h4 class="mb-3">💰 Payment Report</h4>

<!-- FILTER -->
<form method="get" class="row g-2 no-print mb-3">

<div class="col-md-3">
<label class="small">From</label>
<input type="date" name="from" value="<?=$from?>" class="form-control form-control-sm">
</div>

<div class="col-md-3">
<label class="small">To</label>
<input type="date" name="to" value="<?=$to?>" class="form-control form-control-sm">
</div>

<div class="col-md-2 d-flex align-items-end">
<button class="btn btn-primary btn-sm w-100">Filter</button>
</div>

<div class="col-md-2 d-flex align-items-end">
<button type="button" onclick="window.print()" class="btn btn-secondary btn-sm w-100">
Print
</button>
</div>

</form>

<!-- TABLE -->
<table class="table table-bordered table-sm">
<thead class="table-dark">
<tr>
    <th>#</th>
    <th>Date</th>
    <th>Sale No</th>
    <th>Customer</th>
    <th>Type</th>
    <th class="text-end">Amount</th>
</tr>
</thead>
<tbody>

<?php $i=1; while($r=mysqli_fetch_assoc($res)): 
    $total += $r['amount'];
?>
<tr>
    <td><?=$i++?></td>
    <td><?=date('d-M-Y',strtotime($r['pay_date']))?></td>
    <td><?=htmlspecialchars($r['sale_no'])?></td>
    <td><?=htmlspecialchars($r['customer'])?></td>
    <td><?=htmlspecialchars($r['pay_type'])?></td>
    <td class="text-end"><?=number_format($r['amount'])?></td>
</tr>
<?php endwhile; ?>

</tbody>

<tfoot>
<tr class="fw-bold">
    <td colspan="5" class="text-end">TOTAL</td>
    <td class="text-end"><?=number_format($total)?></td>
</tr>
</tfoot>

</table>

</div>
</body>
</html>
