<?php
// rooms_beds.php - Rooms & Beds Management Page
session_start();

// Check if the admin is NOT logged in
if (!isset($_SESSION['admin_logged_in']) || $_SESSION['admin_logged_in'] !== true) {
    header('Location: admin_login.php');
    exit;
}

$pageTitle = 'Rooms & Beds - Hostel Management';
require_once 'config.php'; // Include the database configuration
include_once '_header.php'; // Include the common header
include_once '_sidebar.php'; // Include the new sidebar file

// --- PHP Logic to Fetch Data for Dropdowns and Tables ---
$hostels = []; // For the "Select Hostel" dropdowns
$rooms = [];   // For the "View/Manage Rooms" table
$beds = [];    // For the "View/Manage Beds" table

try {
    // Fetch all hostels for dropdowns
    $sqlHostels = "SELECT hostel_id, name FROM hostels ORDER BY name ASC";
    $stmtHostels = $pdo->prepare($sqlHostels);
    $stmtHostels->execute();
    $hostels = $stmtHostels->fetchAll(PDO::FETCH_ASSOC);

    // Fetch all rooms, joining with floors and hostels for display
    $sqlRooms = "SELECT r.room_id, r.room_number, r.room_type, r.capacity, r.current_occupancy,
                        f.floor_number, h.name AS hostel_name, f.floor_id, h.hostel_id
                 FROM rooms r
                 JOIN floors f ON r.floor_id = f.floor_id
                 JOIN hostels h ON f.hostel_id = h.hostel_id
                 ORDER BY h.name, f.floor_number, r.room_number ASC";
    $stmtRooms = $pdo->prepare($sqlRooms);
    $stmtRooms->execute();
    $rooms = $stmtRooms->fetchAll(PDO::FETCH_ASSOC);

    // Fetch all beds, joining with rooms, floors, and hostels for display
    $sqlBeds = "SELECT b.bed_id, b.bed_number, b.is_occupied,
                       r.room_id, r.room_number, r.room_type, r.capacity, r.current_occupancy,
                       f.floor_id, f.floor_number,
                       h.hostel_id, h.name AS hostel_name
                FROM beds b
                JOIN rooms r ON b.room_id = r.room_id
                JOIN floors f ON r.floor_id = f.floor_id
                JOIN hostels h ON f.hostel_id = h.hostel_id
                ORDER BY h.name, f.floor_number, r.room_number, b.bed_number ASC";
    $stmtBeds = $pdo->prepare($sqlBeds);
    $stmtBeds->execute();
    $beds = $stmtBeds->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    error_log("Error fetching data for rooms_beds.php: " . $e->getMessage());
    $errorMessage = "Could not load data. Please try again later.";
}
?>
    <main class="container-fluid" id="appContent">
        <h5 class="mb-4">Room & Bed Management</h5>

        <?php if (isset($errorMessage)): ?>
            <div class="alert alert-danger" role="alert">
                <?php echo htmlspecialchars($errorMessage); ?>
            </div>
        <?php endif; ?>

        <!-- Add Room Form -->
        <div class="card mb-4">
            <div class="card-header">
                Add New Room
            </div>
            <div class="card-body">
                <form id="addRoomForm">
                    <div class="row g-3">
                        <div class="col-md-4">
                            <label for="addRoomHostelSelect" class="form-label">Select Hostel <span class="text-danger">*</span></label>
                            <select class="form-select" id="addRoomHostelSelect" name="hostelId" required>
                                <option value="">Choose Hostel...</option>
                                <?php foreach ($hostels as $hostel): ?>
                                    <option value="<?php echo htmlspecialchars($hostel['hostel_id']); ?>">
                                        <?php echo htmlspecialchars($hostel['name']); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="col-md-4">
                            <label for="addRoomFloorSelect" class="form-label">Select Floor <span class="text-danger">*</span></label>
                            <select class="form-select" id="addRoomFloorSelect" name="floorId" required disabled>
                                <option value="">Choose Floor...</option>
                                <!-- Floors will be loaded dynamically via JS -->
                            </select>
                        </div>
                        <div class="col-md-4">
                            <label for="roomNumber" class="form-label">Room Number <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" id="roomNumber" name="roomNumber" placeholder="e.g., 101, G01" required>
                        </div>
                        <div class="col-md-6">
                            <label for="roomType" class="form-label">Room Type <span class="text-danger">*</span></label>
                            <select class="form-select" id="roomType" name="roomType" required>
                                <option value="">Select Type...</option>
                                <option value="single">Single</option>
                                <option value="shared">Shared</option>
                                <option value="dormitory">Dormitory</option>
                            </select>
                        </div>
                        <div class="col-md-6">
                            <label for="roomCapacity" class="form-label">Capacity (Number of Beds) <span class="text-danger">*</span></label>
                            <input type="number" class="form-control" id="roomCapacity" name="capacity" min="1" value="1" required>
                        </div>
                        <div class="col-12 text-end">
                            <button type="submit" class="btn btn-primary"><i class="fas fa-plus"></i> Add Room</button>
                        </div>
                    </div>
                </form>
                <div id="roomMessage" class="mt-3 alert d-none" role="alert">
                    <!-- Room message will be displayed here -->
                </div>
            </div>
        </div>

        <!-- View/Manage Rooms Table -->
        <div class="card mb-4">
            <div class="card-header">
                View/Manage Rooms
            </div>
            <div class="card-body">
                <?php if (empty($rooms)): ?>
                    <div class="alert alert-info" role="alert">
                        No rooms found. Add new rooms using the form above.
                    </div>
                <?php else: ?>
                    <div class="table-responsive">
                <table id="roomsTable" class="table table-striped table-bordered display nowrap" style="width:100%">
                    <thead class="table-dark">
                                <tr>
                                    <th>ID</th>
                                    <th>Hostel</th>
                                    <th>Floor</th>
                                    <th>Room Number</th>
                                    <th>Type</th>
                                    <th>Capacity</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($rooms as $room): ?>
                                    <tr>
                                        <td><?php echo htmlspecialchars($room['room_id']); ?></td>
                                        <td><?php echo htmlspecialchars($room['hostel_name']); ?></td>
                                        <td><?php echo htmlspecialchars($room['floor_number']); ?></td>
                                        <td><?php echo htmlspecialchars($room['room_number']); ?></td>
                                        <td><?php echo htmlspecialchars(ucfirst($room['room_type'])); ?></td>
                                        <td><?php echo htmlspecialchars($room['capacity']); ?></td>
                                        <td>
                                            <button class="btn btn-sm btn-warning rounded-pill me-1 edit-room-btn" data-id="<?php echo htmlspecialchars($room['room_id']); ?>">
                                                <i class="fas fa-edit"></i> Edit
                                            </button>
                                            <button class="btn btn-sm btn-danger rounded-pill delete-room-btn" data-id="<?php echo htmlspecialchars($room['room_id']); ?>" data-room-number="<?php echo htmlspecialchars($room['room_number']); ?>" data-hostel-name="<?php echo htmlspecialchars($room['hostel_name']); ?>">
                                                <i class="fas fa-trash-alt"></i> Delete
                                            </button>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                <?php endif; ?>
            </div>
        </div>
        <!-- Add Bed Form -->
        <div class="card mb-4">
            <div class="card-header">
                Add New Bed
            </div>
            <div class="card-body">
                <form id="addBedForm">
                    <div class="row g-3">
                        <div class="col-md-4">
                            <label for="addBedHostelSelect" class="form-label">Select Hostel <span class="text-danger">*</span></label>
                            <select class="form-select" id="addBedHostelSelect" name="hostelId" required>
                                <option value="">Choose Hostel...</option>
                                <?php foreach ($hostels as $hostel): ?>
                                    <option value="<?php echo htmlspecialchars($hostel['hostel_id']); ?>">
                                        <?php echo htmlspecialchars($hostel['name']); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="col-md-4">
                            <label for="addBedFloorSelect" class="form-label">Select Floor <span class="text-danger">*</span></label>
                            <select class="form-select" id="addBedFloorSelect" name="floorId" required disabled>
                                <option value="">Choose Floor...</option>
                                <!-- Floors will be loaded dynamically via JS -->
                            </select>
                        </div>
                        <div class="col-md-4">
                            <label for="addBedRoomSelect" class="form-label">Select Room <span class="text-danger">*</span></label>
                            <select class="form-select" id="addBedRoomSelect" name="roomId" required disabled>
                                <option value="">Choose Room...</option>
                                <!-- Rooms will be loaded dynamically via JS -->
                            </select>
                        </div>
                        <div class="col-md-6">
                            <label for="bedNumber" class="form-label">Bed Number <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" id="bedNumber" name="bedNumber" placeholder="e.g., A, B, 1" required>
                        </div>
                        <div class="col-md-6">
                            <label for="isOccupied" class="form-label">Status</label>
                            <select class="form-select" id="isOccupied" name="isOccupied">
                                <option value="0">Available</option>
                                <option value="1">Occupied</option>
                            </select>
                        </div>
                        <div class="col-12 text-end">
                            <button type="submit" class="btn btn-primary"><i class="fas fa-plus"></i> Add Bed</button>
                        </div>
                    </div>
                </form>
                <div id="bedMessage" class="mt-3 alert d-none" role="alert">
                    <!-- Bed message will be displayed here -->
                </div>
            </div>
        </div>

        <!-- View/Manage Beds Table -->
        <div class="card">
            <div class="card-header">
                View/Manage Beds
            </div>
            <div class="card-body">
                <?php if (empty($beds)): ?>
                    <div class="alert alert-info" role="alert">
                        No beds found. Add new beds using the form above.
                    </div>
                <?php else: ?>
                    <div class="table-responsive">
                <table id="roomsBedsTable" class="table table-striped table-bordered display nowrap" style="width:100%">
                    <thead class="table-dark">
                                <tr>
                                    <th>ID</th>
                                    <th>Hostel</th>
                                    <th>Floor</th>
                                    <th>Room Number</th>
                                    <th>Bed Number</th>
                                    <th>Status</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($beds as $bed): ?>
                                    <tr>
                                        <td><?php echo htmlspecialchars($bed['bed_id']); ?></td>
                                        <td><?php echo htmlspecialchars($bed['hostel_name']); ?></td>
                                        <td><?php echo htmlspecialchars($bed['floor_number']); ?></td>
                                        <td><?php echo htmlspecialchars($bed['room_number']); ?></td>
                                        <td><?php echo htmlspecialchars($bed['bed_number']); ?></td>
                                        <td>
                                            <?php
                                            $statusClass = ($bed['is_occupied'] == 1) ? 'bg-danger' : 'bg-success';
                                            $statusText = ($bed['is_occupied'] == 1) ? 'Occupied' : 'Available';
                                            ?>
                                            <span class="badge <?php echo $statusClass; ?> rounded-pill">
                                                <?php echo htmlspecialchars($statusText); ?>
                                            </span>
                                        </td>
                                  
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </main>

    <!-- Edit Room Modal -->
    <div class="modal fade" id="editRoomModal" tabindex="-1" aria-labelledby="editRoomModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="editRoomModalLabel">Edit Room Details</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <form id="editRoomForm">
                        <input type="hidden" id="editRoomId" name="room_id">
                        <div class="row g-3">
                            <div class="col-md-6">
                                <label for="editRoomHostelSelect" class="form-label">Hostel <span class="text-danger">*</span></label>
                                <select class="form-select" id="editRoomHostelSelect" name="hostelId" required disabled>
                                    <?php foreach ($hostels as $hostel): ?>
                                        <option value="<?php echo htmlspecialchars($hostel['hostel_id']); ?>">
                                            <?php echo htmlspecialchars($hostel['name']); ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <div class="col-md-6">
                                <label for="editRoomFloorSelect" class="form-label">Floor <span class="text-danger">*</span></label>
                                <select class="form-select" id="editRoomFloorSelect" name="floorId" required>
                                    <!-- Floors will be loaded dynamically -->
                                </select>
                            </div>
                            <div class="col-md-6">
                                <label for="editRoomNumber" class="form-label">Room Number <span class="text-danger">*</span></label>
                                <input type="text" class="form-control" id="editRoomNumber" name="roomNumber" required>
                            </div>
                            <div class="col-md-6">
                                <label for="editRoomType" class="form-label">Room Type <span class="text-danger">*</span></label>
                                <select class="form-select" id="editRoomType" name="roomType" required>
                                    <option value="single">Single</option>
                                    <option value="shared">Shared</option>
                                    <option value="dormitory">Dormitory</option>
                                </select>
                            </div>
                            <div class="col-md-6">
                                <label for="editRoomCapacity" class="form-label">Capacity (Beds) <span class="text-danger">*</span></label>
                                <input type="number" class="form-control" id="editRoomCapacity" name="capacity" min="1" required>
                            </div>
                            <div class="col-md-6">
                                <label for="editCurrentOccupancy" class="form-label">Current Occupancy</label>
                                <input type="number" class="form-control" id="editCurrentOccupancy" name="currentOccupancy" min="0" readonly>
                            </div>
                        </div>
                    </form>
                    <div id="editRoomMessage" class="mt-3 alert d-none" role="alert">
                        <!-- Message will be displayed here -->
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-primary" id="saveEditRoomBtn">Save changes</button>
                </div>
            </div>
        </div>
    </div>
    <!-- Edit Bed Modal -->
    <div class="modal fade" id="editBedModal" tabindex="-1" aria-labelledby="editBedModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="editBedModalLabel">Edit Bed Details</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <form id="editBedForm">
                        <input type="hidden" id="editBedId" name="bed_id">
                        <div class="row g-3">
                            <div class="col-md-6">
                                <label for="editBedHostelSelect" class="form-label">Hostel <span class="text-danger">*</span></label>
                                <select class="form-select" id="editBedHostelSelect" name="hostelId" required disabled>
                                    <?php foreach ($hostels as $hostel): ?>
                                        <option value="<?php echo htmlspecialchars($hostel['hostel_id']); ?>">
                                            <?php echo htmlspecialchars($hostel['name']); ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <div class="col-md-6">
                                <label for="editBedFloorSelect" class="form-label">Floor <span class="text-danger">*</span></label>
                                <select class="form-select" id="editBedFloorSelect" name="floorId" required>
                                    <!-- Floors will be loaded dynamically -->
                                </select>
                            </div>
                            <div class="col-md-6">
                                <label for="editBedRoomSelect" class="form-label">Room <span class="text-danger">*</span></label>
                                <select class="form-select" id="editBedRoomSelect" name="roomId" required>
                                    <!-- Rooms will be loaded dynamically -->
                                </select>
                            </div>
                            <div class="col-md-6">
                                <label for="editBedNumber" class="form-label">Bed Number <span class="text-danger">*</span></label>
                                <input type="text" class="form-control" id="editBedNumber" name="bedNumber" required>
                            </div>
                            <div class="col-md-6">
                                <label for="editIsOccupied" class="form-label">Status <span class="text-danger">*</span></label>
                                <select class="form-select" id="editIsOccupied" name="isOccupied" required>
                                    <option value="0">Available</option>
                                    <option value="1">Occupied</option>
                                </select>
                            </div>
                        </div>
                    </form>
                    <div id="editBedMessage" class="mt-3 alert d-none" role="alert">
                        <!-- Message will be displayed here -->
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                    <button type="button" class="btn btn-primary" id="saveEditBedBtn">Save changes</button>
                </div>
            </div>
        </div>
    </div>

    <!-- DataTables CSS/JS -->
