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

$user_id = $_SESSION['user_id'] ?? 0;
$user_role = $_SESSION['role'] ?? '';

// ==================== FILTERS ====================
$status_filter = $_GET['status'] ?? '';
$room_filter   = $_GET['room'] ?? '';

$query = "
    SELECT cb.*, g.name AS guest_name, cr.name AS room_name, cr.price AS room_price
    FROM conference_bookings cb
    LEFT JOIN guests g ON cb.guest_id = g.id
    LEFT JOIN conference_rooms cr ON cb.conference_room_id = cr.id
    WHERE 1 AND cb.status='CONFIRMED'
";

if ($status_filter) {
    $safe_status = $conn->real_escape_string($status_filter);
    $query .= " AND cb.status='$safe_status'";
}
if ($room_filter) {
    $safe_room = intval($room_filter);
    $query .= " AND cb.conference_room_id=$safe_room";
}

$query .= " ORDER BY cb.id DESC";

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

// Fetch all conference rooms for filter dropdown
$rooms = $conn->query("SELECT * FROM conference_rooms  ORDER BY name");

// Current datetime
$now = new DateTime();
?>

<div class="container mt-4">
    <div class="welcome-msg">
        <i class="fa fa-user-circle"></i> Welcome, <strong><?= htmlspecialchars($_SESSION['username'] ?? 'Guest') ?></strong>!
    </div>

    <button class="btn btn-secondary mb-3" onclick="history.back()">
        <i class="fa fa-arrow-left"></i> Back
    </button>

 


    <h3 class="text-center mb-4">📋 Conference Bookings</h3>
    <hr>

    <!-- Filters -->
   

    <!-- Bookings Table -->
    <table class="table table-bordered table-striped">
        <thead class="bg-dark text-white">
            <tr>
                <th>#Booking ID</th>
                <th>Client</th>
                <th>Room</th>
               
                <th>Start Date</th>
                <th>End Date</th>
                <th>Attendees</th>
               
                <th>Status</th>
               
                <th>Actions</th>
            </tr>
        </thead>
        <tbody>
        <?php if($bookings->num_rows > 0): ?>
            <?php while($b = $bookings->fetch_assoc()): ?>
                <?php
                    $booking_start = new DateTime($b['booking_date']);
                    $booking_end = clone $booking_start;
                    $booking_end->modify('+'.($b['num_days']-1).' days');

                    // Progress %
                    $total_days = $b['num_days'];
                    $elapsed_days = max(0, min($total_days, $now->diff($booking_start)->days));
                    if ($now < $booking_start) $elapsed_days = 0;
                    if ($now > $booking_end) $elapsed_days = $total_days;
                    $progress = ($total_days > 0) ? ($elapsed_days/$total_days)*100 : 0;

                    $can_start = ($now >= $booking_start && $now <= $booking_end && $b['status']=='CONFIRMED');

                    // Breakdown for tooltip
                    $room_price = $b['room_price'] ?? 0;
                    $num_days   = $b['num_days'] ?? 1;
                    $attendees  = $b['attendees'] ?? 1;
                    $total_calc = $room_price * $num_days * $attendees;
                    $tooltip = "Room Price: MK $room_price\nDays: $num_days\nAttendees: $attendees\nMK $room_price × $num_days × $attendees = MK ".number_format($total_calc,2);
                ?>
                <tr>
                    <td><?= $b['id'] ?></td>
                    <td><?= htmlspecialchars($b['client_name']) ?></td>
                    <td><?= htmlspecialchars($b['room_name'] ?? '-') ?> (<?= number_format($b['room_price'],2) ?>)</td>
                   
                    <td><?= $booking_start->format('d-m-Y') ?></td>
                    <td><?= $booking_end->format('d-m-Y') ?></td>
                    <td><?= $b['attendees'] ?></td>
                   
                    <td>
                        <?php
                            $status = $b['status'];
                            $badge_class = 'secondary';
                            if($status=='PENDING') $badge_class='warning';
                            if($status=='CONFIRMED') $badge_class='success';
                            if($status=='ONGOING') $badge_class='info';
                            if($status=='COMPLETED') $badge_class='primary';
                            if($status=='CANCELLED') $badge_class='danger';
                            echo "<span class='badge bg-$badge_class'>$status</span>";
                        ?>
                    </td>
                  
                    <td class="d-flex gap-1 flex-wrap">
                      

                    

                        <a href="booking_view.php?booking_id=<?= $b['id'] ?>" class="btn btn-info btn-sm">👁️ View</a>

                     



                      
                       
                    </td>
                </tr>
            <?php endwhile; ?>
        <?php else: ?>
            <tr><td colspan="11" class="text-center">No bookings found.</td></tr>
        <?php endif; ?>
        </tbody>
    </table>
</div>

<script>
// Initialize Bootstrap 5 tooltips
var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'))
var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
  return new bootstrap.Tooltip(tooltipTriggerEl)
})
</script>

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