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

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

// ================= FILTERS =================
// Default to today if empty
$from_date = $_GET['from'] ?? $today;
$to_date   = $_GET['to'] ?? $today;
$status    = $_GET['status'] ?? '';
$guest_id  = $_GET['guest_id'] ?? '';
$search    = $_GET['search'] ?? '';

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

if($from_date){
    $where[] = "DATE(i.issue_date) >= '".$conn->real_escape_string($from_date)."'";
}
if($to_date){
    $where[] = "DATE(i.issue_date) <= '".$conn->real_escape_string($to_date)."'";
}
if($status){
    $where[] = "i.status = '".$conn->real_escape_string($status)."'";
}
if($guest_id){
    $where[] = "i.guest_id = '".$conn->real_escape_string($guest_id)."'";
}
if($search){
    $s = $conn->real_escape_string($search);
    $where[] = "(i.invoice_number LIKE '%$s%' OR i.description LIKE '%$s%')";
}

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

// ================= FETCH INVOICES =================
$query = "
SELECT i.*, g.name AS guest_name
FROM invoices i
LEFT JOIN guests g ON g.id = i.guest_id
$where_sql
ORDER BY i.issue_date DESC
";

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

// ================= SUMMARY =================
$summary = $conn->query("
SELECT 
    COUNT(*) AS total_invoices,
    IFNULL(SUM(total_amount),0) AS total_amount,
    SUM(CASE WHEN status='Paid' THEN 1 ELSE 0 END) AS paid_count,
    SUM(CASE WHEN status='Unpaid' THEN 1 ELSE 0 END) AS unpaid_count,
    SUM(CASE WHEN status='Partially Paid' THEN 1 ELSE 0 END) AS partial_count
FROM invoices i
$where_sql
")->fetch_assoc();

$total_invoices = $summary['total_invoices'] ?? 0;
$total_amount   = $summary['total_amount'] ?? 0;
$paid_count     = $summary['paid_count'] ?? 0;
$unpaid_count   = $summary['unpaid_count'] ?? 0;
$partial_count  = $summary['partial_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-file-invoice text-primary"></i> Invoices Report
    </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="status" class="form-control">
                <option value="">All Statuses</option>
                <option <?= $status=='Paid'?'selected':'' ?>>Paid</option>
                <option <?= $status=='Unpaid'?'selected':'' ?>>Unpaid</option>
                <option <?= $status=='Partially Paid'?'selected':'' ?>>Partially Paid</option>
            </select>
        </div>
        <div class="col-md-3">
            <input type="text" name="search" class="form-control" placeholder="Search invoice / description" value="<?= htmlspecialchars($search) ?>">
        </div>
        <div class="col-md-3 d-flex gap-1">
            <button class="btn btn-primary w-100"><i class="fa fa-filter"></i> Filter</button>
            <a href="invoices_report.php" class="btn btn-secondary w-100"><i class="fa fa-undo"></i> Reset</a>
        </div>
    </form>

    <!-- ================= ACTION BUTTONS ================= -->
    <div class="mb-3 no-print d-flex gap-2">
        <a href="export_invoices_excel.php?from=<?= urlencode($from_date) ?>&to=<?= urlencode($to_date) ?>&status=<?= urlencode($status) ?>&search=<?= urlencode($search) ?>" class="btn btn-success">
            <i class="fa fa-file-excel"></i> Export Excel
        </a>
        <button onclick="window.print()" class="btn btn-info"><i class="fa fa-print"></i> Print / PDF</button>
    </div>

    <!-- ================= 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><i class="fa fa-file-invoice"></i> Total Invoices</h6>
                    <h4 class="text-primary"><?= $total_invoices ?></h4>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card report-card shadow-sm">
                <div class="card-body">
                    <h6><i class="fa fa-money-bill-wave"></i> Total Amount (MK)</h6>
                    <h4 class="text-dark"><?= 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><i class="fa fa-check-circle text-success"></i> Paid</h6>
                    <h4 class="text-success"><?= $paid_count ?></h4>
                </div>
            </div>
        </div>
        <div class="col-md-2">
            <div class="card report-card shadow-sm">
                <div class="card-body">
                    <h6><i class="fa fa-times-circle text-warning"></i> Unpaid</h6>
                    <h4 class="text-warning"><?= $unpaid_count ?></h4>
                </div>
            </div>
        </div>
        <div class="col-md-2">
            <div class="card report-card shadow-sm">
                <div class="card-body">
                    <h6><i class="fa fa-exclamation-circle text-info"></i> Partially Paid</h6>
                    <h4 class="text-info"><?= $partial_count ?></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><i class="fa fa-hashtag"></i> Invoice Number</th>
                    <th><i class="fa fa-user"></i> Guest</th>
                    <th><i class="fa fa-money-bill"></i> Total Amount</th>
                    <th><i class="fa fa-info-circle"></i> Status</th>
                    <th><i class="fa fa-calendar-alt"></i> Issue Date</th>
                    <th><i class="fa fa-calendar-day"></i> Due Date</th>
                    <th><i class="fa fa-align-left"></i> Description</th>
                    <th><i class="fa fa-user-edit"></i> Created 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_name'] ?? $row['guest_id']) ?></td>
                            <td><?= number_format($row['total_amount'],2) ?></td>
                            <td><?= htmlspecialchars($row['status']) ?></td>
                            <td><?= $row['issue_date'] ?></td>
                            <td><?= $row['due_date'] ?></td>
                            <td><?= $row['description'] ?></td>
                            <td><?= $row['created_by'] ?></td>
                        </tr>
                    <?php endwhile; ?>
                <?php else: ?>
                    <tr><td colspan="8" class="text-center text-danger">No records found</td></tr>
                <?php endif; ?>
            </tbody>
            <tfoot class="table-dark">
                <tr>
                    <th colspan="2"><i class="fa fa-calculator"></i> TOTAL</th>
                    <th><?= number_format($total_amount,2) ?></th>
                    <th colspan="5"></th>
                </tr>
            </tfoot>
        </table>
    </div>
</div>

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