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

// ================= FETCH GUESTS =================
$guests = $conn->query("SELECT * FROM guests ORDER BY name");

// ================= BUILD FILTERS =================
$filters = [];
if(!empty($_GET['guest_id'])) $filters[] = "g.id = ".intval($_GET['guest_id']);
if(!empty($_GET['date_from']) && !empty($_GET['date_to'])) {
    $filters[] = "p.payment_date BETWEEN '".$conn->real_escape_string($_GET['date_from'])." 00:00:00' AND '".$conn->real_escape_string($_GET['date_to'])." 23:59:59'";
}
$filter_sql = count($filters) ? "WHERE ".implode(" AND ", $filters) : "";

// ================= FETCH PAYMENT RECORDS =================
$payments = $conn->query("
    SELECT p.*, g.name as guest_name
    FROM payments p
    JOIN guests g ON p.guest_id = g.id
    $filter_sql
    ORDER BY p.payment_date DESC
");

// ================= CALCULATE TOTALS =================
$total_paid = 0;
$payment_summary = [];
$res_summary = $conn->query("
    SELECT g.id as guest_id, g.name as guest_name, SUM(p.amount) as total_paid
    FROM payments p
    JOIN guests g ON p.guest_id=g.id
    ".($filters ? "WHERE ".implode(" AND ", $filters) : "")."
    GROUP BY g.id
");
while($row = $res_summary->fetch_assoc()){
    $payment_summary[$row['guest_id']] = [
        'guest_name' => $row['guest_name'],
        'total_paid' => $row['total_paid']
    ];
    $total_paid += $row['total_paid'];
}
?>

<div class="container mt-4">
     <div class="welcome-msg">
        <i class="fa fa-user-circle"></i> Welcome, <strong><?= htmlspecialchars($_SESSION['username'] ?? 'Guest') ?></strong>!
    </div>
<button class="btn btn-secondary btn-custom mb-3" onclick="history.back()">
    <i class="fa fa-arrow-left"></i> Back
</button>

<h4><i class="fa fa-file-invoice-dollar"></i> Accounting Reports</h4>
<hr>

<!-- ================= FILTER FORM ================= -->
<form method="GET" class="row g-3 mb-4">
    <div class="col-md-4">
        <label>Guest</label>
        <select name="guest_id" class="form-control" onchange="this.form.submit()">
            <option value="">-- All Guests --</option>
            <?php while($g=$guests->fetch_assoc()): ?>
                <option value="<?= $g['id'] ?>" <?= ($_GET['guest_id'] ?? '')==$g['id']?'selected':'' ?>>
                    <?= htmlspecialchars($g['name']) ?>
                </option>
            <?php endwhile; ?>
        </select>
    </div>
    <div class="col-md-3">
        <label>Date From</label>
        <input type="date" name="date_from" value="<?= htmlspecialchars($_GET['date_from'] ?? '') ?>" class="form-control">
    </div>
    <div class="col-md-3">
        <label>Date To</label>
        <input type="date" name="date_to" value="<?= htmlspecialchars($_GET['date_to'] ?? '') ?>" class="form-control">
    </div>
    <div class="col-md-2 d-flex align-items-end">
        <button class="btn btn-primary w-100"><i class="fa fa-filter"></i> Filter</button>
    </div>
</form>

<!-- ================= TOTAL SUMMARY ================= -->
<h5><i class="fa fa-chart-line"></i> Summary</h5>
<div class="mb-3">
    <div class="alert alert-info">
        <strong>Total Paid:</strong> MK <?= number_format($total_paid,2) ?><br>
        <strong>Total Guests:</strong> <?= count($payment_summary) ?>
    </div>
</div>

<!-- ================= PAYMENT HISTORY ================= -->
<h5><i class="fa fa-history"></i> Payment Records</h5>
<table class="table table-bordered table-striped">
    <thead class="bg-dark text-white">
        <tr>
            <th>#</th>
            <th>Guest</th>
            <th>Type</th>
            <th>Amount (MK)</th>
            <th>Method</th>
            <th>Description</th>
            <th>Date</th>
            <th>Action</th>
        </tr>
    </thead>
    <tbody>
    <?php
    $i=1;
    while($p = $payments->fetch_assoc()):
    ?>
        <tr>
            <td><?= $i ?></td>
            <td><?= htmlspecialchars($p['guest_name']) ?></td>
            <td><?= $p['type'] ?></td>
            <td><?= number_format($p['amount'],2) ?></td>
            <td><?= $p['method'] ?></td>
            <td><?= htmlspecialchars($p['description']) ?></td>
            <td><?= date('d-M-Y H:i', strtotime($p['payment_date'])) ?></td>
            <td>
                <a href="edit_payment.php?id=<?= $p['id'] ?>" class="btn btn-sm btn-primary"><i class="fa fa-edit"></i></a>
                <a href="receipt_pay.php?id=<?= $p['id'] ?>" target="_blank" class="btn btn-sm btn-success"><i class="fa fa-receipt"></i></a>
            </td>
        </tr>
    <?php $i++; endwhile; ?>
    </tbody>
</table>

<!-- ================= PER GUEST TOTALS ================= -->
<h5 class="mt-4"><i class="fa fa-users"></i> Total Payments Per Guest</h5>
<table class="table table-bordered table-striped">
    <thead class="bg-primary text-white">
        <tr>
            <th>#</th>
            <th>Guest</th>
            <th>Total Paid (MK)</th>
        </tr>
    </thead>
    <tbody>
    <?php $j=1; foreach($payment_summary as $guest_id=>$summary): ?>
        <tr>
            <td><?= $j ?></td>
            <td><?= htmlspecialchars($summary['guest_name']) ?></td>
            <td><?= number_format($summary['total_paid'],2) ?></td>
        </tr>
    <?php $j++; endforeach; ?>
    </tbody>
</table>

<div class="mt-3">
    <button class="btn btn-secondary" onclick="window.print()"><i class="fa fa-print"></i> Print Report</button>
</div>

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