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

// ================= SUMMARY DATA =================
$reserved_rooms = $conn->query("SELECT COUNT(*) AS total FROM reservations WHERE status='Reserved'")->fetch_assoc()['total'];
$occupied_rooms = $conn->query("SELECT COUNT(*) AS total FROM rooms WHERE status='Occupied'")->fetch_assoc()['total'];
$available_rooms = $conn->query("SELECT COUNT(*) AS total FROM rooms WHERE status='Available'")->fetch_assoc()['total'];
$checked_in_guests = $conn->query("SELECT COUNT(*) AS total FROM stays WHERE checkout_date IS NULL")->fetch_assoc()['total'];
$total_guests = $conn->query("SELECT COUNT(*) AS total FROM guests")->fetch_assoc()['total'];
$total_payments = $conn->query("SELECT IFNULL(SUM(amount), 0) AS total
FROM payments
WHERE status = 'Paid'
  AND DATE(payment_date) = CURDATE(); ")->fetch_assoc()['total'];
$pending_payments = $conn->query("
    SELECT IFNULL(SUM(r.payment_amount - IFNULL(p.total_paid,0)),0) AS pending
    FROM reservations r
    LEFT JOIN (
        SELECT guest_id, SUM(amount) AS total_paid
        FROM payments WHERE status='Paid'
        GROUP BY guest_id
    ) p ON r.guest_id=p.guest_id
")->fetch_assoc()['pending'];
$open_bar_guests = $conn->query("SELECT COUNT(DISTINCT guest_id) AS total FROM bar_tabs WHERE status='Open'")->fetch_assoc()['total'];

// ================= FETCH CURRENT CHECK-INS =================
$stays = $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.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-3">
     <button class="btn btn-secondary btn-custom mb-3" onclick="history.back()">
     <i class="fa fa-arrow-left"></i> Back
 </button>
    <h3><i class="fa fa-users"></i> Guest Management</h3>
    <hr>

    <!-- ================= DASHBOARD CARDS ================= -->
    <div class="row">
        <?php 
        $cards = [
            ['Reserved Rooms','primary',$reserved_rooms,'fa-bed'],
            ['Occupied Rooms','warning',$occupied_rooms,'fa-door-closed'],
            ['Available Rooms','success',$available_rooms,'fa-door-open'],
            ['Checked-In Guests','info',$checked_in_guests,'fa-user-check'],
            ['Total Guests','secondary',$total_guests,'fa-users'],
            ['Payments Received','success',number_format($total_payments,2).' MK','fa-money-bill-wave'],
            ['Pending Payments','danger',number_format($pending_payments,2).' MK','fa-exclamation-triangle'],
            ['Guests With Open Bar Tabs','danger',$open_bar_guests,'fa-cocktail']
        ];
        foreach($cards as $c):
        ?>
        <div class="col-md-3 col-sm-6 mb-3">
            <div class="card text-white bg-<?= $c[1] ?> h-100">
                <div class="card-body p-2">
                    <h6 class="card-title mb-1"><?= $c[0] ?></h6>
                    <p class="card-text fs-5 fw-bold"><?= $c[2] ?></p>
                    <i class="fa <?= $c[3] ?> fa-lg"></i>
                </div>
            </div>
        </div>
        <?php endforeach; ?>
    </div>

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

    <table class="table table-bordered table-striped table-sm" id="checkinTable">
        <thead class="bg-dark text-white">
            <tr>
                <th>#</th>
                <th>Guest</th>
                <th>Room</th>
                <th>Type</th>
                <th>Check-In</th>
                <th>Days</th>
                <th>Checkout</th>
                <th>Total</th>
                <th>Paid</th>
                <th>Balance</th>
                <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 = $s['room_price'] * $s['days'];
            $service_total = $conn->query("SELECT SUM(amount) AS total_charges FROM charges WHERE guest_id={$s['guest_id']}")->fetch_assoc()['total_charges'] ?? 0;
            $total_amount = $room_cost + $service_total;
            $paid_amount = $conn->query("SELECT SUM(amount) AS total_paid FROM payments WHERE guest_id={$s['guest_id']} AND status='Paid'")->fetch_assoc()['total_paid'] ?? 0;
            $balance = $total_amount - $paid_amount;
            $elapsed = max(0,min(100,(($now - $checkin_time)/($checkout_time - $checkin_time))*100));
            $overdue = ($now > $checkout_time);
            $open_tab = $conn->query("SELECT id FROM bar_tabs WHERE guest_id={$s['guest_id']} AND status='Open' LIMIT 1")->num_rows > 0;
        ?>
        <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' ?>" style="width:<?= $elapsed ?>%">
                        <?= number_format($elapsed,0) ?>%
                    </div>
                </div>
            </td>
            <td>
                <a href="add_services.php?stay_id=<?= $s['stay_id'] ?>" class="btn btn-info btn-sm" title="Add Services"><i class="fa fa-concierge-bell"></i></a>
                <a href="invoice.php?stay_id=<?= $s['stay_id'] ?>" class="btn btn-dark btn-sm" title="Invoice"><i class="fa fa-file-invoice-dollar"></i></a>
                <a href="receive_payment.php?guest_id=<?= $s['guest_id'] ?>&stay_id=<?= $s['stay_id'] ?>" class="btn btn-success btn-sm"><i class="fa fa-money-bill-wave"></i></a>
                <?php if($open_tab): ?>
                    <button class="btn btn-danger btn-sm" onclick="alert('Guest has unpaid bar tab!');"><i class="fa fa-ban"></i></button>
                <?php else: ?>
                
                <?php endif; ?>
                
            </td>
        </tr>
        <?php $i++; endwhile; ?>
        </tbody>
    </table>
</div>

<script>
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'; ?>
