<?php
session_start();
require_once 'db.php';

// Fetch floors + hostels
$floors_sql = "SELECT f.floor_id, f.floor_number, h.name AS hostel_name
               FROM floors f
               JOIN hostels h ON f.hostel_id = h.hostel_id
               ORDER BY f.floor_number DESC";
$floors = $conn->query($floors_sql);

while ($floor = $floors->fetch_assoc()):
    echo "<div class='mb-5'>";
    echo "<h3> " . htmlspecialchars($floor['hostel_name']) . " - Floor " . $floor['floor_number'] . "</h3>";
    echo "<div class='d-flex flex-wrap gap-4'>";

    // Fetch rooms for each floor
    $rooms_sql = "SELECT * FROM rooms WHERE floor_id = {$floor['floor_id']} ORDER BY room_number ASC";
    $rooms = $conn->query($rooms_sql);

    while ($room = $rooms->fetch_assoc()):
        echo "<div class='card shadow-sm' style='min-width: 250px;'>";
        echo "<div class='card-header bg-primary text-white'>Room {$room['room_number']} (" . ucfirst($room['room_type']) . ")</div>";
        echo "<div class='card-body d-flex flex-wrap gap-2'>";

        // Fetch beds for each room
        $beds_sql = "
            SELECT b.*, sa.status, s.full_name
            FROM beds b
            LEFT JOIN student_assignments sa 
                ON b.bed_id = sa.bed_id AND sa.status = 'assigned'
            LEFT JOIN students s 
                ON sa.unique_reg_number = s.unique_reg_number
            WHERE b.room_id = {$room['room_id']}
            ORDER BY b.bed_number ASC
        ";
        $beds = $conn->query($beds_sql);

        while ($bed = $beds->fetch_assoc()):
            $isOccupied = !empty($bed['status']) && $bed['status'] == 'assigned';
            $colorClass = $isOccupied ? 'bg-danger text-white' : 'bg-success text-white';
            $tooltip = $isOccupied ? "Occupied by: " . htmlspecialchars($bed['full_name']) : "Available";

            //  Only super admin (ID=1) can click
            if (isset($_SESSION['is_super_admin']) && $_SESSION['is_super_admin'] == 1) {
                echo "<div class='p-2 rounded bed-box {$colorClass}' 
                          style='width: 70px; text-align: center; cursor: pointer;'
                          title='{$tooltip}'
                          data-bed-id='{$bed['bed_id']}'
                          data-occupied='" . ($isOccupied ? 1 : 0) . "'>
                          Bed {$bed['bed_number']}
                      </div>";
            } else {
                // Non-super admins → read-only (no pointer, dimmed opacity)
                echo "<div class='p-2 rounded {$colorClass}' 
                          style='width: 70px; text-align: center; opacity: 0.6; cursor: not-allowed;'
                          title='Read-Only View'>
                          Bed {$bed['bed_number']}
                      </div>";
            }
        endwhile;

        echo "</div></div>";
    endwhile;

    echo "</div></div>";
endwhile;
?>
