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

$username = $_SESSION['username'] ?? 'Guest';
$today = date('Y-m-d');

// ================= FILTERS =================
$from_date = $_GET['from'] ?? $today;
$to_date   = $_GET['to'] ?? $today;
$method    = $_GET['method'] ?? '';
$invoice_status = $_GET['invoice_status'] ?? '';
$guest_id  = $_GET['guest_id'] ?? '';
$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($method){
    $where[] = "p.method = '".$conn->real_escape_string($method)."'";
}
if($invoice_status){
    $where[] = "i.status = '".$conn->real_escape_string($invoice_status)."'";
}
if($guest_id){
    $where[] = "p.guest_id = '".$conn->real_escape_string($guest_id)."'";
}
if($search){
    $s = $conn->real_escape_string($search);
    $where[] = "(i.invoice_number LIKE '%$s%' OR p.user_id LIKE '%$s%')";
}

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

// ================= FETCH PAYMENTS AGAINST INVOICES =================
$query = "
SELECT 
    i.invoice_number,
    i.guest_id,
    i.total_amount AS invoice_total,
    i.status AS invoice_status,
    i.issue_date,
    p.amount AS payment_amount,
    p.method AS payment_method,
    p.payment_date,
    p.user_id AS received_by
FROM payments p
INNER JOIN invoices i ON i.guest_id = p.guest_id
$where_sql
ORDER BY p.payment_date DESC
";

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

// ================= SUMMARY =================
// Totals for table and chart
$summary = $conn->query("
SELECT 
    COUNT(p.id) AS total_payments,
    IFNULL(SUM(p.amount),0) AS total_amount,
    IFNULL(SUM(i.total_amount),0) AS total_invoices,
    IFNULL(SUM(CASE WHEN p.method='Cash' THEN p.amount END),0) AS cash_total,
    IFNULL(SUM(CASE WHEN p.method='Bank' THEN p.amount END),0) AS bank_total,
    IFNULL(SUM(CASE WHEN p.method='Mobile Money' THEN p.amount END),0) AS mobile_total
FROM payments p
INNER JOIN invoices i ON i.guest_id = p.guest_id
$where_sql
")->fetch_assoc();
?>

<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;}
.chart-container{width:200px;height:200px;margin:auto;}
@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-file-invoice-dollar text-success"></i> Payments Against Invoices</h3>
    <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="method" class="form-control">
                <option value="">All Methods</option>
                <option <?= $method=='Cash'?'selected':'' ?>>Cash</option>
                <option <?= $method=='Bank'?'selected':'' ?>>Bank</option>
                <option <?= $method=='Mobile Money'?'selected':'' ?>>Mobile Money</option>
            </select>
        </div>
        <div class="col-md-2">
            <select name="invoice_status" class="form-control">
                <option value="">All Statuses</option>
                <option <?= $invoice_status=='Paid'?'selected':'' ?>>Paid</option>
                <option <?= $invoice_status=='Unpaid'?'selected':'' ?>>Unpaid</option>
                <option <?= $invoice_status=='Partially Paid'?'selected':'' ?>>Partially Paid</option>
                <option <?= $invoice_status=='Cancelled'?'selected':'' ?>>Cancelled</option>
            </select>
        </div>
        <div class="col-md-2"><input type="text" name="guest_id" class="form-control" placeholder="Guest ID" value="<?= htmlspecialchars($guest_id) ?>"></div>
        <div class="col-md-2"><input type="text" name="search" class="form-control" placeholder="Search invoice / user" value="<?= htmlspecialchars($search) ?>"></div>
        <div class="col-md-12 d-flex gap-1 mt-2">
            <button class="btn btn-primary"><i class="fa fa-filter"></i> Filter</button>
            <a href="payments_against_invoices.php" class="btn btn-secondary">Reset</a>
            <button class="btn btn-info" onclick="window.print();return false;"><i class="fa fa-print"></i> Export PDF</button>
            <a href="export_payments_invoices_excel.php?from=<?= urlencode($from_date) ?>&to=<?= urlencode($to_date) ?>&method=<?= urlencode($method) ?>&invoice_status=<?= urlencode($invoice_status) ?>&guest_id=<?= urlencode($guest_id) ?>&search=<?= urlencode($search) ?>" class="btn btn-success"><i class="fa fa-file-excel"></i> Export Excel</a>
        </div>
    </form>

    <!-- ================= SUMMARY CARDS ================= -->
    <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"><?= $summary['total_payments'] ?></h4>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card report-card shadow-sm">
                <div class="card-body">
                    <h6>Total Payment Amount (MK)</h6>
                    <h4 class="text-dark"><?= number_format($summary['total_amount'],2) ?></h4>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card report-card shadow-sm">
                <div class="card-body">
                    <h6>Total Invoices (MK)</h6>
                    <h4 class="text-secondary"><?= number_format($summary['total_invoices'],2) ?></h4>
                </div>
            </div>
        </div>
    </div>

    <!-- ================= DOUGHNUT CHART ================= -->
    <div class="chart-container mb-4">
        <canvas id="paymentChart"></canvas>
    </div>

    <!-- ================= TABLE ================= -->
    <div class="table-responsive">
        <table class="table table-bordered table-striped table-sm">
            <thead class="table-dark">
                <tr>
                    <th>Invoice Number</th>
                    <th>Guest ID</th>
                    <th>Invoice Total</th>
                    <th>Invoice Status</th>
                    <th>Issue Date</th>
                    <th>Payment Amount</th>
                    <th>Payment Method</th>
                    <th>Payment Date</th>
                    <th>Received By</th>
                </tr>
            </thead>
            <tbody>
                <?php if($result && $result->num_rows): ?>
                    <?php while($row = $result->fetch_assoc()): ?>
                        <tr>
                            <td><?= htmlspecialchars($row['invoice_number']) ?></td>
                            <td><?= htmlspecialchars($row['guest_id']) ?></td>
                            <td><?= number_format($row['invoice_total'],2) ?></td>
                            <td><?= htmlspecialchars($row['invoice_status']) ?></td>
                            <td><?= $row['issue_date'] ?></td>
                            <td><?= number_format($row['payment_amount'],2) ?></td>
                            <td><?= htmlspecialchars($row['payment_method']) ?></td>
                            <td><?= $row['payment_date'] ?></td>
                            <td><?= $row['received_by'] ?></td>
                        </tr>
                    <?php endwhile; ?>
                <?php else: ?>
                    <tr><td colspan="9" class="text-center text-danger">No records found</td></tr>
                <?php endif; ?>
            </tbody>
            <tfoot class="table-dark">
                <tr>
                    <th colspan="5">TOTAL</th>
                    <th><?= number_format($summary['total_amount'],2) ?></th>
                    <th colspan="3"></th>
                </tr>
            </tfoot>
        </table>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
const ctx = document.getElementById('paymentChart').getContext('2d');
new Chart(ctx, {
    type: 'doughnut',
    data: {
        labels: ['Total Payments','Total Invoices'],
        datasets: [{
            data: [
                <?= $summary['total_amount'] ?? 0 ?>,
                <?= $summary['total_invoices'] - $summary['total_amount'] ?? 0 ?>
            ],
            backgroundColor: ['#28a745','#ffc107']
        }]
    },
    options: {
        responsive:true,
        plugins:{legend:{position:'bottom', labels:{boxWidth:15}}}
    }
});
</script>

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