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

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

$admin = $_SESSION['user'];

// [Previous PHP code remains exactly the same until the HTML starts]

$admin = $_SESSION['user'];

// Handle status update AJAX request
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 = ?");
        $updateStmt->execute([$new_status, $room_id]);
        
        // Log the status change (optional - add to your logs table if you have one)
        error_log("Room {$room['room_number']} status changed from {$room['status']} to {$new_status} by admin {$admin['name']}");
        
        echo json_encode([
            'success' => true, 
            'message' => "Room {$room['room_number']} status updated to " . ucfirst($new_status),
            'new_status' => $new_status
        ]);
        
    } catch (PDOException $e) {
        error_log("Error updating room status: " . $e->getMessage());
        echo json_encode(['success' => false, 'error' => 'Database error occurred']);
    }
    
    exit;
}

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

// 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($searchFilter)) {
    $whereConditions[] = '(r.room_number LIKE ? OR r.description LIKE ?)';
    $params[] = "%{$searchFilter}%";
    $params[] = "%{$searchFilter}%";
}

$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);

    // 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.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
    $summaryStmt = $pdo->query("
        SELECT 
            status,
            COUNT(*) as count
        FROM rooms 
        GROUP BY status
    ");
    $statusSummary = $summaryStmt->fetchAll(PDO::FETCH_KEY_PAIR);

} catch (PDOException $e) {
    error_log("Database error in list_all_rooms.php: " . $e->getMessage());
    $rooms = [];
    $categories = [];
    $totalRooms = 0;
    $totalPages = 0;
    $statusSummary = [];
    $error_message = "Database error: " . $e->getMessage();
}

