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

$today = date('Y-m-d');

// ===================== FILTERS =====================
$from = $_GET['from'] ?? $today;
$to   = $_GET['to'] ?? $today;
$payment_method = $_GET['payment_method'] ?? '';

$where = "DATE(p.payment_date) BETWEEN '$from' AND '$to'";
if(!empty($payment_method)){
    $where .= " AND p.method='$payment_method'";
}

// ===================== FETCH PAYMENTS =====================
$payments = $conn->query("
    SELECT p.*, g.name AS guest_name, u.username AS cashier
    FROM payments p
    LEFT JOIN guests g ON p.guest_id=g.id
    LEFT JOIN users u ON p.user_id=u.id
    WHERE $where
    ORDER BY p.payment_date DESC
");

// ===================== TOTALS =====================
$total_payments = $conn->query("
    SELECT IFNULL(SUM(p.amount),0) AS total
    FROM payments p
    WHERE $where
")->fetch_assoc()['total'];

// Total discount
$total_discount = $conn->query("
    SELECT IFNULL(SUM(p.discount),0) AS total_discount
    FROM payments p
    WHERE $where
")->fetch_assoc()['total_discount'];

?>

<!-- DataTables CSS -->
<link rel="stylesheet" href="https://cdn.datatables.net/1.13.6/css/jquery.dataTables.min.css">
<link rel="stylesheet" href="https://cdn.datatables.net/buttons/2.4.1/css/buttons.dataTables.min.css">

<div class="container mt-4">
    <div class="welcome-msg mb-3">
        <i class="fa fa-user-circle"></i> Welcome, <strong><?= htmlspecialchars($_SESSION['username'] ?? 'Guest') ?></strong>!
    </div>

    <button class="btn btn-secondary mb-3" onclick="history.back()">
        <i class="fa fa-arrow-left"></i> Back
    </button>

    <h3 class="text-center">💸 Discounts Report</h3>
    <hr>

    <!-- ================= TOTAL SUMMARY ================= -->
    <div class="alert alert-info">
        <strong>Total Payments:</strong> MK <?= number_format($total_payments,2) ?><br>
        <strong>Total Discounts:</strong> MK <?= number_format($total_discount,2) ?>
    </div>

    <!-- ================= FILTERS ================= -->
    <form method="GET" class="row g-3 mb-3">
        <div class="col-md-2">
            <label>From</label>
            <input type="date" name="from" value="<?= $from ?>" class="form-control">
        </div>
        <div class="col-md-2">
            <label>To</label>
            <input type="date" name="to" value="<?= $to ?>" class="form-control">
        </div>
        <div class="col-md-3">
            <label>Payment Method</label>
            <select name="payment_method" class="form-control">
                <option value="">-- All --</option>
                <option <?= $payment_method=='Cash'?'selected':'' ?>>Cash</option>
                <option <?= $payment_method=='Mobile Money'?'selected':'' ?>>Mobile Money</option>
                <option <?= $payment_method=='Card'?'selected':'' ?>>Card</option>
            </select>
        </div>
        <div class="col-md-2 mt-4">
            <button class="btn btn-primary w-100">Filter</button>
        </div>
    </form>

    <!-- ================= PAYMENTS TABLE ================= -->
    <table id="discountTable" class="display nowrap table table-bordered table-striped" style="width:100%">
        <thead class="bg-dark text-white">
            <tr>
                <th>#</th>
                <th>Date</th>
                <th>Guest</th>
                <th>Cashier</th>
                <th>Payment Method</th>
                <th>Amount (MK)</th>
                <th>Discount (MK)</th>
            </tr>
        </thead>
        <tbody>
        <?php 
        $i=1;
        while($p = $payments->fetch_assoc()):
            $discount = $p['discount'] ?? 0;
        ?>
            <tr>
                <td><?= $i++ ?></td>
                <td><?= $p['payment_date'] ?></td>
                <td><?= htmlspecialchars($p['guest_name'] ?? 'Walk-in') ?></td>
                <td><?= htmlspecialchars($p['cashier'] ?? 'System') ?></td>
                <td><?= htmlspecialchars($p['method']) ?></td>
                <td><?= number_format($p['amount'],2) ?></td>
                <td><?= number_format($discount,2) ?></td>
            </tr>
        <?php endwhile; ?>
        </tbody>
    </table>
</div>

<!-- DataTables JS -->
<script src="https://code.jquery.com/jquery-3.7.0.min.js"></script>
<script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.4.1/js/dataTables.buttons.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.4.1/js/buttons.html5.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.4.1/js/buttons.print.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.1/jszip.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.2.7/pdfmake.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.2.7/vfs_fonts.js"></script>

<script>
$(document).ready(function() {
    $('#discountTable').DataTable({
        dom: 'Bfrtip',
        buttons: [
            { extend: 'excelHtml5', title: 'Discount Report' },
            { extend: 'pdfHtml5', title: 'Discount Report', orientation: 'portrait', pageSize: 'A4' },
            { extend: 'print', title: 'Discount Report' }
        ],
        scrollX: true
    });
});
</script>

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