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

$username = $_SESSION['username'] ?? 'Guest';

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

$from_date = $_GET['from'] ?? $today;
$to_date   = $_GET['to'] ?? $today;
$type      = $_GET['type'] ?? '';
$search    = $_GET['search'] ?? '';

// ================= BUILD WHERE =================
$where = [];

if($from_date){
    $where[] = "DATE(p.payment_date) >= '".$conn->real_escape_string($from_date)."'";
}

if($to_date){
    $where[] = "DATE(p.payment_date) <= '".$conn->real_escape_string($to_date)."'";
}

if($type){
    $where[] = "p.type = '".$conn->real_escape_string($type)."'";
}

if($search){
    $s = $conn->real_escape_string($search);
    $where[] = "(p.reference LIKE '%$s%' 
                OR p.received_by LIKE '%$s%'
                OR g.name LIKE '%$s%')";
}

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

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

// ================= SUMMARY =================
$summary = $conn->query("
    SELECT 
        COUNT(*) AS total_count,
        IFNULL(SUM(p.amount),0) AS total_amount,
        IFNULL(SUM(CASE WHEN p.type='Cash' THEN p.amount END),0) AS cash_total,
        IFNULL(SUM(CASE WHEN p.type='Card' THEN p.amount END),0) AS card_total,
        IFNULL(SUM(CASE WHEN p.type='Transfer' THEN p.amount END),0) AS transfer_total
    FROM payments p
    LEFT JOIN guests g ON p.guest_id = g.id
    $where_sql
")->fetch_assoc();

$total_amount   = $summary['total_amount'] ?? 0;
$cash_total     = $summary['cash_total'] ?? 0;
$card_total     = $summary['card_total'] ?? 0;
$transfer_total = $summary['transfer_total'] ?? 0;
$total_count    = $summary['total_count'] ?? 0;
?>

<style>
.report-card{border-radius:12px;}
.table thead th{white-space:nowrap;}
.welcome-msg{
    background:#f8f9fa;
    padding:8px 12px;
    border-radius:8px;
    margin-bottom:10px;
}
@media print{ .no-print{display:none!important;} }
</style>

<div class="container-fluid mt-4">

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

<div class="welcome-msg no-print">
    <i class="fa fa-user-circle"></i>
    Welcome, <strong><?= htmlspecialchars($username) ?></strong>
</div>

<h3 class="mb-2">
    <i class="fa fa-money-bill-wave text-success"></i>
    Payments Report
</h3>

<?php if($from_date == $to_date): ?>
<div class="alert alert-info py-2">
    Showing payments for <strong><?= date('d M Y', strtotime($from_date)) ?></strong>
</div>
<?php endif; ?>

<hr>

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

    <div class="col-md-2">
        <input type="date" name="from" class="form-control"
               value="<?= htmlspecialchars($from_date) ?>">
    </div>

    <div class="col-md-2">
        <input type="date" name="to" class="form-control"
               value="<?= htmlspecialchars($to_date) ?>">
    </div>

    <div class="col-md-2">
        <select name="type" class="form-control">
            <option value="">All Types</option>
            <option <?= $type=='Cash'?'selected':'' ?>>Cash</option>
            <option <?= $type=='Card'?'selected':'' ?>>Card</option>
            <option <?= $type=='Transfer'?'selected':'' ?>>Transfer</option>
        </select>
    </div>

    <div class="col-md-3">
        <input type="text" name="search" class="form-control"
               placeholder="Search reference / guest / user"
               value="<?= htmlspecialchars($search) ?>">
    </div>

    <div class="col-md-1">
        <button class="btn btn-primary w-100">
            <i class="fa fa-filter"></i>
        </button>
    </div>

    <div class="col-md-2">
        <a href="payments_report.php" class="btn btn-secondary w-100">Reset</a>
    </div>
</form>

<!-- ================= EXPORT BUTTONS ================= -->
<div class="mb-3 no-print d-flex gap-2 flex-wrap">

    <button onclick="window.print()" class="btn btn-danger">
        <i class="fa fa-file-pdf"></i> Export PDF
    </button>

    <a href="export_payments_excel.php?from=<?= urlencode($from_date) ?>&to=<?= urlencode($to_date) ?>&type=<?= urlencode($type) ?>&search=<?= urlencode($search) ?>"
       class="btn btn-success">
        <i class="fa fa-file-excel"></i> Export Excel
    </a>

</div>

<!-- ================= SUMMARY ================= -->
<div class="row mb-3 text-center">

    <div class="col-md-3">
        <div class="card report-card shadow-sm">
            <div class="card-body">
                <h6>Total Payments</h6>
                <h4 class="text-primary"><?= $total_count ?></h4>
            </div>
        </div>
    </div>

    <div class="col-md-3">
        <div class="card report-card shadow-sm">
            <div class="card-body">
                <h6>Total Amount (MK)</h6>
                <h4><?= number_format($total_amount,2) ?></h4>
            </div>
        </div>
    </div>

    <div class="col-md-2">
        <div class="card report-card shadow-sm">
            <div class="card-body">
                <h6>Cash</h6>
                <h4 class="text-success"><?= number_format($cash_total,2) ?></h4>
            </div>
        </div>
    </div>

    <div class="col-md-2">
        <div class="card report-card shadow-sm">
            <div class="card-body">
                <h6>Card</h6>
                <h4 class="text-warning"><?= number_format($card_total,2) ?></h4>
            </div>
        </div>
    </div>

    <div class="col-md-2">
        <div class="card report-card shadow-sm">
            <div class="card-body">
                <h6>Transfer</h6>
                <h4 class="text-info"><?= number_format($transfer_total,2) ?></h4>
            </div>
        </div>
    </div>

</div>

<!-- ================= TABLE ================= -->
<div class="table-responsive">
<table class="table table-bordered table-striped table-sm">
<thead class="table-dark">
<tr>
    <th>Date</th>
    <th>Guest</th>
    <th>Reference</th>
    <th>Method</th>
    <th>Type</th>
    <th>Amount (MK)</th>
    <th>Received By</th>
</tr>
</thead>
<tbody>

<?php if($payments && $payments->num_rows): ?>
<?php while($p = $payments->fetch_assoc()): ?>
<tr>
    <td><?= htmlspecialchars($p['payment_date']) ?></td>
    <td><?= htmlspecialchars($p['guest_name'] ?? '-') ?></td>
    <td><?= htmlspecialchars($p['reference'] ?? '-') ?></td>
    <td><?= htmlspecialchars($p['method'] ?? '-') ?></td>
    <td><?= htmlspecialchars($p['type']) ?></td>
    <td class="fw-bold"><?= number_format($p['amount'],2) ?></td>
    <td><?= htmlspecialchars($p['received_by'] ?? '-') ?></td>
</tr>
<?php endwhile; ?>
<?php else: ?>
<tr>
    <td colspan="7" class="text-center text-danger">
        No payments found
    </td>
</tr>
<?php endif; ?>

</tbody>

<tfoot class="table-dark">
<tr>
    <th colspan="5">TOTAL</th>
    <th><?= number_format($total_amount,2) ?></th>
    <th></th>
</tr>
</tfoot>
</table>
</div>

</div>

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