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

/* =====================================================
   📧 EMAIL FUNCTION
===================================================== */
function sendCheckinAlert($guest_name, $room_id, $days){

    $to_emails = [
        'giantplusmw@gmail.com',
        'rams.investments@gmail.com'
    ];

    $subject = "New Guest Check-In Alert";

    $message = "
    <html>
    <head>
        <style>
            body{font-family:Arial;background:#f4f6f9;padding:20px;}
            .box{background:#ffffff;padding:20px;border-radius:8px;}
            .title{color:#198754;font-size:18px;font-weight:bold;}
            .footer{font-size:12px;color:#777;margin-top:15px;}
        </style>
    </head>
    <body>
        <div class='box'>
            <div class='title'>✅ Guest Checked In</div>
            <p><strong>Guest:</strong> {$guest_name}</p>
            <p><strong>Room ID:</strong> {$room_id}</p>
            <p><strong>Days:</strong> {$days}</p>
            <p><strong>Checked-In By:</strong> ".htmlspecialchars($_SESSION['username'] ?? 'System')."</p>
            <p><strong>Time:</strong> ".date('Y-m-d H:i:s')."</p>
            <div class='footer'>RAMS Executive Lodge System</div>
        </div>
    </body>
    </html>
    ";

    $headers  = "MIME-Version: 1.0\r\n";
    $headers .= "Content-type:text/html;charset=UTF-8\r\n";
    $headers .= "From: cloud@gianterp.space\r\n";

    foreach($to_emails as $to){
        @mail($to, $subject, $message, $headers);
    }
}



// ================= EXPIRED STAYS CHECK =================
$expired_guests = [];

$expired_query = $conn->query("
    SELECT s.id, g.name, s.checkin_date, s.days
    FROM stays s
    JOIN guests g ON s.guest_id = g.id
    WHERE s.checkout_date IS NULL
");

while($row = $expired_query->fetch_assoc()){

    $checkin_time = strtotime($row['checkin_date']);
    $checkout_time = strtotime("+{$row['days']} days", $checkin_time);

    if(time() > $checkout_time){
        $expired_guests[] = $row['name'];
    }
}?>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script>

let expiredGuests = <?php echo json_encode($expired_guests); ?>;

function showCheckoutReminder() {

    if (expiredGuests.length > 0) {

        let guestListHTML = "<ul style='text-align:left'>";
        expiredGuests.forEach(function(name){
            guestListHTML += "<li><strong>" + name + "</strong></li>";
        });
        guestListHTML += "</ul>";

        let audio = new Audio("https://actions.google.com/sounds/v1/alarms/alarm_clock.ogg");
        audio.play();

        Swal.fire({
            title: '⚠ Stay Expired!',
            html: `
                <p>The following guest(s) need checkout:</p>
                ${guestListHTML}
                <p style="color:red;font-weight:bold;margin-top:10px;">
                    Please process checkout immediately and Recieve Payment.
                </p>
            `,
            icon: 'warning',
            confirmButtonText: 'OK',
            confirmButtonColor: '#d33'
        });
    }
}

window.addEventListener("load", function(){
    showCheckoutReminder();
});

setInterval(function(){
    showCheckoutReminder();
}, 30000);

</script>
<?php 

/* =====================================================
   📊 SUMMARY CARDS
===================================================== */

$reserved_rooms = $conn->query("SELECT COUNT(*) as total FROM reservations WHERE status='Reserved'")->fetch_assoc()['total'];

$total_payments = $conn->query("
    SELECT SUM(amount) AS total 
    FROM payments 
    WHERE status = 'Paid'
    AND DATE(payment_date) = CURDATE()
")->fetch_assoc()['total'] ?? 0;

$occupied_rooms = $conn->query("SELECT COUNT(*) as total FROM rooms WHERE status='Occupied'")->fetch_assoc()['total'];

$checked_in_guests = $conn->query("SELECT COUNT(*) as total FROM stays WHERE checkout_date IS NULL")->fetch_assoc()['total'];

/* =====================================================
   🏨 CHECK-IN PROCESS
===================================================== */

if(isset($_POST['checkin'])){

    // ================= MULTIPLE CHECK-IN =================
    if(isset($_POST['guest_ids']) && is_array($_POST['guest_ids'])){

        $conn->begin_transaction();

        try {

            foreach($_POST['guest_ids'] as $guest_id){

                $guest_id = intval($guest_id);

                $res = $conn->query("
                    SELECT id, room_id, date_in, date_out
                    FROM reservations
                    WHERE guest_id=$guest_id
                    AND status='Reserved'
                    ORDER BY id DESC
                    LIMIT 1
                ")->fetch_assoc();

                if(!$res) continue;

                $room_id = intval($res['room_id']);

                $days = max(
                    1,
                    intval((strtotime($res['date_out']) - strtotime($res['date_in'])) / 86400)
                );

                // update room
                $conn->query("UPDATE rooms SET status='Occupied' WHERE id=$room_id");

                // insert stay
                $stmt = $conn->prepare("
                    INSERT INTO stays (guest_id, room_id, checkin_date, days)
                    VALUES (?,?,NOW(),?)
                ");
                $stmt->bind_param("iii",$guest_id,$room_id,$days);
                $stmt->execute();

                // mark reservation
                $conn->query("UPDATE reservations SET status='Checked-In' WHERE id=".$res['id']);

                // ✅ GET GUEST NAME
                $guest_row = $conn->query("SELECT name FROM guests WHERE id=$guest_id")->fetch_assoc();
                $guest_name = $guest_row['name'] ?? 'Guest';

                // ✅ SEND EMAIL
                sendCheckinAlert($guest_name, $room_id, $days);
            }

            $conn->commit();

            echo "<script>alert('Selected guests checked in successfully');window.location='checkin.php';</script>";
            exit;

        } catch(Exception $e){
            $conn->rollback();
            echo "<script>alert('Error during check-in. Please try again.');window.location='checkin.php';</script>";
            exit;
        }

    } else {

        // ================= SINGLE CHECK-IN =================

        $guest_id = intval($_POST['guest_id']);
        $room_id  = intval($_POST['room_id']);
        $days     = max(1, intval($_POST['days']));
        $checkin_date = $_POST['checkin_date'] ?? date('Y-m-d H:i:s');
        $checkin_date = date('Y-m-d H:i:s', strtotime($checkin_date));

        $conn->query("UPDATE rooms SET status='Occupied' WHERE id=$room_id");

$created_by = $_SESSION['username'] ?? 'System';
      $stmt = $conn->prepare("
    INSERT INTO stays (guest_id, room_id, checkin_date, days,created_by)
    VALUES (?,?,?,?,?)
");

$stmt->bind_param("iisis",$guest_id,$room_id,$checkin_date,$days,$created_by);
        $stmt->execute();

        // ✅ GET GUEST NAME
        $guest_row = $conn->query("SELECT name FROM guests WHERE id=$guest_id")->fetch_assoc();
        $guest_name = $guest_row['name'] ?? 'Guest';

        // ✅ SEND EMAIL
        sendCheckinAlert($guest_name, $room_id, $days);

        echo "<script>alert('Guest checked in');window.location='checkin.php';</script>";
        exit;
    }
}

// ================= COMPLETED CHECKOUTS =================
$completed_checkouts = $conn->query("
    SELECT s.id AS stay_id,
           g.name AS guest_name,
           r.room_number,
           r.room_type,
           s.checkin_date,
           s.checkout_date,
           IFNULL(r.price,0) AS room_price,
           COALESCE((
               SELECT SUM(amount)
               FROM payments
               WHERE guest_id = s.guest_id
                 AND type IN ('Bar','Restaurant','Room Service')
           ),0) AS service_cost
    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 AND g.status= 2
    ORDER BY s.checkout_date DESC
");

// ================= FETCH DATA =================
$guests = $conn->query("SELECT * FROM guests WHERE status= 2 ORDER BY name");
$rooms  = $conn->query("SELECT * FROM rooms ORDER BY status, room_number");

// Fetch current stays (not checked out)
$stays = $conn->query("
    SELECT s.id AS 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.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 NULL
    ORDER BY s.checkin_date DESC
");
?>

<div class="container mt-4">
    <div class="welcome-msg">
        <i class="fa fa-user-circle"></i> Welcome, <strong><?= htmlspecialchars($_SESSION['username'] ?? 'Guest') ?></strong>!
    </div>
<h4><i class="fa fa-sign-in-alt"></i> Guest Check-In</h4>
<div class="checkout-reminder">
    <i class="fa fa-exclamation-triangle"></i>
    <strong>Reminder:</strong>
    Receive payment before check-In.Also select Checkin Date
</div>
<hr>

<!-- ================= SUMMARY CARDS ================= -->
<style>

    .small-card .card-body{
    padding:10px 12px;
}

.small-card .card-title{
    font-size:13px;
    margin-bottom:4px;
}

.small-card .card-text{
    font-size:18px;
    font-weight:bold;
    margin:0;
}

.small-card i{
    font-size:18px;
    opacity:0.9;
}
</style>
<div class="row mb-3 small-card justify-content-center">

    <div class="col-md-2">
        <div class="card text-white bg-primary">
            <div class="card-body d-flex justify-content-between align-items-center">
                <div>
                    <div class="card-title">Reserved</div>
                    <div class="card-text"><?= $reserved_rooms ?></div>
                </div>
                <i class="fa fa-bed"></i>
            </div>
        </div>
    </div>

    <div class="col-md-2">
        <div class="card text-white bg-success">
            <div class="card-body d-flex justify-content-between align-items-center">
                <div>
                    <div class="card-title">Payments</div>
                    <div class="card-text"><?= number_format($total_payments,2) ?></div>
                </div>
                <i class="fa fa-money-bill-wave"></i>
            </div>
        </div>
    </div>

    <div class="col-md-2">
        <div class="card text-white bg-warning">
            <div class="card-body d-flex justify-content-between align-items-center">
                <div>
                    <div class="card-title">Occupied</div>
                    <div class="card-text"><?= $occupied_rooms ?></div>
                </div>
                <i class="fa fa-door-closed"></i>
            </div>
        </div>
    </div>

    <div class="col-md-2">
        <div class="card text-white bg-danger">
            <div class="card-body d-flex justify-content-between align-items-center">
                <div>
                    <div class="card-title">Guests</div>
                    <div class="card-text"><?= $checked_in_guests ?></div>
                </div>
                <i class="fa fa-users"></i>
            </div>
        </div>
    </div>

</div>

<!-- ================= RESERVED GUESTS FOR CHECK-IN ================= -->
<h5>Guests with Reservations</h5>
<form method="POST" class="mb-4">
    <table class="table table-bordered table-striped">
        <thead class="bg-dark text-white">
            <tr>
                <th><input type="checkbox" id="selectAll"></th>
                <th>Guest Name</th>
                <th>Room Number</th>
                <th>Room Type</th>
                <th>Days Reserved</th>
                <th>Day In</th>
                <th>Day Out</th>
                <th>Days</th>
                <th>Status</th>
            </tr>
        </thead>
        <tbody>
            <?php
            $reserved_guests = $conn->query("
                SELECT 
                    r.id AS reservation_id,
                    r.created_at,
                    r.status,
                     g.status,
                    r.date_in,
                    r.date_out,
                    g.id AS guest_id,
                    g.name AS guest_name,
                    ro.room_number,
                    ro.room_type,
                    DATEDIFF(r.date_out, r.date_in) AS days
                FROM reservations r
                JOIN guests g ON r.guest_id=g.id
                JOIN rooms ro ON r.room_id=ro.id
                WHERE r.status='Reserved' AND g.status= 2
                ORDER BY r.id
            ");

            while($g = $reserved_guests->fetch_assoc()):
                $days = max(1,$g['days']);
            ?>
            <tr>
                <td>
                    <input type="checkbox" class="guest-checkbox" name="guest_ids[]" value="<?= $g['guest_id'] ?>">
                </td>
                <td><?= htmlspecialchars($g['guest_name']) ?></td>
                <td><?= $g['room_number'] ?></td>
                <td><?= $g['room_type'] ?></td>
                <td><?= $g['created_at'] ?></td>
                <td><?= $g['date_in'] ?></td>
                <td><?= $g['date_out'] ?></td>
                <td><?= $days ?></td>
                <td><?= $g['status'] ?></td>
            </tr>
            <?php endwhile; ?>
        </tbody>
    </table>

    <button type="submit" name="checkin" class="btn btn-success">
        <i class="fa fa-sign-in-alt"></i> Check-In Selected Guests
    </button>
</form>

<!-- ================= SINGLE CHECK-IN FORM ================= -->
<form method="POST" class="row g-3 mb-4">
    <div class="col-md-3">
        <label>Guest</label>
        <select name="guest_id" class="form-control" required>
            <option value="">Select Guest</option>
            <?php while($g=$guests->fetch_assoc()): ?>
                <option value="<?= $g['id'] ?>"><?= htmlspecialchars($g['name']) ?></option>
            <?php endwhile; ?>
        </select>
    </div>

  <div class="col-md-3">
    <label>Room</label>
    <?php
    $rooms_res = $conn->query("
        SELECT 
            r.id AS room_id,
            r.room_number,
            r.room_type,
            r.status,
            p.id AS pricing_id,
            p.plan_name,
            p.capacity,
            p.price
        FROM rooms r
        JOIN room_pricing p ON r.id = p.room_id
        ORDER BY r.status='Available' DESC, r.room_number
    ");
    ?>
    <select name="pricing_id" class="form-control" required id="pricingSelect">
        <option value="">Select Room</option>

        <?php 
        while($r = $rooms_res->fetch_assoc()):

            $status = $r['status'];
            $disabled = ($status != 'Available') ? 'disabled' : '';

            switch($status){
                case 'Available': $status_icon = "🟢 Vacant"; break;
                case 'Occupied': $status_icon = "🔴 Occupied"; break;
                case 'Reserved': $status_icon = "🟡 Reserved"; break;
                case 'Maintenance': $status_icon = "⚫ Maintenance"; break;
                case 'Dirty': $status_icon = "🟣 Dirty"; break;
                case 'Out of Order': $status_icon = "⛔ Out of Order"; break;
                default: $status_icon = $status;
            }
        ?>
            <option value="<?= $r['pricing_id'] ?>" 
                    data-room-id="<?= $r['room_id'] ?>" 
                    <?= $disabled ?>>
                <?= $status_icon ?> | 
                Room <?= $r['room_number'] ?> 
                (<?= $r['plan_name'] ?> - <?= $r['capacity'] ?> Person<?= $r['capacity']>1?'s':'' ?>)
                - MK <?= number_format($r['price'],2) ?>
            </option>
        <?php endwhile; ?>
    </select>

    <!-- hidden field for room_id -->
    <input type="hidden" name="room_id" id="room_id_hidden" value="">
</div>

<!-- ==================== JS to populate hidden room_id ==================== -->
<script>
document.getElementById('pricingSelect').addEventListener('change', function() {
    let selectedOption = this.options[this.selectedIndex];
    document.getElementById('room_id_hidden').value = selectedOption.dataset.roomId || '';
});
</script>
<div class="col-md-2">
    <label><b>Check-In Date</b></label>
    <input required type="datetime-local" name="checkin_date" class="form-control"
           value="<?= date('Y-m-d\TH:i') ?>">
</div>

    <div class="col-md-2">
        <label>Days</label>
        <input type="number" name="days" class="form-control" value="1" min="1">
    </div>

    <div class="col-md-2 d-flex align-items-end">
        <button name="checkin" class="btn btn-success w-100">
            <i class="fa fa-sign-in-alt"></i> Check-In
        </button>
    </div>

    
</form>

<!-- ================= CURRENT CHECK-INS ================= -->
<h5>Current Check-Ins</h5>
<input class="form-control mb-2" id="searchInput" placeholder="Search guest or room..." onkeyup="filterTable()">

<style>
#checkinTable {
    font-size: 0.85rem;
}
#checkinTable th,
#checkinTable td {
    padding: 6px 8px;
}
.pagination {
    justify-content: center;
}
</style>
<div class="checkout-reminder">
    <i class="fa fa-exclamation-triangle"></i>
    <strong>Reminder:</strong>
    Make sure you checkout guests once they complete their stay to ensure rooms are marked vacant.
</div>

<style>
.checkout-reminder{
    background: linear-gradient(135deg, #fff3cd, #ffe69c);
    border-left: 6px solid #ffc107;
    color: #664d03;
        border: 2px solid #dc3545;          /* ✅ RED BORDER */
    padding: 6px 10px;
    border-radius: 10px;
    font-size: 0.95rem;
    margin-bottom: 15px;
    box-shadow: 0 2px 8px rgba(0,0,0,0.08);
    display: flex;
    align-items: center;
    gap: 10px;
}

.checkout-reminder i{
    font-size: 20px;
    color: #ff9800;
}

/* subtle animation */
.checkout-reminder{
    animation: fadeInReminder .4s ease-in-out;
}

@keyframes fadeInReminder{
    from{opacity:0; transform: translateY(-5px);}
    to{opacity:1; transform: translateY(0);}
}
</style>
<table class="table table-bordered table-striped" id="checkinTable">
    <thead class="bg-dark text-white">
        <tr>
            <th>#</th>
            <th>Guest</th>
            <th>Room</th>
            <th>Room Type</th>
            <th>Check-In</th>
            <th>Days</th>
            <th>Checkout</th>
            <th>Total</th>
            <th>Paid</th>          <!-- ✅ ADDED -->
<th>Balance</th>       <!-- ✅ ADDED -->
            <th>Progress</th>
            <th>Action</th>
        </tr>
    </thead>
    <tbody>
<?php 
$i=1; 
while($s=$stays->fetch_assoc()): 
  

$checkin_time = strtotime($s['checkin_date']);
$checkout_time = strtotime("+{$s['days']} days", $checkin_time);
$now = time();

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

// ================= SERVICE COST =================
$service_res = $conn->query("
    SELECT SUM(amount) AS total_charges
    FROM charges
    WHERE guest_id={$s['guest_id']}
");
$service_total = ($service_res && $row = $service_res->fetch_assoc()) ? floatval($row['total_charges']) : 0;

// ================= TOTAL AMOUNT =================
$total_amount = $room_cost + $service_total;

// ================= PAID AMOUNT =================
$paid_res = $conn->query("
    SELECT SUM(amount) AS total_paid
    FROM payments
    WHERE guest_id={$s['guest_id']} AND status='Paid'
");
$paid_amount = ($paid_res && $row_paid = $paid_res->fetch_assoc()) ? floatval($row_paid['total_paid']) : 0;

// ================= BALANCE =================
$balance = $total_amount - $paid_amount;

// ================= OPEN BAR TAB CHECK =================
$open_tab_check = $conn->query("
    SELECT id 
    FROM bar_tabs 
    WHERE guest_id = {$s['guest_id']} 
    AND status = 'Open'
    LIMIT 1
");
$has_open_tab = ($open_tab_check && $open_tab_check->num_rows > 0);

// ================= STAY DURATION FOR PROGRESS BAR =================
$total_stay_seconds = $checkout_time - $checkin_time;
$elapsed = ($total_stay_seconds > 0) ? max(0, min(100, (($now - $checkin_time) / $total_stay_seconds) * 100)) : 0;
$overdue = ($now > $checkout_time);

?>
<tr <?= $overdue ? 'class="table-danger"' : '' ?>>
   
  <td><?= $i ?></td>
    <td><?= htmlspecialchars($s['guest_name']) ?></td>
    <td><?= $s['room_number'] ?></td>
    <td><?= $s['room_type'] ?></td>
    <td><?= date('Y-m-d H:i', $checkin_time) ?></td>
    <td><?= $s['days'] ?></td>
    <td><?= date('Y-m-d', $checkout_time) ?></td>
    <td><?= number_format($total_amount,2) ?></td>
    <td><?= number_format($paid_amount,2) ?></td>
    <td><?= number_format($balance,2) ?></td>


    <td>
        <div class="progress" style="height:15px;">
            <div class="progress-bar <?= $overdue ? 'bg-danger' : 'bg-success' ?>" 
                 role="progressbar" style="width:<?= $elapsed ?>%">
                <?= number_format($elapsed,0) ?>%
            </div>
        </div>
    </td>

<td>

<a href="add_services.php?stay_id=<?= $s['id'] ?>" 
   class="btn btn-info btn-sm" title="Add Services">
    <i class="fa fa-concierge-bell"></i> Services
</a>
<!-- ✅ NEW: Invoice Button -->
<a href="invoice.php?stay_id=<?= $s['id'] ?>" 
   class="btn btn-dark btn-sm" title="Generate Invoice">
    <i class="fa fa-file-invoice-dollar"></i> Invoice
</a>

<!-- EDIT STAY -->
<a href="edit_stay.php?stay_id=<?= $s['id'] ?>" 
   class="btn btn-warning btn-sm" title="Edit Stay">
   <i class="fa fa-edit"></i> Edit
</a>

<!-- ✅ Transfer Room Button -->
<a href="transfer_room.php?stay_id=<?= $s['id'] ?>" 
   class="btn btn-warning btn-sm" 
   title="Transfer Room">
   <i class="fa fa-exchange-alt"></i> Transfer
</a>







</td>


</tr>
<?php $i++; endwhile; ?>
    </tbody>
</table>
<br/>

<h5 class="mt-5">Completed Checkouts</h5>
<input class="form-control mb-2" id="checkoutSearch" placeholder="Search guest or room..." onkeyup="filterCheckoutTable()">

<table class="table table-bordered table-striped" id="checkoutTable">
    <thead class="bg-secondary text-white">
        <tr>
            <th>#</th>
            <th>Guest</th>
            <th>Room</th>
            <th>Room Type</th>
            <th>Check-In</th>
            <th>Check-Out</th>
            <th>Days Stayed</th>
            <th>Total Room Cost (MK)</th>
            <th>Service Cost (MK)</th>
            <th>Total Amount (MK)</th>
        </tr>
    </thead>
    <tbody>
    <?php 
$i=1; 
while($s=$stays->fetch_assoc()): 
    $open_tab_check = $conn->query("
        SELECT id 
        FROM bar_tabs 
        WHERE guest_id = {$s['guest_id']} 
        AND status = 'Open'
        LIMIT 1
    ");
    $has_open_tab = ($open_tab_check && $open_tab_check->num_rows > 0);

    $checkin_time = strtotime($s['checkin_date']);
    $checkout_time = strtotime("+{$s['days']} days", $checkin_time);
    $now = time();

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

    // ================= SERVICE COST INCLUDING CHARGES =================
    $service_cost = 0;

    // Charges from add_services.php
    $charges_res = $conn->query("
        SELECT SUM(amount) as total_charges 
        FROM charges 
        WHERE guest_id={$s['guest_id']}
    ");
    $charges_total = ($charges_res && $row = $charges_res->fetch_assoc()) ? floatval($row['total_charges']) : 0;

    // Optional: include payments of type Bar/Restaurant/Room Service if you want
    $payments_res = $conn->query("
        SELECT SUM(amount) as total_paid_services 
        FROM payments 
        WHERE guest_id={$s['guest_id']} 
        AND type IN ('Bar','Restaurant','Room Service')
    ");
    $payments_total = ($payments_res && $row = $payments_res->fetch_assoc()) ? floatval($row['total_paid_services']) : 0;

    // Use only charges for total (so the amount reflects added services/items)
    $service_cost = $charges_total; // or $charges_total + $payments_total if you want all-inclusive

    // Total amount for guest
    $total_amount = $room_cost + $service_cost;

    // ================= PAID AMOUNT =================
    $paid_amount = 0;
    $paid_res = $conn->query("
        SELECT SUM(amount) as total_paid
        FROM payments
        WHERE guest_id={$s['guest_id']}
        AND status='Paid'
    ");

    if($paid_res && $row_paid = $paid_res->fetch_assoc()){
        $paid_amount = floatval($row_paid['total_paid']);
    }

    // ================= BALANCE =================
    $balance = $total_amount - $paid_amount;

    $total_stay_seconds = ($checkout_time - $checkin_time);

    if ($total_stay_seconds > 0) {
        $elapsed = max(0, min(100, (($now - $checkin_time) / $total_stay_seconds) * 100));
    } else {
        $elapsed = 0;
    }

    $overdue = ($now > $checkout_time);
?>
<tr <?= $overdue ? 'class="table-danger"' : '' ?>>
    <td><?= $i ?></td>
    <td><?= htmlspecialchars($s['guest_name']) ?></td>
    <td><?= $s['room_number'] ?></td>
    <td><?= $s['room_type'] ?></td>
    <td><?= date('Y-m-d H:i', $checkin_time) ?></td>
    <td><?= $s['days'] ?></td>
    <td><?= date('Y-m-d', $checkout_time) ?></td>
    <td><?= number_format($total_amount,2) ?></td>

    <!-- ✅ PAID COLUMN -->
    <td class="text-success fw-bold">
        <?= number_format($paid_amount,2) ?>
    </td>

    <!-- ✅ BALANCE COLUMN -->
    <td class="<?= $balance>0 ? 'text-danger fw-bold':'text-primary fw-bold' ?>">
        <?= number_format($balance,2) ?>
    </td>

    <td>
        <div class="progress" style="height:15px;">
            <div class="progress-bar <?= $overdue ? 'bg-danger' : 'bg-success' ?>" 
                 role="progressbar" style="width:<?= $elapsed ?>%">
                <?= number_format($elapsed,0) ?>%
            </div>
        </div>
    </td>

    <td>
        <?php if($has_open_tab): ?>
            <button class="btn btn-danger btn-sm"
                    onclick="alert('❌ Cannot checkout. Guest has unpaid bar tab.');">
                <i class="fa fa-ban"></i> Blocked
            </button>
        <?php else: ?>
            <a href="checkout.php?stay_id=<?= $s['id'] ?>" class="btn btn-primary btn-sm">
                <i class="fa fa-file-invoice"></i> Checkout
            </a>
        <?php endif; ?>

        <a href="invoice.php?stay_id=<?= $s['id'] ?>" class="btn btn-dark btn-sm" title="Generate Invoice">
            <i class="fa fa-file-invoice-dollar"></i> Invoice
        </a>

        <a href="receive_payment.php?guest_id=<?= $s['guest_id'] ?>&stay_id=<?= $s['id'] ?>" 
           class="btn btn-success btn-sm" title="Receive Payment">
            <i class="fa fa-money-bill-wave"></i> Receive
        </a>

        <a href="receipt_thermal.php?stay_id=<?= $s['id'] ?>" target="_blank" class="btn btn-secondary btn-sm" title="Thermal Receipt">
            <i class="fa fa-receipt"></i>
        </a>

        <a href="edit_stay.php?stay_id=<?= $s['id'] ?>" class="btn btn-warning btn-sm">
            <i class="fa fa-edit"></i> Edit
        </a>

        <a href="add_services.php?stay_id=<?= $s['id'] ?>" class="btn btn-info btn-sm" title="Add Services">
            <i class="fa fa-concierge-bell"></i> S
        </a>
    </td>
</tr>
<?php $i++; endwhile; ?>

    </tbody>
</table>
<script>
function filterCheckoutTable() {
    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<4; j++){ // search Guest, Room, Room Type
            if(tds[j] && tds[j].textContent.toLowerCase().includes(input)){
                show = true;
                break;
            }
        }
        tr[i].style.display = show ? "" : "none";
    }
}
</script>

</div>
<?php
// ================= EXPIRED STAYS =================
$expired_guests = [];

$expired_query = $conn->query("
    SELECT s.id, g.name, s.checkin_date, s.days
    FROM stays s
    JOIN guests g ON s.guest_id = g.id
    WHERE s.checkout_date IS NULL
");

while($row = $expired_query->fetch_assoc()){

    $checkin_time = strtotime($row['checkin_date']);
    $checkout_time = strtotime("+{$row['days']} days", $checkin_time);

    if(time() > $checkout_time){
        $expired_guests[] = $row['name'];
    }
}
?>

<script>
document.getElementById('selectAll').addEventListener('change', function() {
    let checkboxes = document.querySelectorAll('.guest-checkbox');
    checkboxes.forEach(cb => cb.checked = this.checked);
});

document.querySelectorAll('.guest-checkbox').forEach(cb => {
    cb.addEventListener('change', function() {
        if(!this.checked){
            document.getElementById('selectAll').checked = false;
        }
    });
});

function filterTable() {
    let input = document.getElementById("searchInput").value.toLowerCase();
    let table = document.getElementById("checkinTable");
    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<5; j++){
            if(tds[j] && tds[j].textContent.toLowerCase().includes(input)){
                show = true;
                break;
            }
        }
        tr[i].style.display = show ? "" : "none";
    }
}
</script>

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