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

// ================= DATE RANGE =================
$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 = $conn->query("
    SELECT s.*, g.name AS guest_name, r.room_number, r.room_type, r.price AS room_price
    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
");

// 🔥 Generate a random stay_id for testing (from existing stays)
$random_stay = $conn->query("SELECT id FROM stays ORDER BY RAND() LIMIT 1")->fetch_assoc();
$random_stay_id = $random_stay ? $random_stay['id'] : 0;

$random_guest_name = "Test Guest";
$random_room_number = "R".rand(1,50);
$random_room_type = "Standard";
$random_room_price = 5000;
$random_days = rand(1,5);

$random_services = [
    ['name'=>'Test Service 1','amount'=>1000],
    ['name'=>'Test Service 2','amount'=>500]
];

$random_service_total = array_sum(array_column($random_services,'amount'));
$random_total = ($random_room_price*$random_days) + $random_service_total;
$random_paid = 0;
$random_balance = $random_total - $random_paid;
?>

<div class="container mt-4">

<h4>Completed Checkouts (Unpaid Only)</h4>

<form method="POST" action="bulk_invoice.php" target="_blank">

<div class="mb-3">

<button class="btn btn-dark">
    <i class="fa fa-layer-group"></i>
    Generate Combined CheckedOut Invoice
</button>

<a href="generate_stays_invoice.php"
class="btn btn-primary">

<i class="fa fa-file-invoice-dollar"></i>
Generate Stays Invoice

</a>

</div>

<table class="table table-bordered table-sm">
<thead class="table-dark">
<tr>
    <th><input type="checkbox" id="select_all"></th>
    <th>Guest</th>
    <th>Room</th>
    <th>CheckIn</th>
    <th>CheckOut</th>
    <th>Total</th>
    <th>Paid</th>
    <th>Balance</th>
</tr>
</thead>

<tbody>

<!-- 🔥 Random Test Row -->
<tr style="background:#f9f9f9;">
     <td>
        <input type="checkbox" name="stay_ids[]" value="<?= $random_stay_id ?>">
    </td>
    <td><?= $random_guest_name ?></td>
    <td><?= $random_room_number ?> (<?= $random_room_type ?>)</td>
    <td>01/01/2026</td>
    <td>03/01/2026</td>
    <td><?= number_format($random_total,2) ?></td>
    <td><?= number_format($random_paid,2) ?></td>
    <td class="text-danger fw-bold"><?= number_format($random_balance,2) ?></td>
</tr>

<?php while($s = $completed_checkouts->fetch_assoc()):

    // SAFE DATES
    $checkin  = !empty($s['checkin_date']) ? date('d/m/Y', strtotime($s['checkin_date'])) : '-';
    $checkout = !empty($s['checkout_date']) ? date('d/m/Y', strtotime($s['checkout_date'])) : '-';

    // COSTS
    $room_cost = $s['room_price'] * $s['days'];

    $services = $conn->query("SELECT amount FROM charges WHERE guest_id={$s['guest_id']}");
    $service_total = 0;
    while($srv = $services->fetch_assoc()){
        $service_total += $srv['amount'];
    }

    $total = $room_cost + $service_total;

    $paid = $conn->query("
        SELECT COALESCE(SUM(amount),0) as total 
        FROM payments 
        WHERE guest_id={$s['guest_id']} AND status='Paid'
    ")->fetch_assoc()['total'];

    $balance = $total - $paid;

    // 🔥 ONLY UNPAID
    if($balance <= 0) continue;
?>

<tr>
    <td>
        <input type="checkbox" name="stay_ids[]" value="<?= $s['id'] ?>">
    </td>
    <td><?= htmlspecialchars($s['guest_name']) ?></td>
    <td><?= $s['room_number'] ?></td>
    <td><?= $checkin ?></td>
    <td><?= $checkout ?></td>
    <td><?= number_format($total,2) ?></td>
    <td><?= number_format($paid,2) ?></td>
    <td class="text-danger fw-bold"><?= number_format($balance,2) ?></td>
</tr>

<?php endwhile; ?>
</tbody>
</table>

</form>
</div>

<script>
document.getElementById('select_all').addEventListener('click', function(){
    document.querySelectorAll('input[name="stay_ids[]"]').forEach(cb => {
        cb.checked = this.checked;
    });
});

// validate
document.querySelector("form").addEventListener("submit", function(e){
    let checked = document.querySelectorAll('input[name="stay_ids[]"]:checked');
    if(checked.length === 0){
        alert("Select at least one record");
        e.preventDefault();
    }
});
</script>

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