<link rel="stylesheet" href="https://cdn.datatables.net/1.13.6/css/jquery.dataTables.min.css">
<link rel="stylesheet" href="https://cdn.datatables.net/buttons/2.4.2/css/buttons.dataTables.min.css">
<link rel="stylesheet" href="https://cdn.datatables.net/responsive/2.5.0/css/responsive.dataTables.min.css">
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.4.2/js/dataTables.buttons.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.4.2/js/buttons.html5.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.4.2/js/buttons.print.min.js"></script>
<script src="https://cdn.datatables.net/responsive/2.5.0/js/dataTables.responsive.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.1/jszip.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.2.7/pdfmake.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.2.7/vfs_fonts.js"></script>


<script>
$(document).ready(function() {
    $('#roomsTable').DataTable({
        responsive: true,
        scrollX: true,
        dom: "<'row mb-2'<'col-sm-12 col-md-6'B><'col-sm-12 col-md-6'f>>" +
             "<'row mb-2'<'col-sm-12 col-md-6'l><'col-sm-12 col-md-6'ip>>" +
             "t",
        buttons: [
            { extend: 'copyHtml5',  title: 'Floors' },
            { extend: 'excelHtml5', title: 'Floors' },
            { extend: 'print',      title: 'Floors' }
        ],
        lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "All"]]
    });
});
</script>  


