<?php 
if ($_SERVER["REQUEST_METHOD"] === "POST") {
    $name      = trim($_POST['name']);
    $phone     = trim($_POST['phone']);
    $email     = trim($_POST['email']);
    $checkin   = $_POST['checkin_date'];
    $checkout  = $_POST['checkout_date'];
    $category  = $_POST['room_category'];
    $room_id   = $_POST['room_id'];
    $price     = $_POST['price'];

    // Basic input validation
    if (empty($name) || empty($phone) || empty($email) || empty($checkin) || empty($checkout) || empty($category) || empty($room_id)) {
        $error = "All fields are required.";
    } elseif (strtotime($checkin) >= strtotime($checkout)) {
        $error = "Check-out date must be after check-in date.";
    } else {
        // Check if the room is still available
        $roomCheck = $pdo->prepare("SELECT status FROM rooms WHERE id = ?");
        $roomCheck->execute([$room_id]);
        $roomStatus = $roomCheck->fetchColumn();

        if ($roomStatus !== 'available') {
            $error = "This room has already been booked. Please choose another.";
        } else {
            // Insert booking
            //INSERT INTO `customers`(`id`, `full_name`, `email`, `phone`, `address`, `created_at`) VALUES (?,?,?,?,?,?)
            //INSERT INTO `bookings`(`id`, `customer_id`, `booked_by`, `room_id`, `check_in`, `check_out`, `total_amount`, `status`, `created_at`, `booking_type`) VALUES (?,?,?,?,?,?,?,?,?,?)
            $stmt = $pdo->prepare("INSERT INTO bookings (guest_name, phone, email, checkin_date, checkout_date, room_id, category_id, price) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
            $stmt2 = $pdo->prepare("INSERT INTO `customers`(`id`, `full_name`, `email`, `phone`, `address`, `created_at`) VALUES (?,?,?,?,?,?)");
            $stmt->execute([$name, $phone, $email, $checkin, $checkout, $room_id, $category, $price]);

            // Update room status
            $pdo->prepare("UPDATE rooms SET status = 'booked' WHERE id = ?")->execute([$room_id]);

            $message = "Room successfully booked!";
        }
    }
}


?>























<?php
session_start();
require_once __DIR__ . '/../includes/db.php';

if (!isset($_SESSION['user']) || $_SESSION['user']['role'] !== 'admin') {
    header("Location: ../index.php");
    exit;
}

$admin = $_SESSION['user'];

// Handle status update via AJAX
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'update_status') {
    header('Content-Type: application/json');
    
    $room_id = (int)($_POST['room_id'] ?? 0);
    $new_status = trim($_POST['status'] ?? '');
    
    // Validate inputs
    $valid_statuses = ['available', 'occupied', 'maintenance'];
    
    if ($room_id <= 0) {
        echo json_encode(['success' => false, 'error' => 'Invalid room ID']);
        exit;
    }
    
    if (!in_array($new_status, $valid_statuses)) {
        echo json_encode(['success' => false, 'error' => 'Invalid status']);
        exit;
    }
    
    try {
        // Check if room exists
        $checkStmt = $pdo->prepare("SELECT id, room_number, status FROM rooms WHERE id = ?");
        $checkStmt->execute([$room_id]);
        $room = $checkStmt->fetch(PDO::FETCH_ASSOC);
        
        if (!$room) {
            echo json_encode(['success' => false, 'error' => 'Room not found']);
            exit;
        }
        
        // Update room status
        $updateStmt = $pdo->prepare("UPDATE rooms SET status = ?, updated_at = NOW() WHERE id = ?");
        $result = $updateStmt->execute([$new_status, $room_id]);
        
        if ($result) {
            // Log the status change (optional - you can create a status_logs table)
            // $logStmt = $pdo->prepare("INSERT INTO status_logs (room_id, old_status, new_status, changed_by, changed_at) VALUES (?, ?, ?, ?, NOW())");
            // $logStmt->execute([$room_id, $room['status'], $new_status, $admin['id']]);
            
            echo json_encode([
                'success' => true, 
                'message' => "Room {$room['room_number']} status updated to " . ucfirst($new_status),
                'room_id' => $room_id,
                'new_status' => $new_status
            ]);
        } else {
            echo json_encode(['success' => false, 'error' => 'Failed to update room status']);
        }
        
    } catch (PDOException $e) {
        error_log("Status update error: " . $e->getMessage());
        echo json_encode(['success' => false, 'error' => 'Database error occurred']);
    }
    exit;
}

