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

// ================= DATE RANGE FILTER =================
// Default: yesterday and today
$default_from = date('Y-m-d', strtotime('-1 day'));
$default_to   = date('Y-m-d');

$from_date = $_GET['from'] ?? $default_from;
$to_date   = $_GET['to'] ?? $default_to;

$where_date = "";
if(isset($_GET['from']) && isset($_GET['to'])){
    $from = $conn->real_escape_string($from_date);
    $to   = $conn->real_escape_string($to_date);
    $where_date = " AND s.checkout_date BETWEEN '$from' AND '$to' ";
}

// ================= FETCH COMPLETED CHECKOUTS =================
$completed_checkouts = $conn->query("
    SELECT s.id AS stay_id,
           g.id AS guest_id,
           g.name AS guest_name,
           r.room_number,
           r.room_type,
           IFNULL(r.price,0) AS room_price,
           s.checkin_date,
           s.checkout_date,
           s.days
    FROM stays s
    JOIN guests g ON s.guest_id = g.id
    JOIN rooms r ON s.room_id = r.id
    WHERE s.checkout_date IS NOT NULL $where_date
    ORDER BY s.checkout_date DESC
");

// ================= CALCULATE TOTALS =================
$total_room_cost = 0;
$total_service_cost = 0;
$total_revenue = 0;
?>

<div class="container mt-4">

    <!-- Welcome & Summary Cards -->
    <div class="d-flex justify-content-between mb-3 flex-wrap">
        <div class="welcome-msg mb-2">
            <i class="fa fa-user-circle"></i> Welcome, <strong><?= htmlspecialchars($_SESSION['username'] ?? 'Guest') ?></strong>!
        </div>

        <div class="summary-cards d-flex gap-2 mb-2">
            <div class="card text-white bg-success p-2">
                <div>Total Revenue</div>
                <div><?= number_format($total_revenue,2) ?> MK</div>
            </div>
            <div class="card text-white bg-warning p-2">
                <div>Total Room Cost</div>
                <div><?= number_format($total_room_cost,2) ?> MK</div>
            </div>
            <div class="card text-white bg-danger p-2">
                <div>Total Outstanding</div>
                <div><?= number_format(($total_room_cost+$total_service_cost)-$total_revenue,2) ?> MK</div>
            </div>
        </div>
    </div>

    <!-- Back & View All Buttons -->
    <div class="mb-3">
        <button class="btn btn-secondary btn-custom" onclick="history.back()">
            <i class="fa fa-arrow-left"></i> Back
        </button>
        <a href="reversed_checkouts.php" class="btn btn-secondary btn-custom">
            <i class="fa fa-arrow-left"></i> Reversed Checkouts
        </a>
        <a href="checkouts.php" class="btn btn-info btn-custom">
            <i class="fa fa-eye"></i> View All
        </a>
    </div>

    <h4><i class="fa fa-file-invoice-dollar"></i> Completed Checkouts 
        (<?= htmlspecialchars($from_date) ?> to <?= htmlspecialchars($to_date) ?>)
    </h4>
    <hr>

    <!-- Filter Form -->
    <form method="get" class="row g-2 mb-3">
        <div class="col-md-3">
            <input type="date" name="from" class="form-control" value="<?= htmlspecialchars($from_date) ?>">
        </div>
        <div class="col-md-3">
            <input type="date" name="to" class="form-control" value="<?= htmlspecialchars($to_date) ?>">
        </div>
        <div class="col-md-2">
            <button type="submit" class="btn btn-primary"><i class="fa fa-filter"></i> Filter</button>
        </div>
        <div class="col-md-2">
            <button type="button" id="exportExcel" class="btn btn-success"><i class="fa fa-file-excel"></i> Export Excel</button>
        </div>
    </form>

    <!-- Search -->
    <input class="form-control mb-3" id="checkoutSearch" placeholder="Search guest, room or type..." onkeyup="filterTable()">

    <!-- Table -->
    <div class="table-responsive">
        <style>
#checkoutTable { font-size: 0.85rem; }
#checkoutTable th, #checkoutTable td { padding: 0.25rem 0.4rem; vertical-align: middle; }
#checkoutTable .btn-sm { padding: 0.2rem 0.35rem; font-size: 0.75rem; }
        </style>
        <table class="table table-bordered table-striped table-sm" id="checkoutTable">
            <thead class="bg-secondary text-white sticky-top">
                <tr>
                    <th>#</th>
                    <th>Guest</th>
                    <th>Room</th>
                    <th>Room Type</th>
                    <th>Check-In</th>
                    <th>Check-Out</th>
                    <th>Days</th>
                    <th>Room Cost</th>
                    <th>Service Cost</th>
                    <th>Total</th>
                    <th>Paid</th>
                    <th>Balance</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php 
                $i = 1; 
                while($s = $completed_checkouts->fetch_assoc()):
                    $room_cost = $s['room_price'] * $s['days'];
                    $services_res = $conn->query("SELECT name, amount FROM charges WHERE guest_id={$s['guest_id']}");
                    $service_cost = 0;
                    $services_list = "";
                    while($srv = $services_res->fetch_assoc()){
                        $service_cost += $srv['amount'];
                        $services_list .= htmlspecialchars($srv['name'])." (".number_format($srv['amount'],2)." MK)<br>";
                    }
                    $total_amount = $room_cost + $service_cost;
                    $paid_amount = floatval($conn->query("SELECT COALESCE(SUM(amount),0) AS total_paid FROM payments WHERE guest_id={$s['guest_id']} AND status='Paid'")->fetch_assoc()['total_paid']);
                    $balance = $total_amount - $paid_amount;
                    $total_room_cost += $room_cost;
                    $total_service_cost += $service_cost;
                    $total_revenue += $paid_amount;
                ?>
                <tr class="<?= $balance>0 ? 'table-warning' : 'table-success' ?>">
                    <td><?= $i ?></td>
                 <td>
    <?= $s['guest_name'] ?? '-' ?><br/>
    <?= $s['invoice_number'] ?? '-' ?>
</td>
                    <td><?= $s['room_number'] ?></td>
                    <td><?= $s['room_type'] ?></td>
                    <td><?= date('Y-m-d H:i:s', strtotime($s['checkin_date'])) ?></td>
                    <td><?= date('Y-m-d H:i:s', strtotime($s['checkout_date'])) ?></td>
                    <td><?= $s['days'] ?></td>
                    <td><?= number_format($room_cost,2) ?></td>
                    <td title="<?= $services_list ?>"><?= number_format($service_cost,2) ?></td>
                    <td><?= number_format($total_amount,2) ?></td>
                    <td><?= number_format($paid_amount,2) ?></td>
                    <td><?= number_format($balance,2) ?></td>
                    <td>
                        <a href="invoice.php?stay_id=<?= $s['stay_id'] ?>" class="btn btn-dark btn-sm" title="Print Invoice">
                            <i class="fa fa-file-invoice-dollar"></i>Invoice
                        </a>
                        <?php if($balance>0): ?>
                            <a href="receive_payment.php?guest_id=<?= $s['guest_id'] ?>" class="btn btn-success btn-sm" title="Receive Payment">
                                <i class="fa fa-credit-card"></i>Receive Payment
                            </a>
                        <?php endif; ?>
                        <a href="reverse_checkout.php?stay_id=<?= $s['stay_id'] ?>" class="btn btn-danger btn-sm" title="Reverse Checkout" onclick="return confirm('Are you sure you want to reverse this checkout?');">
                            <i class="fa fa-undo"></i>Reverse Checkout
                        </a>
                        <?php if($balance <= 0): ?>
                            <a href="receipt_thermal.php?stay_id=<?= $s['stay_id'] ?>" target="_blank" class="btn btn-secondary btn-sm">
                                <i class="fa fa-receipt"></i>Receipt
                            </a>
                        <?php endif; ?>
                    </td>
                </tr>
                <?php $i++; endwhile; ?>
            </tbody>
            <tfoot class="table-secondary">
                <tr>
                    <th colspan="7">Totals:</th>
                    <th><?= number_format($total_room_cost,2) ?></th>
                    <th><?= number_format($total_service_cost,2) ?></th>
                    <th><?= number_format($total_room_cost + $total_service_cost,2) ?></th>
                    <th><?= number_format($total_revenue,2) ?></th>
                    <th colspan="2"></th>
                </tr>
            </tfoot>
        </table>
    </div>
</div>

<!-- JavaScript -->
<script src="https://cdn.jsdelivr.net/npm/xlsx/dist/xlsx.full.min.js"></script>
<script>
function filterTable() {
    let input = document.getElementById("checkoutSearch").value.toLowerCase();
    let table = document.getElementById("checkoutTable");
    let tr = table.getElementsByTagName("tr");
    for (let i=1; i<tr.length; i++) {
        let tds = tr[i].getElementsByTagName("td");
        let show = false;
        for(let j=1; j<7; j++){
            if(tds[j] && tds[j].textContent.toLowerCase().includes(input)){
                show = true;
                break;
            }
        }
        tr[i].style.display = show ? "" : "none";
    }
}

// Export Table to Excel
document.getElementById('exportExcel').addEventListener('click', function(){
    let wb = XLSX.utils.table_to_book(document.getElementById('checkoutTable'), {sheet:"Completed Checkouts"});
    XLSX.writeFile(wb, 'Completed_Checkouts.xlsx');
});
</script>

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