<script>
$(document).ready(function() {
    $('#roomsBedsTable').DataTable({
        responsive: true,
        scrollX: true,
        dom: "<'row mb-2'<'col-sm-12 col-md-6'B><'col-sm-12 col-md-6'f>>" +
             "<'row mb-2'<'col-sm-12 col-md-6'l><'col-sm-12 col-md-6'ip>>" +
             "t",
        buttons: [
            { extend: 'copyHtml5',  title: 'Floors' },
            { extend: 'excelHtml5', title: 'Floors' },
            { extend: 'print',      title: 'Floors' }
        ],
        lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "All"]]
    });
});
</script>                                    




    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // --- Elements for Add Room Form ---
            const addRoomForm = document.getElementById('addRoomForm');
            const addRoomHostelSelect = document.getElementById('addRoomHostelSelect');
            const addRoomFloorSelect = document.getElementById('addRoomFloorSelect');
            const roomMessage = document.getElementById('roomMessage');

            // --- Elements for Add Bed Form ---
            const addBedForm = document.getElementById('addBedForm');
            const addBedHostelSelect = document.getElementById('addBedHostelSelect');
            const addBedFloorSelect = document.getElementById('addBedFloorSelect');
            const addBedRoomSelect = document.getElementById('addBedRoomSelect');
            const bedMessage = document.getElementById('bedMessage');

            // --- Edit Room Modal Elements ---
            const editRoomModal = new bootstrap.Modal(document.getElementById('editRoomModal'));
            const editRoomForm = document.getElementById('editRoomForm');
            const editRoomIdInput = document.getElementById('editRoomId');
            const editRoomHostelSelect = document.getElementById('editRoomHostelSelect'); // Disabled in HTML, but needed for context
            const editRoomFloorSelect = document.getElementById('editRoomFloorSelect');
            const editRoomNumberInput = document.getElementById('editRoomNumber');
            const editRoomTypeSelect = document.getElementById('editRoomType');
            const editRoomCapacityInput = document.getElementById('editRoomCapacity');
            const editCurrentOccupancyInput = document.getElementById('editCurrentOccupancy');
            const saveEditRoomBtn = document.getElementById('saveEditRoomBtn');
            const editRoomMessage = document.getElementById('editRoomMessage');

            // --- Edit Bed Modal Elements ---
            const editBedModal = new bootstrap.Modal(document.getElementById('editBedModal'));
            const editBedForm = document.getElementById('editBedForm');
            const editBedIdInput = document.getElementById('editBedId');
            const editBedHostelSelect = document.getElementById('editBedHostelSelect'); // Disabled in HTML, but needed for context
            const editBedFloorSelect = document.getElementById('editBedFloorSelect');
            const editBedRoomSelect = document.getElementById('editBedRoomSelect');
            const editBedNumberInput = document.getElementById('editBedNumber');
            const editIsOccupiedSelect = document.getElementById('editIsOccupied');
            const saveEditBedBtn = document.getElementById('saveEditBedBtn');
            const editBedMessage = document.getElementById('editBedMessage');


            // --- Helper Functions to Display Messages ---
            function showMessage(element, message, type) {
                element.textContent = message;
                element.className = `mt-3 alert alert-${type}`;
                element.classList.remove('d-none');
                setTimeout(() => {
                    element.classList.add('d-none');
                }, 5000);
            }

            // --- Dynamic Dropdown Loading (Floors based on Hostel) ---
            async function loadFloors(hostelId, targetSelectElement, selectedFloorId = null) {
                targetSelectElement.innerHTML = '<option value="">Loading Floors...</option>';
                targetSelectElement.disabled = true;

                if (!hostelId) {
                    targetSelectElement.innerHTML = '<option value="">Choose Floor...</option>';
                    return;
                }

                try {
                    const response = await fetch(`get_floors_by_hostel.php?hostel_id=${hostelId}`);
                    const data = await response.json();

                    if (data.success) {
                        targetSelectElement.innerHTML = '<option value="">Choose Floor...</option>';
                        data.floors.forEach(floor => {
                            const option = document.createElement('option');
                            option.value = floor.floor_id;
                            option.textContent = `Floor ${floor.floor_number} (${floor.description || 'No Description'})`;
                            if (selectedFloorId !== null && floor.floor_id == selectedFloorId) { // Use == for type coercion
                                option.selected = true;
                            }
                            targetSelectElement.appendChild(option);
                        });
                        targetSelectElement.disabled = false;
                    } else {
                        showMessage(targetSelectElement === addRoomFloorSelect ? roomMessage : bedMessage, data.message || 'Failed to load floors.', 'danger');
                        targetSelectElement.innerHTML = '<option value="">No Floors Found</option>';
                    }
                } catch (error) {
                    console.error('Error loading floors:', error);
                    showMessage(targetSelectElement === addRoomFloorSelect ? roomMessage : bedMessage, 'Error loading floors.', 'danger');
                    targetSelectElement.innerHTML = '<option value="">Error Loading Floors</option>';
                }
            }

            // --- Dynamic Dropdown Loading (Rooms based on Floor) ---
            async function loadRooms(floorId, targetSelectElement, selectedRoomId = null) {
                targetSelectElement.innerHTML = '<option value="">Loading Rooms...</option>';
                targetSelectElement.disabled = true;

                if (!floorId) {
                    targetSelectElement.innerHTML = '<option value="">Choose Room...</option>';
                    return;
                }

                try {
                    const response = await fetch(`get_rooms_by_floor.php?floor_id=${floorId}`);
                    const data = await response.json();

                    if (data.success) {
                        targetSelectElement.innerHTML = '<option value="">Choose Room...</option>';
                        data.rooms.forEach(room => {
                            const option = document.createElement('option');
                            option.value = room.room_id;
                            option.textContent = `Room ${room.room_number} (Capacity: ${room.capacity}, Occupancy: ${room.current_occupancy})`;
                            if (selectedRoomId !== null && room.room_id == selectedRoomId) { // Use == for type coercion
                                option.selected = true;
                            }
                            targetSelectElement.appendChild(option);
                        });
                        targetSelectElement.disabled = false;
                    } else {
                        showMessage(bedMessage, data.message || 'Failed to load rooms.', 'danger');
                        targetSelectElement.innerHTML = '<option value="">No Rooms Found</option>';
                    }
                } catch (error) {
                    console.error('Error loading rooms:', error);
                    showMessage(bedMessage, 'Error loading rooms.', 'danger');
                    targetSelectElement.innerHTML = '<option value="">Error Loading Rooms</option>';
                }
            }

            // --- Event Listeners for Dynamic Dropdowns (Add Forms) ---
            addRoomHostelSelect.addEventListener('change', function() {
                loadFloors(this.value, addRoomFloorSelect);
            });

            addBedHostelSelect.addEventListener('change', function() {
                loadFloors(this.value, addBedFloorSelect);
                addBedRoomSelect.innerHTML = '<option value="">Choose Room...</option>'; // Reset rooms
                addBedRoomSelect.disabled = true;
            });

            addBedFloorSelect.addEventListener('change', function() {
                loadRooms(this.value, addBedRoomSelect);
            });


            // --- Handle Add Room Form Submission ---
            addRoomForm.addEventListener('submit', async function(event) {
                event.preventDefault();

                if (!addRoomForm.checkValidity()) {
                    event.stopPropagation();
                    addRoomForm.classList.add('was-validated');
                    return;
                } else {
                    addRoomForm.classList.remove('was-validated');
                }

                const formData = new FormData(addRoomForm);
                const roomData = {};
                for (let [key, value] of formData.entries()) {
                    roomData[key] = value;
                }
                roomData['capacity'] = parseInt(roomData['capacity']); // Ensure integer

                showMessage(roomMessage, 'Adding room...', 'info');

                try {
                    const response = await fetch('add_room_process.php', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                        },
                        body: JSON.stringify(roomData),
                    });

                    const result = await response.json();

                    if (result.success) {
                        showMessage(roomMessage, result.message, 'success');
                        addRoomForm.reset();
                        addRoomForm.classList.remove('was-validated');
                        addRoomHostelSelect.value = ""; // Reset hostel dropdown
                        addRoomFloorSelect.innerHTML = '<option value="">Choose Floor...</option>'; // Reset floor dropdown
                        addRoomFloorSelect.disabled = true;
                        setTimeout(() => {
                            location.reload(); // Reload page to show new room
                        }, 1000);
                    } else {
                        showMessage(roomMessage, result.message, 'danger');
                    }
                } catch (error) {
                    console.error('Error adding room:', error);
                    showMessage(roomMessage, 'An unexpected error occurred. Please try again.', 'danger');
                }
            });

            // --- Handle Add Bed Form Submission ---
            addBedForm.addEventListener('submit', async function(event) {
                event.preventDefault();

                if (!addBedForm.checkValidity()) {
                    event.stopPropagation();
                    addBedForm.classList.add('was-validated');
                    return;
                } else {
                    addBedForm.classList.remove('was-validated');
                }

                const formData = new FormData(addBedForm);
                const bedData = {};
                for (let [key, value] of formData.entries()) {
                    bedData[key] = value;
                }
                bedData['isOccupied'] = parseInt(bedData['isOccupied']); // Ensure integer (0 or 1)

                showMessage(bedMessage, 'Adding bed...', 'info');

                try {
                    const response = await fetch('add_bed_process.php', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                        },
                        body: JSON.stringify(bedData),
                    });

                    const result = await response.json();

                    if (result.success) {
                        showMessage(bedMessage, result.message, 'success');
                        addBedForm.reset();
                        addBedForm.classList.remove('was-validated');
                        addBedHostelSelect.value = ""; // Reset hostel dropdown
                        addBedFloorSelect.innerHTML = '<option value="">Choose Floor...</option>'; // Reset floor dropdown
                        addBedFloorSelect.disabled = true;
                        addBedRoomSelect.innerHTML = '<option value="">Choose Room...</option>'; // Reset room dropdown
                        addBedRoomSelect.disabled = true;
                        setTimeout(() => {
                            location.reload(); // Reload page to show new bed
                        }, 1000);
                    } else {
                        showMessage(bedMessage, result.message, 'danger');
                    }
                } catch (error) {
                    console.error('Error adding bed:', error);
                    showMessage(bedMessage, 'An unexpected error occurred. Please try again.', 'danger');
                }
            });


            // --- Action Buttons (Edit/Delete - Rooms) ---
            document.querySelector('#appContent').addEventListener('click', async function(event) {
                // Edit Room Button
                if (event.target.closest('.edit-room-btn')) {
                    const button = event.target.closest('.edit-room-btn');
                    const roomId = button.dataset.id;
                    console.log('Edit button clicked for Room ID:', roomId);

                    try {
                        const response = await fetch(`get_room_details.php?id=${roomId}`);
                        const data = await response.json();

                        if (data.success && data.room) {
                            const room = data.room;
                            editRoomIdInput.value = room.room_id;
                            editRoomHostelSelect.value = room.hostel_id; // Set hostel (disabled)
                            editRoomNumberInput.value = room.room_number;
                            editRoomTypeSelect.value = room.room_type;
                            editRoomCapacityInput.value = room.capacity;
                            editCurrentOccupancyInput.value = room.current_occupancy;

                            // Load floors for the edit modal's floor dropdown
                            await loadFloors(room.hostel_id, editRoomFloorSelect, room.floor_id);

                            editRoomModal.show(); // Show the modal
                            showMessage(editRoomMessage, '', ''); // Clear any previous messages in the modal
                            editRoomForm.classList.remove('was-validated'); // Clear validation styling
                        } else {
                            showMessage(roomMessage, data.message || 'Failed to fetch room details.', 'danger');
                        }
                    } catch (error) {
                        console.error('Error fetching room details:', error);
                        showMessage(roomMessage, 'An error occurred while fetching room details.', 'danger');
                    }
                }

                // Delete Room Button
                if (event.target.closest('.delete-room-btn')) {
                    const button = event.target.closest('.delete-room-btn');
                    const roomId = button.dataset.id;
                    const roomNumber = button.dataset.roomNumber;
                    const hostelName = button.dataset.hostelName;

                    const confirmDelete = confirm(`Are you sure you want to delete Room ${roomNumber} from ${hostelName} (ID: ${roomId})? This will also delete all associated beds.`);

                    if (confirmDelete) {
                        console.log('Confirmed deletion for Room ID:', roomId);
                        showMessage(roomMessage, 'Deleting room...', 'info');

                        try {
                            const response = await fetch('delete_room_process.php', {
                                method: 'POST',
                                headers: {
                                    'Content-Type': 'application/json',
                                },
                                body: JSON.stringify({ room_id: roomId }),
                            });

                            const result = await response.json();

                            if (result.success) {
                                showMessage(roomMessage, result.message, 'success');
                                setTimeout(() => {
                                    location.reload();
                                }, 1000);
                            } else {
                                showMessage(roomMessage, result.message, 'danger');
                            }
                        } catch (error) {
                            console.error('Error deleting room:', error);
                            showMessage(roomMessage, 'An unexpected error occurred during deletion. Please try again.', 'danger');
                        }
                    } else {
                        showMessage(roomMessage, 'Deletion cancelled.', 'secondary');
                    }
                }

                // Edit Bed Button
                if (event.target.closest('.edit-bed-btn')) {
                    const button = event.target.closest('.edit-bed-btn');
                    const bedId = button.dataset.id;
                    console.log('Edit button clicked for Bed ID:', bedId);

                    try {
                        const response = await fetch(`get_bed_details.php?id=${bedId}`);
                        const data = await response.json();

                        if (data.success && data.bed) {
                            const bed = data.bed;
                            editBedIdInput.value = bed.bed_id;
                            editBedHostelSelect.value = bed.hostel_id; // Set hostel (disabled)
                            editBedNumberInput.value = bed.bed_number;
                            editIsOccupiedSelect.value = bed.is_occupied; // Set status

                            // Load floors for the edit modal's floor dropdown
                            await loadFloors(bed.hostel_id, editBedFloorSelect, bed.floor_id);
                            // Load rooms for the edit modal's room dropdown after floors are loaded
                            await loadRooms(bed.floor_id, editBedRoomSelect, bed.room_id);

                            editBedModal.show(); // Show the modal
                            showMessage(editBedMessage, '', ''); // Clear any previous messages in the modal
                            editBedForm.classList.remove('was-validated'); // Clear validation styling
                        } else {
                            showMessage(bedMessage, data.message || 'Failed to fetch bed details.', 'danger');
                        }
                    } catch (error) {
                        console.error('Error fetching bed details:', error);
                        showMessage(bedMessage, 'An error occurred while fetching bed details.', 'danger');
                    }
                }

                // Delete Bed Button
                if (event.target.closest('.delete-bed-btn')) {
                    const button = event.target.closest('.delete-bed-btn');
                    const bedId = button.dataset.id;
                    const bedNumber = button.dataset.bedNumber;
                    const roomNumber = button.dataset.roomNumber;
                    const hostelName = button.dataset.hostelName;

                    const confirmDelete = confirm(`Are you sure you want to delete Bed ${bedNumber} in Room ${roomNumber} from ${hostelName} (ID: ${bedId})?`);

                    if (confirmDelete) {
                        console.log('Confirmed deletion for Bed ID:', bedId);
                        showMessage(bedMessage, 'Deleting bed...', 'info');

                        try {
                            const response = await fetch('delete_bed_process.php', {
                                method: 'POST',
                                headers: {
                                    'Content-Type': 'application/json',
                                },
                                body: JSON.stringify({ bed_id: bedId }),
                            });

                            const result = await response.json();

                            if (result.success) {
                                showMessage(bedMessage, result.message, 'success');
                                setTimeout(() => {
                                    location.reload();
                                }, 1000);
                            } else {
                                showMessage(bedMessage, result.message, 'danger');
                            }
                        } catch (error) {
                            console.error('Error deleting bed:', error);
                            showMessage(bedMessage, 'An unexpected error occurred during deletion. Please try again.', 'danger');
                        }
                    } else {
                        showMessage(bedMessage, 'Deletion cancelled.', 'secondary');
                    }
                }
            });

            // --- Event Listeners for Dynamic Dropdowns (Edit Modals) ---
            editRoomHostelSelect.addEventListener('change', function() {
                // This select is disabled, so this listener won't fire via user interaction
                // It's here for consistency if it were to become enabled.
                // The loadFloors call is made when the modal is opened.
            });

            editBedHostelSelect.addEventListener('change', function() {
                // This select is disabled, so this listener won't fire via user interaction
                // The loadFloors call is made when the modal is opened.
            });

            editRoomFloorSelect.addEventListener('change', function() {
                // If the floor is changed in the edit room modal, we might need to re-validate room number uniqueness.
                // For now, no dynamic updates needed for rooms when floor changes in edit modal.
            });

            editBedFloorSelect.addEventListener('change', function() {
                loadRooms(this.value, editBedRoomSelect);
            });


            // --- Handle Save Changes Button (Edit Room Modal) ---
            saveEditRoomBtn.addEventListener('click', async function() {
                if (!editRoomForm.checkValidity()) {
                    event.stopPropagation();
                    editRoomForm.classList.add('was-validated');
                    showMessage(editRoomMessage, 'Please fill all required fields correctly.', 'warning');
                    return;
                } else {
                    editRoomForm.classList.remove('was-validated');
                }

                const formData = new FormData(editRoomForm);
                const updatedRoomData = {};
                for (let [key, value] of formData.entries()) {
                    updatedRoomData[key] = value;
                }
                updatedRoomData['capacity'] = parseInt(updatedRoomData['capacity']); // Ensure integer

                console.log('Submitting updated room data:', updatedRoomData);
                showMessage(editRoomMessage, 'Saving changes...', 'info');

                try {
                    const response = await fetch('update_room_process.php', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                        },
                        body: JSON.stringify(updatedRoomData),
                    });

                    const result = await response.json();

                    if (result.success) {
                        showMessage(editRoomMessage, result.message, 'success');
                        setTimeout(() => {
                            editRoomModal.hide(); // Hide modal first
                            location.reload(); // Reload page to show updated data
                        }, 1000);
                    } else {
                        showMessage(editRoomMessage, result.message, 'danger');
                    }
                } catch (error) {
                    console.error('Error updating room:', error);
                    showMessage(editRoomMessage, 'An unexpected error occurred while saving changes. Please try again.', 'danger');
                }
            });

            // --- Handle Save Changes Button (Edit Bed Modal) ---
            saveEditBedBtn.addEventListener('click', async function() {
                if (!editBedForm.checkValidity()) {
                    event.stopPropagation();
                    editBedForm.classList.add('was-validated');
                    showMessage(editBedMessage, 'Please fill all required fields correctly.', 'warning');
                    return;
                } else {
                    editBedForm.classList.remove('was-validated');
                }

                const formData = new FormData(editBedForm);
                const updatedBedData = {};
                for (let [key, value] of formData.entries()) {
                    updatedBedData[key] = value;
                }
                updatedBedData['isOccupied'] = parseInt(updatedBedData['isOccupied']); // Ensure integer

                console.log('Submitting updated bed data:', updatedBedData);
                showMessage(editBedMessage, 'Saving changes...', 'info');

                try {
                    const response = await fetch('update_bed_process.php', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                        },
                        body: JSON.stringify(updatedBedData),
                    });

                    const result = await response.json();

                    if (result.success) {
                        showMessage(editBedMessage, result.message, 'success');
                        setTimeout(() => {
                            editBedModal.hide(); // Hide modal first
                            location.reload(); // Reload page to show updated data
                        }, 1000);
                    } else {
                        showMessage(editBedMessage, result.message, 'danger');
                    }
                } catch (error) {
                    console.error('Error updating bed:', error);
                    showMessage(editBedMessage, 'An unexpected error occurred while saving changes. Please try again.', 'danger');
                }
            });
        });
    </script>
<?php include_once 'footer.php'; ?>