// Helper function to build filter-aware pagination URLs
function buildPaginationUrl($page, $statusFilter, $categoryFilter, $searchFilter) {
    $params = ['page' => $page];
    if (!empty($statusFilter)) $params['status'] = $statusFilter;
    if ($categoryFilter > 0) $params['category'] = $categoryFilter;
    if (!empty($searchFilter)) $params['search'] = $searchFilter;
    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>
<head>
    <title>All Rooms Management - Sheridan Hotel</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <style>
        @import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap');
        
        body {
            font-family: 'Inter', sans-serif;
        }
        
        .gradient-bg {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        }
        
        .card-hover {
            transition: all 0.3s ease;
        }
        
        .card-hover:hover {
            transform: translateY(-5px);
            box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);
        }
        
        .nav-item {
            transition: all 0.2s ease;
            position: relative;
            overflow: hidden;
        }
        
        .nav-item:hover {
            background: linear-gradient(135deg, #f3f4f6, #e5e7eb);
            transform: translateX(5px);
        }
        
        .nav-item.active {
            background: linear-gradient(135deg, #3b82f6, #1d4ed8);
            color: white;
        }
        
        .metric-card {
            background: linear-gradient(135deg, #ffffff, #f8fafc);
            border: 1px solid rgba(255, 255, 255, 0.2);
            backdrop-filter: blur(10px);
        }
        
        .sidebar-gradient {
            background: linear-gradient(180deg, #1e293b 0%, #334155 100%);
        }
        
        .animate-fade-in {
            animation: fadeIn 0.8s ease-in-out;
        }
        
        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(20px); }
            to { opacity: 1; transform: translateY(0); }
        }
        
        .pulse-dot {
            animation: pulse 2s infinite;
        }
        
        @keyframes pulse {
            0%, 100% { transform: scale(1); opacity: 1; }
            50% { transform: scale(1.1); opacity: 0.8; }
        }
    </style>
</head>
<body class="bg-gradient-to-br from-gray-50 to-gray-100 min-h-screen">
    <!-- Sidebar -->
    <aside class="fixed left-0 top-0 w-72 h-full sidebar-gradient shadow-2xl z-50">
        <div class="p-8">
            <div class="flex items-center gap-3 mb-2">
                <div class="w-10 h-10 bg-gradient-to-r from-blue-400 to-purple-500 rounded-xl flex items-center justify-center">
                    <i class="fas fa-hotel text-white text-lg"></i>
                </div>
                <h1 class="text-2xl font-bold text-white">Sheridan Hotel</h1>
            </div>
            <div class="flex items-center gap-2 mt-4 p-3 bg-white/10 rounded-lg backdrop-blur-sm">
                <div class="w-2 h-2 bg-green-400 rounded-full pulse-dot"></div>
                <p class="text-white/90 text-sm">Logged in as <span class="font-semibold text-blue-300"><?= htmlspecialchars($admin['role']) ?></span></p>
            </div>
        </div>
        
        <nav class="px-6 space-y-2">
            <a href="dashboard.php" class="nav-item flex items-center gap-3 px-4 py-3 text-white/80 hover:text-white rounded-xl">
                <i class="fas fa-tachometer-alt w-5"></i>
                <span class="font-medium">Dashboard Home</span>
            </a>
            <a href="book_room.php" class="nav-item flex items-center gap-3 px-4 py-3 text-white/80 hover:text-white rounded-xl">
                <i class="fas fa-calendar-plus w-5"></i>
                <span class="font-medium">Book a Room</span>
            </a>
            <a href="room_status.php" class="nav-item flex items-center gap-3 px-4 py-3 text-white/80 hover:text-white rounded-xl">
                <i class="fas fa-bed w-5"></i>
                <span class="font-medium">Room Status</span>
            </a>
            <a href="available_rooms.php" class="nav-item flex items-center gap-3 px-4 py-3 text-white/80 hover:text-white rounded-xl">
                <i class="fas fa-door-open w-5"></i>
                <span class="font-medium">Available Rooms</span>
            </a>
            <a href="check_out.php" class="nav-item flex items-center gap-3 px-4 py-3 text-white/80 hover:text-white rounded-xl">
                <i class="fas fa-sign-out-alt w-5"></i>
                <span class="font-medium">Customer Check-out</span>
            </a>
            <a href="list_booked.php" class="nav-item flex items-center gap-3 px-4 py-3 text-white/80 hover:text-white rounded-xl">
                <i class="fas fa-list-alt w-5"></i>
                <span class="font-medium">Booked Rooms</span>
            </a>
            <a href="list_all_rooms.php" class="nav-item active flex items-center gap-3 px-4 py-3 text-white rounded-xl">
                <i class="fas fa-building w-5"></i>
                <span class="font-medium">All Rooms</span>
            </a>
        </nav>
        
        <div class="absolute bottom-0 left-0 right-0 p-6 border-t border-white/10">
            <p class="text-white/60 text-xs mb-3">© Sheridan Hotels and Suites</p>
            <a href="../logout.php" class="flex items-center gap-2 text-red-400 hover:text-red-300 text-sm font-medium transition-colors">
                <i class="fas fa-power-off"></i>
                <span>Logout</span>
            </a>
        </div>
    </aside>

    <!-- Main Content Area -->
    <div class="ml-72 min-h-screen">
        <!-- Top Header -->
        <header class="bg-white/80 backdrop-blur-sm border-b border-gray-200/50 px-8 py-6 sticky top-0 z-40">
            <div class="flex justify-between items-center">
                <div>
                    <h1 class="text-3xl font-bold text-gray-800">All Rooms Management</h1>
                    <p class="text-gray-600 mt-1">Manage all hotel rooms and their statuses</p>
                </div>
                <div class="flex items-center gap-6">
                    <div class="text-right">
                        <p class="text-sm text-gray-500">Welcome back,</p>
                        <p class="font-semibold text-gray-800"><?= htmlspecialchars($admin['name']) ?></p>
                    </div>
                    <div class="w-12 h-12 bg-gradient-to-r from-blue-500 to-purple-600 rounded-full flex items-center justify-center text-white font-bold text-lg">
                        <?= strtoupper(substr($admin['name'], 0, 1)) ?>
                    </div>
                    <div class="text-sm text-gray-600 font-mono bg-gray-100 px-3 py-2 rounded-lg">
                        <span id="datetime"></span>
                    </div>
                </div>
            </div>
        </header>

        <!-- Dashboard Content -->
        <main class="p-8">
            <?php if (isset($error_message)): ?>
                <div class="mb-6 p-4 bg-red-100 border-l-4 border-red-500 text-red-700 rounded-lg shadow">
                    <p><?= htmlspecialchars($error_message) ?></p>
                </div>
            <?php endif; ?>

            <!-- Status Summary Cards -->
            <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
                <div class="metric-card card-hover p-6 rounded-2xl shadow-lg">
                    <div class="flex items-center justify-between mb-4">
                        <div class="w-12 h-12 bg-green-100 rounded-full flex items-center justify-center">
                            <i class="fas fa-door-open text-green-600 text-xl"></i>
                        </div>
                        <div class="text-right">
                            <div class="w-3 h-3 bg-green-500 rounded-full"></div>
                        </div>
                    </div>
                    <h3 class="text-gray-600 font-medium mb-2">Available</h3>
                    <p class="text-3xl font-bold text-green-600 mb-1"><?= $statusSummary['available'] ?? 0 ?></p>
                    <p class="text-xs text-gray-500">Ready for booking</p>
                </div>

                <div class="metric-card card-hover p-6 rounded-2xl shadow-lg">
                    <div class="flex items-center justify-between mb-4">
                        <div class="w-12 h-12 bg-red-100 rounded-full flex items-center justify-center">
                            <i class="fas fa-user-check text-red-600 text-xl"></i>
                        </div>
                        <div class="text-right">
                            <div class="w-3 h-3 bg-red-500 rounded-full"></div>
                        </div>
                    </div>
                    <h3 class="text-gray-600 font-medium mb-2">Occupied</h3>
                    <p class="text-3xl font-bold text-red-600 mb-1"><?= $statusSummary['occupied'] ?? 0 ?></p>
                    <p class="text-xs text-gray-500">Currently in use</p>
                </div>

                <div class="metric-card card-hover p-6 rounded-2xl shadow-lg">
                    <div class="flex items-center justify-between mb-4">
                        <div class="w-12 h-12 bg-yellow-100 rounded-full flex items-center justify-center">
                            <i class="fas fa-calendar-check text-yellow-600 text-xl"></i>
                        </div>
                        <div class="text-right">
                            <div class="w-3 h-3 bg-yellow-500 rounded-full"></div>
                        </div>
                    </div>
                    <h3 class="text-gray-600 font-medium mb-2">Booked</h3>
                    <p class="text-3xl font-bold text-yellow-600 mb-1"><?= $statusSummary['booked'] ?? 0 ?></p>
                    <p class="text-xs text-gray-500">Reserved</p>
                </div>

                <div class="metric-card card-hover p-6 rounded-2xl shadow-lg">
                    <div class="flex items-center justify-between mb-4">
                        <div class="w-12 h-12 bg-gray-100 rounded-full flex items-center justify-center">
                            <i class="fas fa-tools text-gray-600 text-xl"></i>
                        </div>
                        <div class="text-right">
                            <div class="w-3 h-3 bg-gray-500 rounded-full"></div>
                        </div>
                    </div>
                    <h3 class="text-gray-600 font-medium mb-2">Maintenance</h3>
                    <p class="text-3xl font-bold text-gray-600 mb-1"><?= $statusSummary['maintenance'] ?? 0 ?></p>
                    <p class="text-xs text-gray-500">Under repair</p>
                </div>
            </div>

            <!-- Filters Card -->
            <div class="bg-white rounded-2xl shadow-lg mb-8 overflow-hidden">
                <div class="gradient-bg p-6 text-white">
                    <h2 class="text-xl font-bold">Room Filters</h2>
                    <p class="text-blue-100">Refine your room search</p>
                </div>
                <div class="p-6">
                    <form method="GET" class="grid grid-cols-1 md:grid-cols-4 gap-4">
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">Search Room</label>
                            <input type="text" name="search" value="<?= htmlspecialchars($searchFilter) ?>" 
                                   placeholder="Room number or description" 
                                   class="w-full border border-gray-300 p-2 rounded-md focus:ring-2 focus:ring-blue-500 focus:border-blue-500">
                        </div>

                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">Status</label>
                            <select name="status" class="w-full 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="booked" <?= $statusFilter === 'booked' ? 'selected' : '' ?>>Booked</option>
                                <option value="occupied" <?= $statusFilter === 'occupied' ? 'selected' : '' ?>>Occupied</option>
                                <option value="maintenance" <?= $statusFilter === 'maintenance' ? 'selected' : '' ?>>Under Maintenance</option>
                            </select>
                        </div>

                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">Category</label>
                            <select name="category" class="w-full 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 class="flex items-end gap-2">
                            <button type="submit" class="bg-blue-600 text-white px-4 py-2 rounded-md hover:bg-blue-700 transition-colors h-[42px]">
                                Apply Filters
                            </button>
                            <?php if (!empty($statusFilter) || $categoryFilter > 0 || !empty($searchFilter)): ?>
                                <a href="list_all_rooms.php" class="bg-gray-500 text-white px-4 py-2 rounded-md hover:bg-gray-600 transition-colors h-[42px]">
                                    Clear All
                                </a>
                            <?php endif; ?>
                        </div>
                    </form>
                </div>
            </div>

            <!-- Results Summary -->
            <div class="flex justify-between items-center mb-6">
                <div>
                    <h2 class="text-2xl font-bold text-gray-800">Room Management</h2>
                    <p class="text-gray-600">
                        Showing <?= count($rooms) ?> of <?= $totalRooms ?> rooms
                        <?php if ($totalPages > 1): ?>
                            (Page <?= $page ?> of <?= $totalPages ?>)
                        <?php endif; ?>
                    </p>
                </div>
                <div class="text-sm text-gray-600 bg-gray-100 px-3 py-1 rounded-lg">
                    Total Rooms: <span class="font-semibold"><?= $totalRooms ?></span>
                </div>
            </div>

            <!-- Rooms Grid -->
            <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6 mb-8">
                <?php if (count($rooms) > 0): ?>
                    <?php foreach ($rooms as $room): ?>
                        <div class="bg-white border border-gray-200 rounded-xl p-6 hover:shadow-lg transition-shadow card-hover">
                            <div class="flex justify-between items-start mb-4">
                                <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>
                                    <?php if (!empty($room['price_per_night'])): ?>
                                        <p class="text-sm font-medium text-green-600">₦<?= number_format($room['price_per_night'], 2) ?>/night</p>
                                    <?php endif; ?>
                                </div>
                                <span class="inline-flex px-3 py-1 text-xs font-semibold rounded-full border <?= getStatusBadgeClass($room['status']) ?>">
                                    <?= ucfirst($room['status']) ?>
                                </span>
                            </div>

                            <?php if (!empty($room['description'])): ?>
                                <p class="text-sm text-gray-600 mb-4 line-clamp-2"><?= htmlspecialchars($room['description']) ?></p>
                            <?php endif; ?>

                            <?php if (!empty($room['floor'])): ?>
                                <p class="text-xs text-gray-500 mb-4">Floor: <?= htmlspecialchars($room['floor']) ?></p>
                            <?php endif; ?>

                            <!-- Action Buttons -->
                            <div class="space-y-3">
                                <div class="text-xs font-medium text-gray-700">Change Status:</div>
                                <div class="flex flex-wrap gap-2">
                                    <?php if ($room['status'] !== 'available'): ?>
                                        <button onclick="updateRoomStatus(<?= $room['id'] ?>, 'available', '<?= htmlspecialchars($room['room_number']) ?>')" 
                                                class="px-3 py-1 text-xs bg-green-500 text-white rounded-lg hover:bg-green-600 transition-colors">
                                            <i class="fas fa-check-circle mr-1"></i> Available
                                        </button>
                                    <?php endif; ?>
                                    
                                    <?php if ($room['status'] !== 'occupied'): ?>
                                        <button onclick="updateRoomStatus(<?= $room['id'] ?>, 'occupied', '<?= htmlspecialchars($room['room_number']) ?>')" 
                                                class="px-3 py-1 text-xs bg-red-500 text-white rounded-lg hover:bg-red-600 transition-colors">
                                            <i class="fas fa-user-check mr-1"></i> Occupied
                                        </button>
                                    <?php endif; ?>
                                    
                                    <?php if ($room['status'] !== 'maintenance'): ?>
                                        <button onclick="updateRoomStatus(<?= $room['id'] ?>, 'maintenance', '<?= htmlspecialchars($room['room_number']) ?>')" 
                                                class="px-3 py-1 text-xs bg-gray-500 text-white rounded-lg hover:bg-gray-600 transition-colors">
                                            <i class="fas fa-tools mr-1"></i> Maintenance
                                        </button>
                                    <?php endif; ?>
                                </div>
                                
                                <div class="pt-2 border-t border-gray-100">
                                    <button onclick="viewRoomDetails(<?= htmlspecialchars(json_encode($room)) ?>)" 
                                            class="w-full px-4 py-2 text-sm bg-blue-500 text-white rounded-lg hover:bg-blue-600 transition-colors">
                                        <i class="fas fa-info-circle mr-2"></i> View Details
                                    </button>
                                </div>
                            </div>
                        </div>
                    <?php endforeach; ?>
                <?php else: ?>
                    <div class="col-span-full text-center py-12">
                        <div class="text-gray-500">
                            <i class="fas fa-door-open text-4xl mb-4 opacity-30"></i>
                            <div class="text-lg mb-2">No rooms found</div>
                            <div class="text-sm">Try adjusting your filters or check back later.</div>
                        </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, $searchFilter) ?>" 
                               class="px-4 py-2 text-sm border border-gray-300 rounded-l-md bg-white text-gray-500 hover:bg-gray-50">
                                <i class="fas fa-chevron-left mr-1"></i> Previous
                            </a>
                        <?php endif; ?>

                        <?php 
                        $start = max(1, $page - 2);
                        $end = min($totalPages, $page + 2);
                        
                        for ($i = $start; $i <= $end; $i++): ?>
                            <a href="<?= buildPaginationUrl($i, $statusFilter, $categoryFilter, $searchFilter) ?>" 
                               class="px-4 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 ($page < $totalPages): ?>
                            <a href="<?= buildPaginationUrl($page + 1, $statusFilter, $categoryFilter, $searchFilter) ?>" 
                               class="px-4 py-2 text-sm border border-gray-300 rounded-r-md bg-white text-gray-500 hover:bg-gray-50">
                                Next <i class="fas fa-chevron-right ml-1"></i>
                            </a>
                        <?php endif; ?>
                    </nav>
                </div>
            <?php endif; ?>
        </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-xl shadow-xl w-96 max-w-full mx-4 relative animate-fade-in">
            <button onclick="closeModal()" class="absolute top-4 right-4 text-gray-400 hover:text-gray-600 text-xl">
                <i class="fas fa-times"></i>
            </button>
            <div class="gradient-bg p-4 rounded-t-xl -m-6 mb-4">
                <h3 class="text-xl font-bold text-white">Room Details</h3>
            </div>
            <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-lg hover:bg-gray-600 transition-colors">
                    Close
                </button>
            </div>
        </div>
    </div>

    <!-- Loading Modal -->
    <div id="loadingModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center hidden z-50">
        <div class="bg-white p-6 rounded-xl shadow-xl animate-fade-in">
            <div class="flex items-center space-x-3">
                <div class="animate-spin rounded-full h-6 w-6 border-b-2 border-blue-600"></div>
                <span class="text-gray-700">Updating room status...</span>
            </div>
        </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();

        function updateRoomStatus(roomId, newStatus, roomNumber) {
            if (!confirm(`Change Room ${roomNumber} status to ${newStatus.toUpperCase()}?`)) {
                return;
            }

            // Show loading modal
            document.getElementById('loadingModal').classList.remove('hidden');

            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 => {
                document.getElementById('loadingModal').classList.add('hidden');
                
                if (data.success) {
                    alert(data.message);
                    location.reload(); // Reload to show updated status
                } else {
                    alert('Error: ' + (data.error || 'Could not update room status.'));
                }
            })
            .catch(error => {
                document.getElementById('loadingModal').classList.add('hidden');
                console.error('Error:', error);
                alert('An error occurred. Please try again.');
            });
        }

        function viewRoomDetails(room) {
            const modal = document.getElementById('roomModal');
            const detailBox = document.getElementById('roomDetails');
            
            detailBox.innerHTML = `
                <div class="grid grid-cols-1 gap-3">
                    <div class="flex justify-between">
                        <span class="font-medium text-gray-700">Room Number:</span>
                        <span class="text-gray-900">${escapeHtml(room.room_number)}</span>
                    </div>
                    <div class="flex justify-between">
                        <span class="font-medium text-gray-700">Category:</span>
                        <span class="text-gray-900">${escapeHtml(room.category_name)}</span>
                    </div>
                    <div class="flex justify-between">
                        <span class="font-medium text-gray-700">Status:</span>
                        <span class="px-2 py-1 text-xs rounded-full ${getStatusClass(room.status)}">${room.status.charAt(0).toUpperCase() + room.status.slice(1)}</span>
                    </div>
                    <div class="flex justify-between">
                        <span class="font-medium text-gray-700">Floor:</span>
                        <span class="text-gray-900">${escapeHtml(room.floor || 'N/A')}</span>
                    </div>
                    <div class="flex justify-between">
                        <span class="font-medium text-gray-700">Price per Night:</span>
                        <span class="text-gray-900">₦${room.price_per_night ? parseFloat(room.price_per_night).toLocaleString() : 'N/A'}</span>
                    </div>
                    <div class="flex justify-between">
                        <span class="font-medium text-gray-700">Description:</span>
                        <span class="text-gray-900 text-right max-w-48">${escapeHtml(room.description || 'No description available')}</span>
                    </div>
                </div>
            `;
            
            modal.classList.remove('hidden');
        }

        function closeModal() {
            document.getElementById('roomModal').classList.add('hidden');
        }

        function escapeHtml(text) {
            const div = document.createElement('div');
            div.textContent = text;
            return div.innerHTML;
        }

        function getStatusClass(status) {
            const classes = {
                'available': 'bg-green-100 text-green-700',
                'booked': 'bg-yellow-100 text-yellow-700', 
                'occupied': 'bg-red-100 text-red-700',
                'maintenance': 'bg-gray-100 text-gray-700'
            };
            return classes[status] || 'bg-blue-100 text-blue-700';
        }

        // Close modal when clicking outside
        document.getElementById('roomModal').addEventListener('click', function(e) {
            if (e.target === this) {
                closeModal();
            }
        });

        // Close modal with Escape key
        document.addEventListener('keydown', function(e) {
            if (e.key === 'Escape') {
                closeModal();
            }
        });
    </script>
</body>
</html>