<?php
include 'includes/auth.php';
include 'db.php';
include 'includes/header.php';

// --- Filter by date ---
$filter_date = $_POST['filter_date'] ?? date('Y-m-d');

$sql = "
SELECT s.payment_method,
       SUM(si.qty * si.price + si.vat) AS total_amount,
       SUM(si.qty) AS total_items,
       COUNT(DISTINCT s.id) AS total_sales
FROM sales s
JOIN sale_items si ON s.id = si.sale_id
WHERE DATE(s.sale_date) = '$filter_date'
GROUP BY s.payment_method
ORDER BY total_amount DESC
";

$result = $conn->query($sql);
?>

<div class="container mt-4">
    <h3 class="text-center">Daily Sales</h3>
    <hr>

    <!-- Date Filter -->
    <form method="POST" class="row g-3 mb-4">
        <div class="col-md-6">
            <input type="date" name="filter_date" value="<?= htmlspecialchars($filter_date) ?>" class="form-control" required>
        </div>
        <div class="col-md-6">
            <button type="submit" class="btn btn-primary w-100">Filter</button>
        </div>
    </form>

    <!-- Reconciliation Table -->
    <table class="table table-bordered table-striped">
        <thead class="bg-dark text-white">
            <tr>
                <th>Payment Method</th>
                <th>Total Sales (MK)</th>
                <th>Total Items Sold</th>
                <th>Number of Transactions</th>
            </tr>
        </thead>
        <tbody>
            <?php
            $grand_total_amount = 0;
            $grand_total_items = 0;
            $grand_total_sales = 0;
            while($row = $result->fetch_assoc()){
                $grand_total_amount += $row['total_amount'];
                $grand_total_items += $row['total_items'];
                $grand_total_sales += $row['total_sales'];
                echo "
                <tr>
                    <td>{$row['payment_method']}</td>
                    <td>".number_format($row['total_amount'],2)."</td>
                    <td>{$row['total_items']}</td>
                    <td>{$row['total_sales']}</td>
                </tr>
                ";
            }
            ?>
        </tbody>
        <tfoot>
            <tr class="fw-bold">
                <td>Total</td>
                <td>MK <?= number_format($grand_total_amount,2) ?></td>
                <td><?= $grand_total_items ?></td>
                <td><?= $grand_total_sales ?></td>
            </tr>
        </tfoot>
    </table>
</div>

<?php include 'includes/footer.php'; ?>
