<?php include '../db.php'; ?>

<h2>All Payments</h2>
<a href="add.php">+ Add Payment</a><br><br>

<form method="get">
    <label>From:</label><input type="date" name="from">
    <label>To:</label><input type="date" name="to">
    <button type="submit">Filter</button>
</form>

<table border="1" cellpadding="5">
<tr>
    <th>Invoice</th><th>Client</th><th>Amount</th><th>Mode</th><th>Date</th><th>Receipt</th>
</tr>
<?php
$query = "
    SELECT p.*, i.invoice_number, c.name AS client_name
    FROM payments p
    JOIN invoices i ON p.invoice_id = i.id
    JOIN clients c ON i.client_id = c.id
    WHERE 1 ";

if ($_GET['from'] ?? '') {
    $query .= "AND p.paid_at >= '". $_GET['from'] ."' ";
}
if ($_GET['to'] ?? '') {
    $query .= "AND p.paid_at <= '". $_GET['to'] ."' ";
}

$query .= "ORDER BY p.paid_at DESC";

foreach ($conn->query($query)->fetchAll() as $p) {
    echo "<tr>
        <td>{$p['invoice_number']}</td>
        <td>{$p['client_name']}</td>
        <td>?{$p['amount']}</td>
        <td>{$p['mode']}</td>
        <td>{$p['paid_at']}</td>
        <td><a href='receipt.php?id={$p['id']}' target='_blank'>View</a></td>
    </tr>";
}
?>
</table>
