<?php
// floors.php - Floors Management Page
session_start();
require_once 'config.php';

// Auth check (only admin allowed)
if (!isset($_SESSION['admin_logged_in']) || $_SESSION['admin_logged_in'] !== true) {
    header('Location: admin_login.php');
    exit;
}

$pageTitle = "Floors Plan (Live)";
include_once '_header.php';
include_once '_sidebar.php';
?>
<main class="container-fluid">
    <h5 class="mb-4">Hostel Floor Plan</h5>
    <div id="floorPlanContainer" class="mt-3">
        Loading floor plan...
    </div>
</main>

<!-- Scripts -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<script>
/**
 * Load floor plan data from server
 */
function loadFloorPlan() {
    $.get('get_floor_plan_data.php', function (html) {
        $('#floorPlanContainer').html(html);
    }).fail(function () {
        $('#floorPlanContainer').html('<div class="alert alert-danger">Failed to load floor plan.</div>');
    });
}

// First load
loadFloorPlan();

// Refresh every 10 seconds
setInterval(loadFloorPlan, 10000);

/**
 * Handle bed box click
 */
$(document).on('click', '.bed-box', function () {
    let bedId = $(this).data('bed-id');
    let isOccupied = $(this).data('occupied');

    if (isOccupied == 1) {
        // Bed is occupied → ask to vacate
        Swal.fire({
            title: 'Vacate Bed?',
            text: "This bed is currently occupied. Do you want to vacate it?",
            icon: 'warning',
            showCancelButton: true,
            confirmButtonText: 'Yes, Vacate',
            cancelButtonText: 'Cancel'
        }).then((result) => {
            if (result.isConfirmed) {
                $.post('vacate_bed.php', { bed_id: bedId }, function (response) {
                    try {
                        let data = JSON.parse(response);
                        if (data.status === "success") {
                            Swal.fire('Done!', data.message, 'success');
                            loadFloorPlan();
                        } else {
                            //Swal.fire('Error', data.message, 'error');
                        }
                    } catch (err) {
                        console.error("Invalid JSON:", response);
                        //Swal.fire('Error', 'Unexpected server response.', 'error');
                    }
                }).fail(function () {
                    Swal.fire('Error', 'Network or server error.', 'error');
                });
            }
        });
    } else {
        // If free → go to assign student page
        window.location.href = 'assign_student_form.php?bed_id=' + bedId;
    }
});
</script>

<?php include_once 'footer.php'; ?>
