<?php
session_start();
session_regenerate_id(true);

// Generate CSRF token
if (!isset($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}
$csrf_token = $_SESSION['csrf_token'];

// Enforce HTTPS
if (!isset($_SERVER['HTTPS']) || $_SERVER['HTTPS'] !== 'on') {
    header("Location: https://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']);
    exit();
}

// Disable debug in production
if ($_SERVER['SERVER_NAME'] !== 'localhost') {
    ini_set('display_errors', 0);
    error_reporting(0);
}

// Check if user is logged in
if (!isset($_SESSION['student_id']) || !in_array($_SESSION['role'], ['student', 'admin'])) {
    error_log("Invalid session: student_id or role missing. Redirecting to login.");
    header("Location: login.php");
    exit();
}

// Database connection
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "school_db";

try {
    $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    error_log("Database connection successful.");
} catch(PDOException $e) {
    error_log("Connection failed: " . $e->getMessage());
    $error = "Connection failed. Please contact support.";
    $conn = null;
}

// Fetch user's student details
$user = ['name' => 'Admin', 'admission_no' => 'N/A', 'programme' => 'N/A', 'stage' => 'N/A'];
if ($_SESSION['role'] === 'student' && $conn) {
    try {
        $stmt = $conn->prepare("SELECT name, grade, contact, admission_no, programme, stage FROM students WHERE id = :student_id");
        $stmt->execute([':student_id' => (int)$_SESSION['student_id']]);
        $user = $stmt->fetch(PDO::FETCH_ASSOC);
        if (!$user) {
            error_log("No student found for student_id: " . $_SESSION['student_id']);
            $error = "User data not found.";
        }
    } catch(PDOException $e) {
        error_log("User fetch error: " . $e->getMessage());
        $error = "Error fetching user data.";
    }
}

// Check if student has an active booking
$has_active_booking = false;
if ($_SESSION['role'] === 'student' && $conn) {
    try {
        $stmt = $conn->prepare("SELECT COUNT(*) FROM accommodation_bookings WHERE student_id = :student_id AND status IN ('pending', 'approved')");
        $stmt->execute([':student_id' => (int)$_SESSION['student_id']]);
        $has_active_booking = $stmt->fetchColumn() > 0;
        error_log("Active booking check for student_id " . $_SESSION['student_id'] . ": " . ($has_active_booking ? 'Yes' : 'No'));
    } catch(PDOException $e) {
        error_log("Active booking check error: " . $e->getMessage());
        $error = "Error checking active bookings.";
    }
}

// Fetch bookings
$bookings = [];
if ($conn) {
    try {
        if ($_SESSION['role'] === 'admin') {
            $booking_stmt = $conn->query("SELECT b.*, s.name AS student_name, r.hostel, r.room_number, r.room_type, r.cost_per_semester FROM accommodation_bookings b LEFT JOIN students s ON b.student_id = s.id LEFT JOIN rooms r ON b.room_id = r.id ORDER BY b.submitted_date DESC");
            $bookings = $booking_stmt->fetchAll(PDO::FETCH_ASSOC) ?: [];
        } else {
            $booking_stmt = $conn->prepare("SELECT b.*, r.hostel, r.room_number, r.room_type, r.cost_per_semester FROM accommodation_bookings b LEFT JOIN rooms r ON b.room_id = r.id WHERE b.student_id = :student_id ORDER BY b.submitted_date DESC");
            $booking_stmt->execute([':student_id' => (int)$_SESSION['student_id']]);
            $bookings = $booking_stmt->fetchAll(PDO::FETCH_ASSOC) ?: [];
        }
        error_log("Bookings fetched: " . count($bookings));
    } catch(PDOException $e) {
        error_log("Bookings fetch error: " . $e->getMessage());
        $error = "Error fetching bookings.";
        $bookings = [];
    }
}

// Fetch all rooms for admin management and student form
$rooms = [];
if ($conn) {
    try {
        $room_stmt = $conn->query("SELECT * FROM rooms ORDER BY hostel, room_type, room_number");
        $rooms = $room_stmt->fetchAll(PDO::FETCH_ASSOC);
        error_log("Rooms fetched: " . count($rooms));
    } catch(PDOException $e) {
        error_log("Rooms fetch error: " . $e->getMessage());
        $error = "Error fetching rooms.";
        $rooms = [];
    }
}

// Fetch all students for admin allocation
$students = [];
if ($_SESSION['role'] === 'admin' && $conn) {
    try {
        $student_stmt = $conn->query("SELECT id, name, admission_no FROM students ORDER BY name");
        $students = $student_stmt->fetchAll(PDO::FETCH_ASSOC);
        error_log("Students fetched: " . count($students));
    } catch(PDOException $e) {
        error_log("Students fetch error: " . $e->getMessage());
        $error = "Error fetching students.";
        $students = [];
    }
}

// Handle submit booking (student)
if ($_SESSION['role'] === 'student' && $_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['csrf_token'] === $csrf_token && $conn) {
    if ($_POST['action'] === 'submit_booking') {
        if ($has_active_booking) {
            $error = "You already have an active booking. Please wait for it to be processed or contact support.";
        } else {
            $room_id = filter_input(INPUT_POST, 'room_id', FILTER_VALIDATE_INT);
            $duration = filter_input(INPUT_POST, 'duration', FILTER_SANITIZE_STRING);

            if ($room_id && $duration && in_array($duration, ['Semester', 'Year'])) {
                try {
                    $conn->beginTransaction();
                    // Verify room is available and not booked
                    $stmt = $conn->prepare("SELECT is_available FROM rooms WHERE id = :room_id AND NOT EXISTS (SELECT 1 FROM accommodation_bookings WHERE room_id = :room_id AND status IN ('pending', 'approved'))");
                    $stmt->execute([':room_id' => $room_id]);
                    $room = $stmt->fetch(PDO::FETCH_ASSOC);
                    if ($room && $room['is_available']) {
                        $stmt = $conn->prepare("INSERT INTO accommodation_bookings (student_id, room_id, duration, status, submitted_date) VALUES (:student_id, :room_id, :duration, 'pending', NOW())");
                        $stmt->execute([':student_id' => (int)$_SESSION['student_id'], ':room_id' => $room_id, ':duration' => $duration]);
                        // Mark room as unavailable
                        $stmt = $conn->prepare("UPDATE rooms SET is_available = 0 WHERE id = :room_id");
                        $stmt->execute([':room_id' => $room_id]);
                        $conn->commit();
                        $success = "Booking submitted successfully.";
                        header("Location: accommodation.php?success=" . urlencode($success));
                        exit();
                    } else {
                        $conn->rollBack();
                        $error = "Selected room is not available or already booked.";
                    }
                } catch(PDOException $e) {
                    $conn->rollBack();
                    error_log("Submit booking error: " . $e->getMessage());
                    $error = "Error submitting booking.";
                }
            } else {
                $error = "All fields are required or invalid.";
            }
        }
    }
}

// Handle admin allocation
if ($_SESSION['role'] === 'admin' && $_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['csrf_token'] === $csrf_token && $conn) {
    if ($_POST['action'] === 'allocate_room') {
        $student_id = filter_input(INPUT_POST, 'student_id', FILTER_VALIDATE_INT);
        $room_id = filter_input(INPUT_POST, 'room_id', FILTER_VALIDATE_INT);
        $duration = filter_input(INPUT_POST, 'duration', FILTER_SANITIZE_STRING);

        if ($student_id && $room_id && $duration && in_array($duration, ['Semester', 'Year'])) {
            try {
                $conn->beginTransaction();
                // Check if student has an active booking
                $stmt = $conn->prepare("SELECT COUNT(*) FROM accommodation_bookings WHERE student_id = :student_id AND status IN ('pending', 'approved')");
                $stmt->execute([':student_id' => $student_id]);
                if ($stmt->fetchColumn() > 0) {
                    $conn->rollBack();
                    $error = "Student already has an active booking.";
                } else {
                    // Verify room is available
                    $stmt = $conn->prepare("SELECT is_available FROM rooms WHERE id = :room_id AND NOT EXISTS (SELECT 1 FROM accommodation_bookings WHERE room_id = :room_id AND status IN ('pending', 'approved'))");
                    $stmt->execute([':room_id' => $room_id]);
                    $room = $stmt->fetch(PDO::FETCH_ASSOC);
                    if ($room && $room['is_available']) {
                        $stmt = $conn->prepare("INSERT INTO accommodation_bookings (student_id, room_id, duration, status, submitted_date) VALUES (:student_id, :room_id, :duration, 'approved', NOW())");
                        $stmt->execute([':student_id' => $student_id, ':room_id' => $room_id, ':duration' => $duration]);
                        // Mark room as unavailable
                        $stmt = $conn->prepare("UPDATE rooms SET is_available = 0 WHERE id = :room_id");
                        $stmt->execute([':room_id' => $room_id]);
                        $conn->commit();
                        $success = "Room allocated successfully.";
                        header("Location: accommodation.php?success=" . urlencode($success));
                        exit();
                    } else {
                        $conn->rollBack();
                        $error = "Selected room is not available or already booked.";
                    }
                }
            } catch(PDOException $e) {
                $conn->rollBack();
                error_log("Allocate room error: " . $e->getMessage());
                $error = "Error allocating room.";
            }
        } else {
            $error = "All fields are required or invalid.";
        }
    }
}

// Handle delete booking (admin)
if ($_SESSION['role'] === 'admin' && $_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['csrf_token'] === $csrf_token && $conn) {
    if ($_POST['action'] === 'delete_booking') {
        $booking_id = filter_input(INPUT_POST, 'booking_id', FILTER_VALIDATE_INT);
        if ($booking_id) {
            try {
                $conn->beginTransaction();
                // Fetch room_id before deleting booking
                $stmt = $conn->prepare("SELECT room_id FROM accommodation_bookings WHERE id = :booking_id");
                $stmt->execute([':booking_id' => $booking_id]);
                $booking = $stmt->fetch(PDO::FETCH_ASSOC);
                if ($booking) {
                    $stmt = $conn->prepare("DELETE FROM accommodation_bookings WHERE id = :booking_id");
                    $stmt->execute([':booking_id' => $booking_id]);
                    // Mark room as available
                    $stmt = $conn->prepare("UPDATE rooms SET is_available = 1 WHERE id = :room_id");
                    $stmt->execute([':room_id' => $booking['room_id']]);
                    $conn->commit();
                    $success = "Booking deleted successfully.";
                    header("Location: accommodation.php?success=" . urlencode($success));
                    exit();
                } else {
                    $conn->rollBack();
                    $error = "Booking not found.";
                }
            } catch(PDOException $e) {
                $conn->rollBack();
                error_log("Delete booking error: " . $e->getMessage());
                $error = "Error deleting booking.";
            }
        } else {
            $error = "Invalid booking ID.";
        }
    }
}

// Handle add/edit/delete room (admin)
if ($_SESSION['role'] === 'admin' && $_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['csrf_token'] === $csrf_token && $conn) {
    if ($_POST['action'] === 'add_room') {
        $hostel = filter_input(INPUT_POST, 'hostel', FILTER_SANITIZE_STRING);
        $room_number = filter_input(INPUT_POST, 'room_number', FILTER_SANITIZE_STRING);
        $room_type = filter_input(INPUT_POST, 'room_type', FILTER_SANITIZE_STRING);
        $cost_per_semester = filter_input(INPUT_POST, 'cost_per_semester', FILTER_VALIDATE_FLOAT);
        $is_available = isset($_POST['is_available']) ? 1 : 0;

        if ($hostel && $room_number && $room_type && $cost_per_semester !== false) {
            try {
                $stmt = $conn->prepare("INSERT INTO rooms (hostel, room_number, room_type, cost_per_semester, is_available) VALUES (:hostel, :room_number, :room_type, :cost_per_semester, :is_available)");
                $stmt->execute([
                    ':hostel' => $hostel,
                    ':room_number' => $room_number,
                    ':room_type' => $room_type,
                    ':cost_per_semester' => $cost_per_semester,
                    ':is_available' => $is_available
                ]);
                $success = "Room added successfully.";
                header("Location: accommodation.php?success=" . urlencode($success));
                exit();
            } catch(PDOException $e) {
                error_log("Add room error: " . $e->getMessage());
                $error = "Error adding room.";
            }
        } else {
            $error = "All fields are required or invalid.";
        }
    } elseif ($_POST['action'] === 'edit_room') {
        $room_id = filter_input(INPUT_POST, 'room_id', FILTER_VALIDATE_INT);
        $hostel = filter_input(INPUT_POST, 'hostel', FILTER_SANITIZE_STRING);
        $room_number = filter_input(INPUT_POST, 'room_number', FILTER_SANITIZE_STRING);
        $room_type = filter_input(INPUT_POST, 'room_type', FILTER_SANITIZE_STRING);
        $cost_per_semester = filter_input(INPUT_POST, 'cost_per_semester', FILTER_VALIDATE_FLOAT);
        $is_available = isset($_POST['is_available']) ? 1 : 0;

        if ($room_id && $hostel && $room_number && $room_type && $cost_per_semester !== false) {
            try {
                $conn->beginTransaction();
                $stmt = $conn->prepare("UPDATE rooms SET hostel = :hostel, room_number = :room_number, room_type = :room_type, cost_per_semester = :cost_per_semester, is_available = :is_available WHERE id = :room_id");
                $stmt->execute([
                    ':hostel' => $hostel,
                    ':room_number' => $room_number,
                    ':room_type' => $room_type,
                    ':cost_per_semester' => $cost_per_semester,
                    ':is_available' => $is_available,
                    ':room_id' => $room_id
                ]);
                $conn->commit();
                $success = "Room updated successfully.";
                header("Location: accommodation.php?success=" . urlencode($success));
                exit();
            } catch(PDOException $e) {
                $conn->rollBack();
                error_log("Edit room error: " . $e->getMessage());
                $error = "Error updating room.";
            }
        } else {
            $error = "All fields are required or invalid.";
        }
    } elseif ($_POST['action'] === 'delete_room') {
        $room_id = filter_input(INPUT_POST, 'room_id', FILTER_VALIDATE_INT);
        if ($room_id) {
            try {
                $conn->beginTransaction();
                $stmt = $conn->prepare("SELECT COUNT(*) FROM accommodation_bookings WHERE room_id = :room_id AND status IN ('pending', 'approved')");
                $stmt->execute([':room_id' => $room_id]);
                if ($stmt->fetchColumn() > 0) {
                    $conn->rollBack();
                    $error = "Cannot delete room with active bookings.";
                } else {
                    $stmt = $conn->prepare("DELETE FROM rooms WHERE id = :room_id");
                    $stmt->execute([':room_id' => $room_id]);
                    $conn->commit();
                    $success = "Room deleted successfully.";
                    header("Location: accommodation.php?success=" . urlencode($success));
                    exit();
                }
            } catch(PDOException $e) {
                $conn->rollBack();
                error_log("Delete room error: " . $e->getMessage());
                $error = "Error deleting room.";
            }
        } else {
            $error = "Invalid room ID.";
        }
    }
}

// Handle update booking status (admin)
if ($_SESSION['role'] === 'admin' && $_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'update_status' && $_POST['csrf_token'] === $csrf_token && $conn) {
    $booking_id = filter_input(INPUT_POST, 'booking_id', FILTER_VALIDATE_INT);
    $status = filter_input(INPUT_POST, 'status', FILTER_SANITIZE_STRING);
    if ($booking_id && in_array($status, ['approved', 'rejected'])) {
        try {
            $conn->beginTransaction();
            // If rejecting, make room available again
            if ($status === 'rejected') {
                $stmt = $conn->prepare("SELECT room_id FROM accommodation_bookings WHERE id = :booking_id");
                $stmt->execute([':booking_id' => $booking_id]);
                $booking = $stmt->fetch(PDO::FETCH_ASSOC);
                if ($booking) {
                    $stmt = $conn->prepare("UPDATE rooms SET is_available = 1 WHERE id = :room_id");
                    $stmt->execute([':room_id' => $booking['room_id']]);
                }
            }
            $stmt = $conn->prepare("UPDATE accommodation_bookings SET status = :status WHERE id = :booking_id");
            $stmt->execute([':status' => $status, ':booking_id' => $booking_id]);
            $conn->commit();
            $success = "Booking status updated to $status.";
            header("Location: accommodation.php?success=" . urlencode($success));
            exit();
        } catch(PDOException $e) {
            $conn->rollBack();
            error_log("Update booking status error: " . $e->getMessage());
            $error = "Error updating booking status.";
        }
    } else {
        $error = "Invalid booking ID or status.";
    }
}

// Handle logout
if (isset($_POST['logout']) && $_POST['csrf_token'] === $csrf_token) {
    session_unset();
    session_destroy();
    header("Location: login.php");
    exit();
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="Book and manage accommodation at Cypher University.">
    <meta name="keywords" content="Cypher University, student portal, accommodation booking">
    <meta name="author" content="Cypher University">
    <title>Accommodation Booking - Cypher University</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.5/font/bootstrap-icons.css">
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;600&display=swap" rel="stylesheet">
    <style>
        * {
            box-sizing: border-box;
        }
        body {
            font-family: 'Poppins', sans-serif;
            background-color: #f5f6f5;
            color: #333;
            margin: 0;
            overflow-x: hidden;
        }
        .navbar {
            background-color: #003087;
            padding: 8px 0;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
            z-index: 1001;
            position: sticky;
            top: 0;
        }
        .navbar-brand {
            font-size: 1.25rem;
            font-weight: 600;
            color: #fff !important;
        }
        .nav-link {
            font-size: 0.9rem;
            color: #fff !important;
            padding: 6px 12px;
            transition: color 0.3s ease, background-color 0.3s ease;
        }
        .nav-link:hover {
            color: #a9d6e5 !important;
            background-color: rgba(255, 255, 255, 0.1);
            border-radius: 4px;
        }
        .navbar-toggler {
            border-color: rgba(255, 255, 255, 0.5);
        }
        .sidebar {
            position: fixed;
            top: 48px;
            left: 0;
            width: 250px;
            height: calc(100vh - 48px);
            background-color: #003087;
            color: #fff;
            overflow-y: auto;
            z-index: 1000;
            box-shadow: 2px 0 4px rgba(0, 0, 0, 0.1);
            transition: transform 0.3s ease;
        }
        .sidebar-header {
            border-bottom: 1px solid rgba(255, 255, 255, 0.2);
        }
        .sidebar .nav-link {
            font-size: 0.95rem;
            padding: 10px 15px;
            color: #fff;
            transition: background-color 0.3s ease, padding-left 0.3s ease;
        }
        .sidebar .nav-link:hover {
            background-color: rgba(255, 255, 255, 0.1);
            padding-left: 20px;
        }
        .profile-card {
            background: rgba(255, 255, 255, 0.05);
            border-radius: 8px;
            margin: 15px;
            padding: 15px;
        }
        .avatar {
            width: 80px;
            height: 80px;
            display: flex;
            align-items: center;
            justify-content: center;
            border-radius: 50%;
        }
        main {
            margin-left: 250px;
            padding: 20px;
            min-height: calc(100vh - 48px - 80px);
            overflow-y: auto;
            background-color: #fff;
            border-radius: 8px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
        }
        footer {
            position: relative;
            background-color: #003087;
            color: #fff;
            padding: 20px 0;
            margin-top: 20px;
        }
        footer a {
            color: #a9d6e5;
            text-decoration: none;
            transition: color 0.3s ease;
        }
        footer a:hover {
            color: #fff;
        }
        .hero-section {
            background: linear-gradient(135deg, #003087, #005f73);
            border-radius: 8px;
            padding: 20px;
            margin-bottom: 2rem;
        }
        .hero-section h1 {
            font-size: 1.75rem;
            font-weight: 600;
        }
        .hero-section p {
            font-size: 1rem;
        }
        .section-title {
            font-size: 1.75rem;
            color: #003087;
            margin-bottom: 1rem;
            position: relative;
        }
        .section-title::after {
            content: '';
            display: block;
            width: 50px;
            height: 3px;
            background: #003087;
            margin-top: 0.5rem;
        }
        .card {
            border: none;
            border-radius: 8px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
            transition: transform 0.3s ease, box-shadow 0.3s ease;
        }
        .card:hover {
            transform: translateY(-5px);
            box-shadow: 0 6px 16px rgba(0, 0, 0, 0.2);
        }
        .card-title {
            font-size: 1.25rem;
            color: #003087;
            margin-bottom: 0.75rem;
        }
        .card-body {
            padding: 1.5rem;
        }
        .btn-primary {
            background-color: #003087;
            border: none;
            padding: 0.75rem 1.5rem;
            border-radius: 8px;
            transition: background-color 0.3s ease;
        }
        .btn-primary:hover {
            background-color: #00205b;
        }
        .btn-outline-primary {
            border-color: #003087;
            color: #003087;
        }
        .btn-outline-primary:hover {
            background-color: #003087;
            color: #fff;
        }
        .btn-outline-success {
            border-color: #28a745;
            color: #28a745;
        }
        .btn-outline-success:hover {
            background-color: #28a745;
            color: #fff;
        }
        .btn-outline-danger {
            border-color: #dc3545;
            color: #dc3545;
        }
        .btn-outline-danger:hover {
            background-color: #dc3545;
            color: #fff;
        }
        .table {
            margin-top: 1rem;
        }
        .table th {
            background-color: #e9ecef;
            color: #003087;
        }
        .form-control {
            border-radius: 8px;
            border: 1px solid #ced4da;
            transition: border-color 0.3s ease, box-shadow 0.3s ease;
        }
        .form-control:focus {
            border-color: #003087;
            box-shadow: 0 0 5px rgba(0, 48, 135, 0.5);
        }
        .form-control:disabled {
            background-color: #e9ecef;
            cursor: not-allowed;
        }
        .form-label {
            color: #003087;
        }
        .alert {
            border-radius: 8px;
            font-size: 0.9rem;
        }
        #cost-display, #admin_cost-display {
            font-weight: 600;
            color: #003087;
            margin-top: 0.5rem;
        }
        @media (max-width: 991px) {
            .sidebar {
                display: none;
            }
            main {
                margin-left: 0;
            }
            .navbar-brand {
                font-size: 1.1rem;
            }
            .nav-link {
                font-size: 0.85rem;
            }
            .hero-section {
                padding: 2rem 0;
            }
            .hero-section h1 {
                font-size: 1.5rem;
            }
            .section-title {
                font-size: 1.5rem;
            }
        }
    </style>
</head>
<body>
    <nav class="navbar navbar-expand-lg navbar-dark sticky-top">
        <div class="container">
            <a class="navbar-brand" href="index.php">Cypher University</a>
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="navbarNav">
                <ul class="navbar-nav ms-auto">
                    <li class="nav-item"><a class="nav-link" href="index.php">Home</a></li>
                    <li class="nav-item"><a class="nav-link" href="about.php">About</a></li>
                    <li class="nav-item"><a class="nav-link" href="contact.php">Contact</a></li>
                    <li class="nav-item"><a class="nav-link" href="news.php">News</a></li>
                    <li class="nav-item">
                        <form method="POST" action="accommodation.php" style="display:inline;">
                            <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars($csrf_token); ?>">
                            <button type="submit" name="logout" class="nav-link btn btn-link text-white">Logout</button>
                        </form>
                    </li>
                </ul>
            </div>
        </div>
    </nav>

    <div class="d-flex">
        <nav class="sidebar bg-primary text-white" id="sidebar">
            <div class="sidebar-header text-center p-3">
                <h4 class="mb-0">Cypher University</h4>
            </div>
            <div class="profile-card">
                <div class="text-center">
                    <div class="avatar bg-light text-primary rounded-circle mx-auto mb-2">
                        <i class="bi bi-person-circle fs-2"></i>
                    </div>
                    <h6 class="mb-1"><?php echo htmlspecialchars($user['name']); ?></h6>
                    <small class="text-white-50">Admission No: <?php echo htmlspecialchars($user['admission_no']); ?></small><br>
                    <small class="text-white-50">Programme: <?php echo htmlspecialchars($user['programme']); ?></small><br>
                    <small class="text-white-50">Stage: <?php echo htmlspecialchars($user['stage']); ?></small>
                </div>
            </div>
            <h5 class="p-3">MAIN NAVIGATION</h5>
            <ul class="nav flex-column p-3">
                <li class="nav-item">
                    <a class="nav-link text-white" href="<?php echo $_SESSION['role'] === 'admin' ? 'admin_page.php' : 'student_dashboard.php'; ?>"><i class="bi bi-house me-2"></i>Dashboard</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link text-white" href="financials.php"><i class="bi bi-wallet me-2"></i>Financials</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link text-white" href="academics.php"><i class="bi bi-book me-2"></i>Academics</a>
                </li>
                <?php if ($_SESSION['role'] === 'admin'): ?>
                    <li class="nav-item">
                        <a class="nav-link text-white" href="manage_students.php"><i class="bi bi-people me-2"></i>Manage Students</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link text-white" href="manage_news.php"><i class="bi bi-newspaper me-2"></i>Manage News</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link text-white" href="manage_timetables.php"><i class="bi bi-calendar me-2"></i>Manage Timetables</a>
                    </li>
                <?php endif; ?>
                <li class="nav-item">
                    <a class="nav-link text-white" href="student_requests.php"><i class="bi bi-file-text me-2"></i>Student Requests</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link text-white active" href="accommodation.php"><i class="bi bi-building me-2"></i>Accommodation</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link text-white" href="special_exams.php"><i class="bi bi-pencil-square me-2"></i>Special Exams</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link text-white" href="downloads.php"><i class="bi bi-download me-2"></i>Downloads</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link text-white" href="clearance.php"><i class="bi bi-check-circle me-2"></i>Students Clearance</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link text-white" href="transfer.php"><i class="bi bi-arrow-left-right me-2"></i>Inter-School Transfer</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link text-white" href="settings.php"><i class="bi bi-gear me-2"></i>Settings</a>
                </li>
                <li class="nav-item">
                    <form method="POST">
                        <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars($csrf_token); ?>">
                        <button type="submit" name="logout" class="nav-link text-white bg-transparent border-0"><i class="bi bi-box-arrow-right me-2"></i>Logout</button>
                    </form>
                </li>
            </ul>
            <h5 class="p-3">PERIODIC ACTIVITIES</h5>
            <ul class="nav flex-column p-3">
                <li class="nav-item">
                    <a class="nav-link text-white" href="lecturers_evaluation.php"><i class="bi bi-person-check me-2"></i>Lecturers Evaluation</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link text-white" href="msu_election.php"><i class="bi bi-box-seam me-2"></i>MSU Election</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link text-white" href="notice_board.php"><i class="bi bi-megaphone me-2"></i>Notice Board</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link text-white" href="https://facebook.com/Cypher" target="_blank"><i class="bi bi-facebook me-2"></i>MSU Official Facebook</a>
                </li>
            </ul>
        </nav>

        <main class="flex-grow-1 p-4">
            <button class="btn btn-primary d-lg-none mb-3" type="button" data-bs-toggle="offcanvas" data-bs-target="#sidebarOffcanvas" aria-controls="sidebarOffcanvas">
                <i class="bi bi-list"></i> Menu
            </button>
            <div class="offcanvas offcanvas-start bg-primary text-white" tabindex="-1" id="sidebarOffcanvas" aria-labelledby="sidebarOffcanvasLabel">
                <div class="offcanvas-header">
                    <h5 class="offcanvas-title" id="sidebarOffcanvasLabel">Cypher University</h5>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="offcanvas" aria-label="Close"></button>
                </div>
                <div class="offcanvas-body">
                    <div class="profile-card">
                        <div class="text-center">
                            <div class="avatar bg-light text-primary rounded-circle mx-auto mb-2">
                                <i class="bi bi-person-circle fs-2"></i>
                            </div>
                            <h6 class="mb-1"><?php echo htmlspecialchars($user['name']); ?></h6>
                            <small class="text-white-50">Admission No: <?php echo htmlspecialchars($user['admission_no']); ?></small><br>
                            <small class="text-white-50">Programme: <?php echo htmlspecialchars($user['programme']); ?></small><br>
                            <small class="text-white-50">Stage: <?php echo htmlspecialchars($user['stage']); ?></small>
                        </div>
                    </div>
                    <h5>MAIN NAVIGATION</h5>
                    <ul class="nav flex-column">
                        <li class="nav-item">
                            <a class="nav-link text-white" href="<?php echo $_SESSION['role'] === 'admin' ? 'admin_page.php' : 'student_dashboard.php'; ?>"><i class="bi bi-house me-2"></i>Dashboard</a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link text-white" href="financials.php"><i class="bi bi-wallet me-2"></i>Financials</a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link text-white" href="academics.php"><i class="bi bi-book me-2"></i>Academics</a>
                        </li>
                        <?php if ($_SESSION['role'] === 'admin'): ?>
                            <li class="nav-item">
                                <a class="nav-link text-white" href="manage_students.php"><i class="bi bi-people me-2"></i>Manage Students</a>
                            </li>
                            <li class="nav-item">
                                <a class="nav-link text-white" href="manage_news.php"><i class="bi bi-newspaper me-2"></i>Manage News</a>
                            </li>
                            <li class="nav-item">
                                <a class="nav-link text-white" href="manage_timetables.php"><i class="bi bi-calendar me-2"></i>Manage Timetables</a>
                            </li>
                        <?php endif; ?>
                        <li class="nav-item">
                            <a class="nav-link text-white" href="student_requests.php"><i class="bi bi-file-text me-2"></i>Student Requests</a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link text-white active" href="accommodation.php"><i class="bi bi-building me-2"></i>Accommodation</a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link text-white" href="special_exams.php"><i class="bi bi-pencil-square me-2"></i>Special Exams</a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link text-white" href="downloads.php"><i class="bi bi-download me-2"></i>Downloads</a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link text-white" href="clearance.php"><i class="bi bi-check-circle me-2"></i>Students Clearance</a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link text-white" href="transfer.php"><i class="bi bi-arrow-left-right me-2"></i>Inter-School Transfer</a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link text-white" href="settings.php"><i class="bi bi-gear me-2"></i>Settings</a>
                        </li>
                        <li class="nav-item">
                            <form method="POST">
                                <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars($csrf_token); ?>">
                                <button type="submit" name="logout" class="nav-link text-white bg-transparent border-0"><i class="bi bi-box-arrow-right me-2"></i>Logout</button>
                            </form>
                        </li>
                    </ul>
                    <h5>PERIODIC ACTIVITIES</h5>
                    <ul class="nav flex-column">
                        <li class="nav-item">
                            <a class="nav-link text-white" href="lecturers_evaluation.php"><i class="bi bi-person-check me-2"></i>Lecturers Evaluation</a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link text-white" href="msu_election.php"><i class="bi bi-box-seam me-2"></i>MSU Election</a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link text-white" href="notice_board.php"><i class="bi bi-megaphone me-2"></i>Notice Board</a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link text-white" href="https://facebook.com/Cypher" target="_blank"><i class="bi bi-facebook me-2"></i>MSU Official Facebook</a>
                        </li>
                    </ul>
                </div>
            </div>

            <header class="hero-section text-white text-center py-4 rounded mb-4">
                <h1 class="display-5">Accommodation Booking</h1>
                <p class="lead">Book your accommodation</p>
                <small class="text-white-50">Online</small>
            </header>

            <?php if (isset($error)): ?>
                <div class="alert alert-danger alert-dismissible fade show" role="alert">
                    <?php echo htmlspecialchars($error); ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                </div>
            <?php endif; ?>
            <?php if (isset($success) || (isset($_GET['success']) && $_GET['success'])): ?>
                <div class="alert alert-success alert-dismissible fade show" role="alert">
                    <?php echo htmlspecialchars($success ?? $_GET['success']); ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                </div>
            <?php endif; ?>

            <?php if ($_SESSION['role'] === 'student'): ?>
                <section class="mb-5">
                    <h2 class="section-title">Book Accommodation</h2>
                    <div class="card">
                        <div class="card-body">
                            <?php if ($has_active_booking): ?>
                                <div class="alert alert-info">
                                    You have an active booking. Please wait for it to be processed or contact support to make changes.
                                </div>
                            <?php elseif (empty($rooms)): ?>
                                <div class="alert alert-warning">
                                    No rooms are available for booking at this time.
                                </div>
                            <?php else: ?>
                                <form method="POST" id="booking-form" onsubmit="return validateBookingForm() && confirm('Are you sure you want to submit this booking?');">
                                    <input type="hidden" name="action" value="submit_booking">
                                    <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars($csrf_token); ?>">
                                    <div class="mb-3">
                                        <label for="hostel" class="form-label">Hostel</label>
                                        <select id="hostel" name="hostel" class="form-control" required>
                                            <option value="">Select Hostel</option>
                                            <?php
                                            $hostels = array_unique(array_column($rooms, 'hostel'));
                                            foreach ($hostels as $hostel):
                                                $available_rooms = array_filter($rooms, function($room) use ($hostel, $bookings) {
                                                    return $room['hostel'] === $hostel && $room['is_available'] && !in_array((int)$room['id'], array_map(function($b) { return (int)$b['room_id']; }, $bookings));
                                                });
                                                if (!empty($available_rooms)):
                                            ?>
                                                <option value="<?php echo htmlspecialchars($hostel); ?>"><?php echo htmlspecialchars($hostel); ?></option>
                                            <?php endif; ?>
                                        <?php endforeach; ?>
                                        </select>
                                        <?php if (empty($hostels)): ?>
                                            <small class="text-danger">No hostels with available rooms found.</small>
                                        <?php endif; ?>
                                    </div>
                                    <div class="mb-3">
                                        <label for="room_type" class="form-label">Room Type</label>
                                        <select id="room_type" name="room_type" class="form-control" required disabled>
                                            <option value="">Select a hostel first</option>
                                        </select>
                                    </div>
                                    <div class="mb-3">
                                        <label for="room_id" class="form-label">Room</label>
                                        <select id="room_id" name="room_id" class="form-control" required disabled>
                                            <option value="">Select a room type first</option>
                                        </select>
                                    </div>
                                    <div class="mb-3">
                                        <label for="duration" class="form-label">Duration</label>
                                        <select id="duration" name="duration" class="form-control" required>
                                            <option value="">Select Duration</option>
                                            <option value="Semester">Semester</option>
                                            <option value="Year">Year</option>
                                        </select>
                                    </div>
                                    <div id="cost-display" class="mb-3">Cost: Select a room and duration to see cost</div>
                                    <button type="submit" class="btn btn-primary">Submit Booking</button>
                                </form>
                            <?php endif; ?>
                        </div>
                    </div>
                </section>
            <?php endif; ?>

            <?php if ($_SESSION['role'] === 'admin'): ?>
                <section class="mb-5">
                    <h2 class="section-title">Allocate Room to Student</h2>
                    <div class="card">
                        <div class="card-body">
                            <?php if (empty($students) || empty($rooms)): ?>
                                <div class="alert alert-warning">
                                    <?php echo empty($students) ? "No students available for allocation." : "No rooms available for allocation."; ?>
                                </div>
                            <?php else: ?>
                                <form method="POST" id="allocation-form" onsubmit="return validateAllocationForm() && confirm('Are you sure you want to allocate this room?');">
                                    <input type="hidden" name="action" value="allocate_room">
                                    <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars($csrf_token); ?>">
                                    <div class="mb-3">
                                        <label for="student_id" class="form-label">Student</label>
                                        <select id="student_id" name="student_id" class="form-control" required>
                                            <option value="">Select Student</option>
                                            <?php foreach ($students as $student): ?>
                                                <option value="<?php echo htmlspecialchars($student['id']); ?>">
                                                    <?php echo htmlspecialchars($student['name'] . ' (' . $student['admission_no'] . ')'); ?>
                                                </option>
                                            <?php endforeach; ?>
                                        </select>
                                    </div>
                                    <div class="mb-3">
                                        <label for="admin_hostel" class="form-label">Hostel</label>
                                        <select id="admin_hostel" name="hostel" class="form-control" required>
                                            <option value="">Select Hostel</option>
                                            <?php
                                            foreach ($hostels as $hostel):
                                                $available_rooms = array_filter($rooms, function($room) use ($hostel, $bookings) {
                                                    return $room['hostel'] === $hostel && $room['is_available'] && !in_array((int)$room['id'], array_map(function($b) { return (int)$b['room_id']; }, $bookings));
                                                });
                                                if (!empty($available_rooms)):
                                            ?>
                                                <option value="<?php echo htmlspecialchars($hostel); ?>"><?php echo htmlspecialchars($hostel); ?></option>
                                            <?php endif; ?>
                                            <?php endforeach; ?>
                                        </select>
                                        <?php if (empty($hostels)): ?>
                                            <small class="text-danger">No hostels with available rooms found.</small>
                                        <?php endif; ?>
                                    </div>
                                    <div class="mb-3">
                                        <label for="admin_room_type" class="form-label">Room Type</label>
                                        <select id="admin_room_type" name="room_type" class="form-control" required disabled>
                                            <option value="">Select a hostel first</option>
                                        </select>
                                    </div>
                                    <div class="mb-3">
                                        <label for="admin_room_id" class="form-label">Room</label>
                                        <select id="admin_room_id" name="room_id" class="form-control" required disabled>
                                            <option value="">Select a room type first</option>
                                        </select>
                                    </div>
                                    <div class="mb-3">
                                        <label for="admin_duration" class="form-label">Duration</label>
                                        <select id="admin_duration" name="duration" class="form-control" required>
                                            <option value="">Select Duration</option>
                                            <option value="Semester">Semester</option>
                                            <option value="Year">Year</option>
                                        </select>
                                    </div>
                                    <div id="admin_cost-display" class="mb-3">Cost: Select a room and duration to see cost</div>
                                    <button type="submit" class="btn btn-primary">Allocate Room</button>
                                </form>
                            <?php endif; ?>
                        </div>
                    </div>
                </section>

                <section class="mb-5">
                    <h2 class="section-title">Manage Rooms</h2>
                    <div class="card">
                        <div class="card-body">
                            <button class="btn btn-primary mb-3" data-bs-toggle="modal" data-bs-target="#addRoomModal">Add New Room</button>
                            <div class="table-responsive">
                                <table class="table table-bordered table-striped">
                                    <thead>
                                        <tr>
                                            <th scope="col">Hostel</th>
                                            <th scope="col">Room Number</th>
                                            <th scope="col">Room Type</th>
                                            <th scope="col">Cost per Semester</th>
                                            <th scope="col">Available</th>
                                            <th scope="col">Actions</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php if (!empty($rooms)): ?>
                                            <?php foreach ($rooms as $room): ?>
                                                <tr>
                                                    <td><?php echo htmlspecialchars($room['hostel']); ?></td>
                                                    <td><?php echo htmlspecialchars($room['room_number']); ?></td>
                                                    <td><?php echo htmlspecialchars($room['room_type']); ?></td>
                                                    <td><?php echo number_format($room['cost_per_semester'], 2); ?></td>
                                                    <td><?php echo $room['is_available'] ? 'Yes' : 'No'; ?></td>
                                                    <td>
                                                        <button class="btn btn-outline-primary btn-sm edit-room-btn" 
                                                                data-bs-toggle="modal" 
                                                                data-bs-target="#editRoomModal" 
                                                                data-room-id="<?php echo htmlspecialchars($room['id']); ?>"
                                                                data-hostel="<?php echo htmlspecialchars($room['hostel']); ?>"
                                                                data-room-number="<?php echo htmlspecialchars($room['room_number']); ?>"
                                                                data-room-type="<?php echo htmlspecialchars($room['room_type']); ?>"
                                                                data-cost="<?php echo htmlspecialchars($room['cost_per_semester']); ?>"
                                                                data-is-available="<?php echo $room['is_available'] ? '1' : '0'; ?>">Edit</button>
                                                        <form method="POST" style="display: inline;" onsubmit="return confirm('Are you sure you want to delete this room?');">
                                                            <input type="hidden" name="action" value="delete_room">
                                                            <input type="hidden" name="room_id" value="<?php echo htmlspecialchars($room['id']); ?>">
                                                            <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars($csrf_token); ?>">
                                                            <button type="submit" class="btn btn-outline-danger btn-sm">Delete</button>
                                                        </form>
                                                    </td>
                                                </tr>
                                            <?php endforeach; ?>
                                        <?php else: ?>
                                            <tr><td colspan="6" class="text-center">No rooms found.</td></tr>
                                        <?php endif; ?>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                    <!-- Single Edit Room Modal -->
                    <div class="modal fade" id="editRoomModal" tabindex="-1" aria-labelledby="editRoomModalLabel" aria-hidden="true">
                        <div class="modal-dialog">
                            <div class="modal-content">
                                <div class="modal-header">
                                    <h5 class="modal-title" id="editRoomModalLabel">Edit Room</h5>
                                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                                </div>
                                <div class="modal-body">
                                    <form method="POST" id="edit-room-form">
                                        <input type="hidden" name="action" value="edit_room">
                                        <input type="hidden" name="room_id" id="edit_room_id">
                                        <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars($csrf_token); ?>">
                                        <div class="mb-3">
                                            <label for="edit_hostel" class="form-label">Hostel</label>
                                            <input type="text" id="edit_hostel" name="hostel" class="form-control" required>
                                        </div>
                                        <div class="mb-3">
                                            <label for="edit_room_number" class="form-label">Room Number</label>
                                            <input type="text" id="edit_room_number" name="room_number" class="form-control" required>
                                        </div>
                                        <div class="mb-3">
                                            <label for="edit_room_type" class="form-label">Room Type</label>
                                            <select id="edit_room_type" name="room_type" class="form-control" required>
                                                <option value="Single">Single</option>
                                                <option value="Double">Double</option>
                                                <option value="Shared">Shared</option>
                                            </select>
                                        </div>
                                        <div class="mb-3">
                                            <label for="edit_cost_per_semester" class="form-label">Cost per Semester</label>
                                            <input type="number" id="edit_cost_per_semester" name="cost_per_semester" class="form-control" step="0.01" required>
                                        </div>
                                        <div class="mb-3">
                                            <label for="edit_is_available" class="form-label">Available</label>
                                            <input type="checkbox" id="edit_is_available" name="is_available" value="1">
                                        </div>
                                        <button type="submit" class="btn btn-primary">Save Changes</button>
                                    </form>
                                </div>
                            </div>
                        </div>
                    </div>
                    <!-- Add Room Modal -->
                    <div class="modal fade" id="addRoomModal" tabindex="-1" aria-labelledby="addRoomModalLabel" aria-hidden="true">
                        <div class="modal-dialog">
                            <div class="modal-content">
                                <div class="modal-header">
                                    <h5 class="modal-title" id="addRoomModalLabel">Add New Room</h5>
                                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                                </div>
                                <div class="modal-body">
                                    <form method="POST" id="add-room-form" onsubmit="return validateAddRoomForm()">
                                        <input type="hidden" name="action" value="add_room">
                                        <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars($csrf_token); ?>">
                                        <div class="mb-3">
                                            <label for="hostel" class="form-label">Hostel</label>
                                            <input type="text" id="hostel" name="hostel" class="form-control" required>
                                        </div>
                                        <div class="mb-3">
                                            <label for="room_number" class="form-label">Room Number</label>
                                            <input type="text" id="room_number" name="room_number" class="form-control" required>
                                        </div>
                                        <div class="mb-3">
                                            <label for="room_type" class="form-label">Room Type</label>
                                            <select id="room_type" name="room_type" class="form-control" required>
                                                <option value="Single">Single</option>
                                                <option value="Double">Double</option>
                                                <option value="Shared">Shared</option>
                                            </select>
                                        </div>
                                        <div class="mb-3">
                                            <label for="cost_per_semester" class="form-label">Cost per Semester</label>
                                            <input type="number" id="cost_per_semester" name="cost_per_semester" class="form-control" step="0.01" required>
                                        </div>
                                        <div class="mb-3">
                                            <label for="is_available" class="form-label">Available</label>
                                            <input type="checkbox" id="is_available" name="is_available" value="1" checked>
                                        </div>
                                        <button type="submit" class="btn btn-primary">Add Room</button>
                                    </form>
                                </div>
                            </div>
                        </div>
                    </div>
                </section>
            <?php endif; ?>

            <section class="mb-5">
                <h2 class="section-title">Bookings List</h2>
                <div class="table-responsive">
                    <table class="table table-bordered table-striped">
                        <thead>
                            <tr>
                                <?php if ($_SESSION['role'] === 'admin'): ?>
                                    <th scope="col">Student Name</th>
                                <?php endif; ?>
                                <th scope="col">Hostel</th>
                                <th scope="col">Room Number</th>
                                <th scope="col">Room Type</th>
                                <th scope="col">Duration</th>
                                <th scope="col">Status</th>
                                <th scope="col">Submitted Date</th>
                                <?php if ($_SESSION['role'] === 'admin'): ?>
                                    <th scope="col">Actions</th>
                                <?php endif; ?>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (!empty($bookings)): ?>
                                <?php foreach ($bookings as $booking): ?>
                                    <tr>
                                        <?php if ($_SESSION['role'] === 'admin'): ?>
                                            <td><?php echo htmlspecialchars($booking['student_name'] ?? 'N/A'); ?></td>
                                        <?php endif; ?>
                                        <td><?php echo htmlspecialchars($booking['hostel'] ?? 'N/A'); ?></td>
                                        <td><?php echo htmlspecialchars($booking['room_number'] ?? 'N/A'); ?></td>
                                        <td><?php echo htmlspecialchars($booking['room_type'] ?? 'N/A'); ?></td>
                                        <td><?php echo htmlspecialchars($booking['duration']); ?></td>
                                        <td><?php echo htmlspecialchars($booking['status']); ?></td>
                                        <td><?php echo date('F j, Y H:i', strtotime($booking['submitted_date'])); ?></td>
                                        <?php if ($_SESSION['role'] === 'admin'): ?>
                                            <td>
                                                <?php if ($booking['status'] !== 'approved'): ?>
                                                    <form method="POST" style="display: inline;">
                                                        <input type="hidden" name="action" value="update_status">
                                                        <input type="hidden" name="booking_id" value="<?php echo htmlspecialchars($booking['id']); ?>">
                                                        <input type="hidden" name="status" value="approved">
                                                        <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars($csrf_token); ?>">
                                                        <button type="submit" class="btn btn-outline-success btn-sm">Approve</button>
                                                    </form>
                                                <?php endif; ?>
                                                <?php if ($booking['status'] !== 'rejected'): ?>
                                                    <form method="POST" style="display: inline;">
                                                        <input type="hidden" name="action" value="update_status">
                                                        <input type="hidden" name="booking_id" value="<?php echo htmlspecialchars($booking['id']); ?>">
                                                        <input type="hidden" name="status" value="rejected">
                                                        <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars($csrf_token); ?>">
                                                        <button type="submit" class="btn btn-outline-danger btn-sm">Reject</button>
                                                    </form>
                                                <?php endif; ?>
                                                <form method="POST" style="display: inline;" onsubmit="return confirm('Are you sure you want to delete this booking?');">
                                                    <input type="hidden" name="action" value="delete_booking">
                                                    <input type="hidden" name="booking_id" value="<?php echo htmlspecialchars($booking['id']); ?>">
                                                    <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars($csrf_token); ?>">
                                                    <button type="submit" class="btn btn-outline-danger btn-sm">Delete</button>
                                                </form>
                                            </td>
                                        <?php endif; ?>
                                    </tr>
                                <?php endforeach; ?>
                            <?php else: ?>
                                <tr><td colspan="<?php echo $_SESSION['role'] === 'admin' ? '8' : '6'; ?>" class="text-center">No bookings found.</td></tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </section>
        </main>
    </div>

    <footer class="bg-dark text-white text-center py-4">
        <div class="container">
            <p>&copy; <?php echo date("Y"); ?> Cypher University. Powered by AppKings Solutions Limited.</p>
            <p>Email: <a href="mailto:info@Cypher.ac.ke" class="text-white">info@Cypher.ac.ke</a> | Phone: <a href="tel:+254123456789" class="text-white">+254 123 456 789</a></p>
        </div>
    </footer>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // Pass rooms and bookings data to JavaScript
        const rooms = <?php echo json_encode($rooms, JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_QUOT | JSON_HEX_APOS); ?> || [];
        const bookings = <?php echo json_encode($bookings, JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_QUOT | JSON_HEX_APOS); ?> || [];

        console.log('Rooms:', rooms);
        console.log('Bookings:', bookings);

        // Form validation functions
        function validateBookingForm() {
            const hostel = document.getElementById('hostel')?.value;
            const roomType = document.getElementById('room_type')?.value;
            const roomId = document.getElementById('room_id')?.value;
            const duration = document.getElementById('duration')?.value;

            if (!hostel || !roomType || !roomId || !duration) {
                alert('Please fill in all required fields.');
                return false;
            }
            return true;
        }

        function validateAllocationForm() {
            const studentId = document.getElementById('student_id')?.value;
            const hostel = document.getElementById('admin_hostel')?.value;
            const roomType = document.getElementById('admin_room_type')?.value;
            const roomId = document.getElementById('admin_room_id')?.value;
            const duration = document.getElementById('admin_duration')?.value;

            if (!studentId || !hostel || !roomType || !roomId || !duration) {
                alert('Please fill in all required fields.');
                return false;
            }
            return true;
        }

        function validateAddRoomForm() {
            const hostel = document.getElementById('hostel')?.value;
            const roomNumber = document.getElementById('room_number')?.value;
            const roomType = document.getElementById('room_type')?.value;
            const cost = document.getElementById('cost_per_semester')?.value;

            if (!hostel || !roomNumber || !roomType || !cost || cost <= 0) {
                alert('Please fill in all required fields with valid values.');
                return false;
            }
            return true;
        }

        // Student form
        const hostelSelect = document.getElementById('hostel');
        const roomTypeSelect = document.getElementById('room_type');
        const roomSelect = document.getElementById('room_id');
        const durationSelect = document.getElementById('duration');
        const costDisplay = document.getElementById('cost-display');

        if (hostelSelect) {
            hostelSelect.addEventListener('change', function() {
                const hostel = this.value;
                console.log('Hostel selected:', hostel);
                roomTypeSelect.innerHTML = '<option value="">Select Room Type</option>';
                roomTypeSelect.disabled = true;
                roomSelect.innerHTML = '<option value="">Select a room type first</option>';
                roomSelect.disabled = true;
                costDisplay.textContent = 'Cost: Select a room and duration to see cost';

                if (hostel) {
                    const hostelRooms = rooms.filter(room => room.hostel === hostel && room.is_available && !bookings.some(b => parseInt(b.room_id) === parseInt(room.id) && ['pending', 'approved'].includes(b.status)));
                    console.log('Filtered hostel rooms:', hostelRooms);
                    const roomTypes = [...new Set(hostelRooms.map(room => room.room_type))];
                    console.log('Room types:', roomTypes);

                    if (roomTypes.length > 0) {
                        roomTypeSelect.disabled = false;
                        roomTypes.forEach(type => {
                            const option = document.createElement('option');
                            option.value = type;
                            option.textContent = type;
                            roomTypeSelect.appendChild(option);
                        });
                    } else {
                        roomTypeSelect.innerHTML = '<option value="">No room types available</option>';
                        roomTypeSelect.disabled = true;
                    }
                }
            });
        }

        if (roomTypeSelect) {
            roomTypeSelect.addEventListener('change', function() {
                const hostel = hostelSelect.value;
                const roomType = this.value;
                console.log('Room type selected:', roomType);
                roomSelect.innerHTML = '<option value="">Select a room</option>';
                roomSelect.disabled = true;
                costDisplay.textContent = 'Cost: Select a room and duration to see cost';

                if (roomType) {
                    const availableRooms = rooms.filter(room => room.hostel === hostel && room.room_type === roomType && room.is_available && !bookings.some(b => parseInt(b.room_id) === parseInt(room.id) && ['pending', 'approved'].includes(b.status)));
                    console.log('Available rooms:', availableRooms);
                    if (availableRooms.length > 0) {
                        roomSelect.disabled = false;
                        availableRooms.forEach(room => {
                            const option = document.createElement('option');
                            option.value = room.id;
                            option.textContent = `${room.room_number} (Cost per Semester: ${parseFloat(room.cost_per_semester).toFixed(2)})`;
                            roomSelect.appendChild(option);
                        });
                    } else {
                        roomSelect.innerHTML = '<option value="">No rooms available</option>';
                        roomSelect.disabled = true;
                    }
                    updateCost();
                }
            });
        }

        if (roomSelect) {
            roomSelect.addEventListener('change', updateCost);
        }

        if (durationSelect) {
            durationSelect.addEventListener('change', updateCost);
        }

        function updateCost() {
            const roomId = roomSelect?.value;
            const duration = durationSelect?.value;
            console.log('Updating cost - Room ID:', roomId, 'Duration:', duration);
            if (roomId && duration) {
                const room = rooms.find(r => parseInt(r.id) === parseInt(roomId));
                if (room) {
                    const cost = duration === 'Year' ? room.cost_per_semester * 2 : room.cost_per_semester;
                    costDisplay.textContent = `Cost: ${cost.toFixed(2)} ${duration === 'Year' ? '(Yearly)' : '(Semester)'}`;
                } else {
                    costDisplay.textContent = 'Cost: Room not found';
                }
            } else {
                costDisplay.textContent = 'Cost: Select a room and duration to see cost';
            }
        }

        // Admin form
        const adminHostelSelect = document.getElementById('admin_hostel');
        const adminRoomTypeSelect = document.getElementById('admin_room_type');
        const adminRoomSelect = document.getElementById('admin_room_id');
        const adminDurationSelect = document.getElementById('admin_duration');
        const adminCostDisplay = document.getElementById('admin_cost-display');

        if (adminHostelSelect) {
            adminHostelSelect.addEventListener('change', function() {
                const hostel = this.value;
                console.log('Admin hostel selected:', hostel);
                adminRoomTypeSelect.innerHTML = '<option value="">Select Room Type</option>';
                adminRoomTypeSelect.disabled = true;
                adminRoomSelect.innerHTML = '<option value="">Select a room type first</option>';
                adminRoomSelect.disabled = true;
                adminCostDisplay.textContent = 'Cost: Select a room and duration to see cost';

                if (hostel) {
                    const hostelRooms = rooms.filter(room => room.hostel === hostel && room.is_available && !bookings.some(b => parseInt(b.room_id) === parseInt(room.id) && ['pending', 'approved'].includes(b.status)));
                    console.log('Admin filtered hostel rooms:', hostelRooms);
                    const roomTypes = [...new Set(hostelRooms.map(room => room.room_type))];
                    console.log('Admin room types:', roomTypes);

                    if (roomTypes.length > 0) {
                        adminRoomTypeSelect.disabled = false;
                        roomTypes.forEach(type => {
                            const option = document.createElement('option');
                            option.value = type;
                            option.textContent = type;
                            adminRoomTypeSelect.appendChild(option);
                        });
                    } else {
                        adminRoomTypeSelect.innerHTML = '<option value="">No room types available</option>';
                        adminRoomTypeSelect.disabled = true;
                    }
                }
            });
        }

        if (adminRoomTypeSelect) {
            adminRoomTypeSelect.addEventListener('change', function() {
                const hostel = adminHostelSelect.value;
                const roomType = this.value;
                console.log('Admin room type selected:', roomType);
                adminRoomSelect.innerHTML = '<option value="">Select a room</option>';
                adminRoomSelect.disabled = true;
                adminCostDisplay.textContent = 'Cost: Select a room and duration to see cost';

                if (roomType) {
                    const availableRooms = rooms.filter(room => room.hostel === hostel && room.room_type === roomType && room.is_available && !bookings.some(b => parseInt(b.room_id) === parseInt(room.id) && ['pending', 'approved'].includes(b.status)));
                    console.log('Admin available rooms:', availableRooms);
                    if (availableRooms.length > 0) {
                        adminRoomSelect.disabled = false;
                        availableRooms.forEach(room => {
                            const option = document.createElement('option');
                            option.value = room.id;
                            option.textContent = `${room.room_number} (Cost per Semester: ${parseFloat(room.cost_per_semester).toFixed(2)})`;
                            adminRoomSelect.appendChild(option);
                        });
                    } else {
                        adminRoomSelect.innerHTML = '<option value="">No rooms available</option>';
                        adminRoomSelect.disabled = true;
                    }
                    updateAdminCost();
                }
            });
        }

        if (adminRoomSelect) {
            adminRoomSelect.addEventListener('change', updateAdminCost);
        }

        if (adminDurationSelect) {
            adminDurationSelect.addEventListener('change', updateAdminCost);
        }

        function updateAdminCost() {
            const roomId = adminRoomSelect?.value;
            const duration = adminDurationSelect?.value;
            console.log('Updating admin cost - Room ID:', roomId, 'Duration:', duration);
            if (roomId && duration) {
                const room = rooms.find(r => parseInt(r.id) === parseInt(roomId));
                if (room) {
                    const cost = duration === 'Year' ? room.cost_per_semester * 2 : room.cost_per_semester;
                    adminCostDisplay.textContent = `Cost: ${cost.toFixed(2)} ${duration === 'Year' ? '(Yearly)' : '(Semester)'}`;
                } else {
                    adminCostDisplay.textContent = 'Cost: Room not found';
                }
            } else {
                adminCostDisplay.textContent = 'Cost: Select a room and duration to see cost';
            }
        }

        // Edit Room Modal Handling
        document.querySelectorAll('.edit-room-btn').forEach(button => {
            button.addEventListener('click', function() {
                const roomId = this.getAttribute('data-room-id');
                const hostel = this.getAttribute('data-hostel');
                const roomNumber = this.getAttribute('data-room-number');
                const roomType = this.getAttribute('data-room-type');
                const cost = this.getAttribute('data-cost');
                const isAvailable = this.getAttribute('data-is-available') === '1';

                document.getElementById('edit_room_id').value = roomId;
                document.getElementById('edit_hostel').value = hostel;
                document.getElementById('edit_room_number').value = roomNumber;
                document.getElementById('edit_room_type').value = roomType;
                document.getElementById('edit_cost_per_semester').value = parseFloat(cost).toFixed(2);
                document.getElementById('edit_is_available').checked = isAvailable;

                // Validate form on submit
                document.getElementById('edit-room-form').onsubmit = function() {
                    const hostel = document.getElementById('edit_hostel').value;
                    const roomNumber = document.getElementById('edit_room_number').value;
                    const roomType = document.getElementById('edit_room_type').value;
                    const cost = document.getElementById('edit_cost_per_semester').value;

                    if (!hostel || !roomNumber || !roomType || !cost || cost <= 0) {
                        alert('Please fill in all required fields with valid values.');
                        return false;
                    }
                    return confirm('Are you sure you want to save these changes?');
                };
            });
        });
    </script>
</body>
</html>