// Get filter values
$statusFilter = trim($_GET['status'] ?? '');
$categoryFilter = (int)($_GET['category'] ?? 0);
$floorFilter = trim($_GET['floor'] ?? '');

// Pagination setup
$limit = 15;
$page = max((int)($_GET['page'] ?? 1), 1);
$offset = ($page - 1) * $limit;

// Build query conditions
$whereConditions = [];
$params = [];

if (!empty($statusFilter)) {
    $whereConditions[] = 'r.status = ?';
    $params[] = $statusFilter;
}

if ($categoryFilter > 0) {
    $whereConditions[] = 'r.category_id = ?';
    $params[] = $categoryFilter;
}

if (!empty($floorFilter)) {
    $whereConditions[] = 'r.floor = ?';
    $params[] = $floorFilter;
}

$whereSQL = !empty($whereConditions) ? 'WHERE ' . implode(' AND ', $whereConditions) : '';

try {
    // Get all categories for filter dropdown
    $categoryStmt = $pdo->query("SELECT id, name FROM room_categories ORDER BY name");
    $categories = $categoryStmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Get unique floors for filter dropdown
    $floorStmt = $pdo->query("SELECT DISTINCT floor FROM rooms WHERE floor IS NOT NULL AND floor != '' ORDER BY floor");
    $floors = $floorStmt->fetchAll(PDO::FETCH_COLUMN);

    // Fetch rooms
    $sql = "
        SELECT r.*, c.name AS category_name, c.price_per_night
        FROM rooms r 
        JOIN room_categories c ON r.category_id = c.id 
        $whereSQL 
        ORDER BY r.floor ASC, r.room_number ASC 
        LIMIT " . (int)$limit . " OFFSET " . (int)$offset;
    
    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    $rooms = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // Count total rooms for pagination
    $countSQL = "
        SELECT COUNT(*) 
        FROM rooms r 
        JOIN room_categories c ON r.category_id = c.id 
        $whereSQL";
    $countStmt = $pdo->prepare($countSQL);
    $countStmt->execute($params);
    $totalRooms = $countStmt->fetchColumn();
    $totalPages = ceil($totalRooms / $limit);

    // Get status summary
    $statusSummaryStmt = $pdo->query("
        SELECT status, COUNT(*) as count 
        FROM rooms 
        GROUP BY status 
        ORDER BY status
    ");
    $statusSummary = $statusSummaryStmt->fetchAll(PDO::FETCH_ASSOC);

} catch (PDOException $e) {
    error_log("Database error in list_all_rooms.php: " . $e->getMessage());
    $rooms = [];
    $categories = [];
    $floors = [];
    $statusSummary = [];
    $totalRooms = 0;
    $totalPages = 0;
    $error_message = "Unable to fetch room data. Please try again later.";
}

// Helper function to build filter-aware pagination URLs
function buildPaginationUrl($page, $statusFilter, $categoryFilter, $floorFilter) {
    $params = ['page' => $page];
    if (!empty($statusFilter)) $params['status'] = $statusFilter;
    if ($categoryFilter > 0) $params['category'] = $categoryFilter;
    if (!empty($floorFilter)) $params['floor'] = $floorFilter;
    return '?' . http_build_query($params);
}

// Helper function to get status badge class
function getStatusBadgeClass($status) {
    return match($status) {
        'available' => 'bg-green-100 text-green-700 border-green-200',
        'booked' => 'bg-yellow-100 text-yellow-700 border-yellow-200',
        'occupied' => 'bg-red-100 text-red-700 border-red-200',
        'maintenance' => 'bg-gray-100 text-gray-700 border-gray-200',
        default => 'bg-blue-100 text-blue-700 border-blue-200'
    };
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>All Rooms Management - Sheridan Hotel</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <style>
        .status-button {
            transition: all 0.2s ease;
        }
        .status-button:hover {
            transform: translateY(-1px);
        }
        .status-button:disabled {
            opacity: 0.6;
            cursor: not-allowed;
            transform: none;
        }
    </style>
</head>
<body class="bg-gray-100 flex h-screen">
    <!-- Sidebar -->
    <aside class="w-64 bg-white shadow-md h-full flex flex-col">
        <div class="p-6">
            <h1 class="text-xl font-bold text-blue-700">Sheridan Hotel</h1>
            <p class="text-gray-600 mb-6">You are logged in as <strong><?= htmlspecialchars($admin['role']) ?></strong>.</p>
        </div>
        <nav class="flex-1 px-4 space-y-2">
            <a href="dashboard.php" class="block px-4 py-2 text-gray-700 rounded hover:bg-gray-200">Dashboard Home</a>
            <a href="book_room.php" class="block px-4 py-2 text-gray-700 rounded hover:bg-gray-200">Book a Room</a>
            <a href="room_status.php" class="block px-4 py-2 text-gray-700 rounded hover:bg-gray-200">Check Room Status</a>
            <a href="available_rooms.php" class="block px-4 py-2 text-gray-700 rounded hover:bg-gray-200">Available Rooms</a>
            <a href="list_available.php" class="block px-4 py-2 text-gray-700 rounded hover:bg-gray-200">List of Available Rooms</a>
            <a href="list_booked.php" class="block px-4 py-2 text-gray-700 rounded hover:bg-gray-200">List of Booked Rooms</a>
            <a href="list_all_rooms.php" class="block px-4 py-2 text-blue-700 bg-blue-50 rounded font-medium">All Rooms Management</a>
        </nav>
        <div class="p-4 border-t">
            <p class="text-sm text-gray-500">All rights reserved &copy; Sheridan Hotels and Suites</p>
            <a href="../logout.php" class="mt-2 inline-block text-red-500 hover:underline text-sm">Logout</a>
        </div>
    </aside>

    <!-- Main content area -->
    <div class="flex-1 flex flex-col overflow-hidden">
        <!-- Top Navbar -->
        <nav class="bg-white shadow px-6 py-4 flex justify-between items-center">
            <h1 class="text-xl font-bold text-gray-800">All Rooms Management</h1>
            <div class="flex items-center gap-4">
                <span class="text-gray-600 text-sm">Welcome, <?= htmlspecialchars($admin['name']) ?></span>
                <span id="datetime" class="text-gray-500 text-sm"></span>
            </div>
        </nav>

        <main class="p-6 overflow-y-auto">
            <!-- Status Summary Cards -->
            <div class="grid grid-cols-1 md:grid-cols-4 gap-4 mb-6">
                <?php 
                $statusCounts = array_column($statusSummary, 'count', 'status');
                $statusLabels = [
                    'available' => ['Available', 'bg-green-500', 'text-green-100'],
                    'occupied' => ['Occupied', 'bg-red-500', 'text-red-100'],
                    'booked' => ['Booked', 'bg-yellow-500', 'text-yellow-100'],
                    'maintenance' => ['Maintenance', 'bg-gray-500', 'text-gray-100']
                ];
                
                foreach ($statusLabels as $status => $config): 
                    $count = $statusCounts[$status] ?? 0;
                ?>
                    <div class="<?= $config[1] ?> <?= $config[2] ?> p-4 rounded-lg shadow">
                        <div class="flex items-center justify-between">
                            <div>
                                <p class="text-sm opacity-90"><?= $config[0] ?> Rooms</p>
                                <p class="text-2xl font-bold"><?= $count ?></p>
                            </div>
                            <div class="text-3xl opacity-75">🏨</div>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>

            <?php if (isset($error_message)): ?>
                <div class="mb-4 p-4 bg-red-100 border border-red-300 text-red-700 rounded">
                    <?= htmlspecialchars($error_message) ?>
                </div>
            <?php endif; ?>

            <div class="max-w-full bg-white p-6 rounded-lg shadow">
                <div class="flex justify-between items-center mb-6">
                    <h2 class="text-2xl font-bold">Room Management</h2>
                    <?php if (!empty($statusFilter) || $categoryFilter > 0 || !empty($floorFilter)): ?>
                        <div class="flex items-center gap-2">
                            <span class="text-sm text-gray-600">Filters active:</span>
                            <?php if (!empty($statusFilter)): ?>
                                <span class="px-2 py-1 bg-blue-100 text-blue-700 rounded text-sm"><?= ucfirst($statusFilter) ?></span>
                            <?php endif; ?>
                            <?php if ($categoryFilter > 0): ?>
                                <?php 
                                $activeCat = array_filter($categories, fn($c) => $c['id'] == $categoryFilter);
                                $activeCatName = !empty($activeCat) ? reset($activeCat)['name'] : 'Category';
                                ?>
                                <span class="px-2 py-1 bg-green-100 text-green-700 rounded text-sm"><?= htmlspecialchars($activeCatName) ?></span>
                            <?php endif; ?>
                            <?php if (!empty($floorFilter)): ?>
                                <span class="px-2 py-1 bg-purple-100 text-purple-700 rounded text-sm">Floor <?= htmlspecialchars($floorFilter) ?></span>
                            <?php endif; ?>
                            <a href="list_all_rooms.php" class="text-sm text-red-600 hover:underline">Clear filters</a>
                        </div>
                    <?php endif; ?>
                </div>

                <!-- Filters Form -->
                <div class="bg-gray-50 p-4 rounded-lg mb-6">
                    <form method="GET" class="flex flex-wrap gap-4 items-end">
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">Status</label>
                            <select name="status" class="border border-gray-300 p-2 rounded-md focus:ring-2 focus:ring-blue-500 focus:border-blue-500">
                                <option value="">All Statuses</option>
                                <option value="available" <?= $statusFilter === 'available' ? 'selected' : '' ?>>Available</option>
                                <option value="occupied" <?= $statusFilter === 'occupied' ? 'selected' : '' ?>>Occupied</option>
                                <option value="booked" <?= $statusFilter === 'booked' ? 'selected' : '' ?>>Booked</option>
                                <option value="maintenance" <?= $statusFilter === 'maintenance' ? 'selected' : '' ?>>Maintenance</option>
                            </select>
                        </div>

                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">Category</label>
                            <select name="category" class="border border-gray-300 p-2 rounded-md focus:ring-2 focus:ring-blue-500 focus:border-blue-500">
                                <option value="">All Categories</option>
                                <?php foreach ($categories as $cat): ?>
                                    <option value="<?= $cat['id'] ?>" <?= $categoryFilter == $cat['id'] ? 'selected' : '' ?>>
                                        <?= htmlspecialchars($cat['name']) ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>

                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">Floor</label>
                            <select name="floor" class="border border-gray-300 p-2 rounded-md focus:ring-2 focus:ring-blue-500 focus:border-blue-500">
                                <option value="">All Floors</option>
                                <?php foreach ($floors as $floor): ?>
                                    <option value="<?= htmlspecialchars($floor) ?>" <?= $floorFilter === $floor ? 'selected' : '' ?>>
                                        Floor <?= htmlspecialchars($floor) ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>

                        <div class="flex gap-2">
                            <button type="submit" class="bg-blue-600 text-white px-4 py-2 rounded-md hover:bg-blue-700 transition-colors">
                                Apply Filters
                            </button>
                            <?php if (!empty($statusFilter) || $categoryFilter > 0 || !empty($floorFilter)): ?>
                                <a href="list_all_rooms.php" class="bg-gray-500 text-white px-4 py-2 rounded-md hover:bg-gray-600 transition-colors">
                                    Clear
                                </a>
                            <?php endif; ?>
                        </div>
                    </form>
                </div>

                <!-- Results Summary -->
                <div class="mb-4">
                    <p class="text-sm text-gray-600">
                        Showing <?= count($rooms) ?> of <?= $totalRooms ?> rooms
                        <?php if ($totalPages > 1): ?>
                            (Page <?= $page ?> of <?= $totalPages ?>)
                        <?php endif; ?>
                    </p>
                </div>

                <!-- Rooms Grid -->
                <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                    <?php if (count($rooms) > 0): ?>
                        <?php foreach ($rooms as $room): ?>
                            <div class="bg-white border border-gray-200 rounded-lg shadow-sm hover:shadow-md transition-shadow">
                                <div class="p-4">
                                    <!-- Room Header -->
                                    <div class="flex justify-between items-start mb-3">
                                        <div>
                                            <h3 class="text-lg font-semibold text-gray-900">Room <?= htmlspecialchars($room['room_number']) ?></h3>
                                            <p class="text-sm text-gray-600"><?= htmlspecialchars($room['category_name']) ?></p>
                                        </div>
                                        <span class="inline-flex px-2 py-1 text-xs font-semibold rounded-full border <?= getStatusBadgeClass($room['status']) ?>">
                                            <?= ucfirst($room['status']) ?>
                                        </span>
                                    </div>

                                    <!-- Room Details -->
                                    <div class="space-y-2 mb-4">
                                        <?php if (!empty($room['floor'])): ?>
                                            <p class="text-sm text-gray-600">
                                                <span class="font-medium">Floor:</span> <?= htmlspecialchars($room['floor']) ?>
                                            </p>
                                        <?php endif; ?>
                                        <?php if (!empty($room['price_per_night'])): ?>
                                            <p class="text-sm text-gray-600">
                                                <span class="font-medium">Price:</span> $<?= number_format($room['price_per_night'], 2) ?>/night
                                            </p>
                                        <?php endif; ?>
                                        <?php if (!empty($room['description'])): ?>
                                            <p class="text-sm text-gray-600 line-clamp-2">
                                                <?= htmlspecialchars(substr($room['description'], 0, 100)) ?><?= strlen($room['description']) > 100 ? '...' : '' ?>
                                            </p>
                                        <?php endif; ?>
                                    </div>

                                    <!-- Status Change Buttons -->
                                    <div class="space-y-2">
                                        <p class="text-xs font-medium text-gray-700 mb-2">Change Status:</p>
                                        <div class="grid grid-cols-1 gap-2">
                                            <button onclick="updateRoomStatus(<?= $room['id'] ?>, 'available')" 
                                                    class="status-button w-full px-3 py-2 text-sm font-medium rounded-md <?= $room['status'] === 'available' ? 'bg-gray-300 text-gray-500 cursor-not-allowed' : 'bg-green-500 text-white hover:bg-green-600' ?>"
                                                    <?= $room['status'] === 'available' ? 'disabled' : '' ?>>
                                                Mark Available
                                            </button>
                                            
                                            <button onclick="updateRoomStatus(<?= $room['id'] ?>, 'occupied')" 
                                                    class="status-button w-full px-3 py-2 text-sm font-medium rounded-md <?= $room['status'] === 'occupied' ? 'bg-gray-300 text-gray-500 cursor-not-allowed' : 'bg-red-500 text-white hover:bg-red-600' ?>"
                                                    <?= $room['status'] === 'occupied' ? 'disabled' : '' ?>>
                                                Mark Occupied
                                            </button>
                                            
                                            <button onclick="updateRoomStatus(<?= $room['id'] ?>, 'maintenance')" 
                                                    class="status-button w-full px-3 py-2 text-sm font-medium rounded-md <?= $room['status'] === 'maintenance' ? 'bg-gray-300 text-gray-500 cursor-not-allowed' : 'bg-yellow-500 text-white hover:bg-yellow-600' ?>"
                                                    <?= $room['status'] === 'maintenance' ? 'disabled' : '' ?>>
                                                Under Maintenance
                                            </button>
                                        </div>
                                    </div>

                                    <!-- Additional Actions -->
                                    <div class="mt-4 pt-3 border-t border-gray-200">
                                        <button onclick="viewRoomDetails(<?= htmlspecialchars(json_encode($room)) ?>)" 
                                                class="w-full px-3 py-2 text-sm font-medium text-gray-700 bg-gray-100 rounded-md hover:bg-gray-200 transition-colors">
                                            View Full Details
                                        </button>
                                    </div>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <div class="col-span-full text-center py-12">
                            <div class="text-gray-400 text-6xl mb-4">🏨</div>
                            <div class="text-lg text-gray-600 mb-2">No rooms found</div>
                            <div class="text-sm text-gray-500">Try adjusting your filters or check back later.</div>
                        </div>
                    <?php endif; ?>
                </div>

                <!-- Pagination -->
                <?php if ($totalPages > 1): ?>
                    <div class="mt-8 flex justify-center">
                        <nav class="flex items-center space-x-1">
                            <?php if ($page > 1): ?>
                                <a href="<?= buildPaginationUrl($page - 1, $statusFilter, $categoryFilter, $floorFilter) ?>" 
                                   class="px-3 py-2 text-sm border border-gray-300 rounded-l-md bg-white text-gray-500 hover:bg-gray-50">
                                    Previous
                                </a>
                            <?php endif; ?>

                            <?php 
                            $start = max(1, $page - 2);
                            $end = min($totalPages, $page + 2);
                            
                            if ($start > 1): ?>
                                <a href="<?= buildPaginationUrl(1, $statusFilter, $categoryFilter, $floorFilter) ?>" 
                                   class="px-3 py-2 text-sm border border-gray-300 bg-white text-gray-700 hover:bg-gray-50">1</a>
                                <?php if ($start > 2): ?>
                                    <span class="px-3 py-2 text-sm text-gray-500">...</span>
                                <?php endif; ?>
                            <?php endif; ?>

                            <?php for ($i = $start; $i <= $end; $i++): ?>
                                <a href="<?= buildPaginationUrl($i, $statusFilter, $categoryFilter, $floorFilter) ?>" 
                                   class="px-3 py-2 text-sm border <?= $i == $page ? 'bg-blue-600 text-white border-blue-600' : 'border-gray-300 bg-white text-gray-700 hover:bg-gray-50' ?>">
                                    <?= $i ?>
                                </a>
                            <?php endfor; ?>

                            <?php if ($end < $totalPages): ?>
                                <?php if ($end < $totalPages - 1): ?>
                                    <span class="px-3 py-2 text-sm text-gray-500">...</span>
                                <?php endif; ?>
                                <a href="<?= buildPaginationUrl($totalPages, $statusFilter, $categoryFilter, $floorFilter) ?>" 
                                   class="px-3 py-2 text-sm border border-gray-300 bg-white text-gray-700 hover:bg-gray-50"><?= $totalPages ?></a>
                            <?php endif; ?>

                            <?php if ($page < $totalPages): ?>
                                <a href="<?= buildPaginationUrl($page + 1, $statusFilter, $categoryFilter, $floorFilter) ?>" 
                                   class="px-3 py-2 text-sm border border-gray-300 rounded-r-md bg-white text-gray-500 hover:bg-gray-50">
                                    Next
                                </a>
                            <?php endif; ?>
                        </nav>
                    </div>
                <?php endif; ?>
            </div>
        </main>
    </div>

    <!-- Room Details Modal -->
    <div id="roomModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center hidden z-50">
        <div class="bg-white p-6 rounded-lg shadow-xl w-96 max-w-full mx-4 relative">
            <button onclick="closeModal()" class="absolute top-4 right-4 text-gray-400 hover:text-gray-600 text-xl">
                &times;
            </button>
            <h3 class="text-xl font-bold mb-4 text-gray-800">Room Details</h3>
            <div id="roomDetails" class="space-y-3"></div>
            <div class="mt-6 flex justify-end">
                <button onclick="closeModal()" class="px-4 py-2 bg-gray-500 text-white rounded hover:bg-gray-600">
                    Close
                </button>
            </div>
        </div>
    </div>

    <!-- Success/Error Toast -->
    <div id="toast" class="fixed top-4 right-4 p-4 rounded-lg shadow-lg hidden z-50 transition-all duration-300">
        <div id="toastContent" class="flex items-center gap-2">
            <span id="toastMessage"></span>
        </div>
    </div>

    <script>
        // Update datetime display
        function updateDateTime() {
            const now = new Date();
            document.getElementById('datetime').textContent = now.toLocaleString(undefined, { 
                hour12: false,
                year: 'numeric',
                month: '2-digit',
                day: '2-digit',
                hour: '2-digit',
                minute: '2-digit'
            });
        }
        setInterval(updateDateTime, 1000);
        updateDateTime();

        // Update room status
        function updateRoomStatus(roomId, newStatus) {
            const statusLabels = {
                'available': 'Available',
                'occupied': 'Occupied',
                'maintenance': 'Under Maintenance'
            };

            if (!confirm(`Are you sure you want to mark this room as ${statusLabels[newStatus]}?`)) {
                return;
            }

            // Find and disable all buttons for this room
            const roomCard = event.target.closest('.bg-white');
            const buttons = roomCard.querySelectorAll('.status-button');
            buttons.forEach(btn => {
                btn.disabled = true;
                btn.textContent = btn.textContent.replace(/Mark |Under /, 'Updating...');
            });

            fetch('list_all_rooms.php', {
                method: 'POST',
                headers: { 
                    'Content-Type': 'application/x-www-form-urlencoded',
                    'X-Requested-With': 'XMLHttpRequest'
                },
                body: `action=update_status&room_id=${encodeURIComponent(roomId)}&status=${encodeURIComponent(newStatus)}`
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error('Network response was not ok');
                }
                return response.json();
            })
            .then(data => {
                if (data.success) {
                    showToast(data.message, 'success');
                    // Reload page after short delay to show updated status
                    setTimeout(() => {
                        location.reload();
                    }, 1500);
                } else {
                    showToast('Error: ' + (data.error || 'Could not update room status'), 'error');
                    // Re-enable buttons on error
                    buttons.forEach(btn => {
                        btn.disabled = false;
                        // Restore original button text
                        const originalTexts = {
                            'available': 'Mark Available',
                            'occupied': 'Mark Occupied',  
                            'maintenance': 'Under Maintenance'
                        };
                        if (btn.textContent.includes('Updating')) {
                            for (const [status, text] of Object.entries(originalTexts)) {
                                if (btn.onclick.toString().includes(`'${status}'`)) {
                                    btn.textContent = text;
                                    break;
                                }
                            }
                        }
                    });
                }
            })