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

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

$pageTitle = "Floors Beds";
include_once '_header.php';
include_once '_sidebar.php';
?>
<main class="container-fluid" id="appContent">
    <h5 class="mb-4">Available Beds</h5>

    <!-- Filters -->
    <div class="row mb-3">
        <div class="col-md-4">
            <label class="form-label">Select Hostel</label>
            <select id="hostelFilter" class="form-select">
                <option value="">All Hostels</option>
                <?php
                $hostels = $conn->query("SELECT hostel_id, name FROM hostels WHERE status='active' ORDER BY name");
                while ($h = $hostels->fetch_assoc()) {
                    echo "<option value='{$h['hostel_id']}'>" . htmlspecialchars($h['name']) . "</option>";
                }
                ?>
            </select>
        </div>
        <div class="col-md-4">
            <label class="form-label">Select Floor</label>
            <select id="floorFilter" class="form-select">
                <option value="">All Floors</option>
            </select>
        </div>
        <div class="col-md-4">
            <label class="form-label">Select Room</label>
            <select id="roomFilter" class="form-select">
                <option value="">All Rooms</option>
            </select>
        </div>
    </div>

    <div class="card shadow-sm">
        <div class="card-body">
            <div class="table-responsive">
                <table id="bedsTable" class="table table-striped table-bordered display nowrap" style="width:100%">
                    <thead class="table-dark">
                        <tr>
                            <th>Hostel</th>
                            <th>Floor</th>
                            <th>Room</th>
                            <th>Bed</th>
                            <th>Room Type</th>
                            <th>Capacity</th>
                            <th>Current Occupancy</th>
                            <th>Action</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php
                        $sql = "
                            SELECT 
                                h.name AS hostel_name,
                                f.floor_number,
                                r.room_number,
                                b.bed_id,
                                b.bed_number,
                                r.room_type,
                                r.capacity,
                                r.current_occupancy
                            FROM beds b
                            INNER JOIN rooms r ON b.room_id = r.room_id
                            INNER JOIN floors f ON r.floor_id = f.floor_id
                            INNER JOIN hostels h ON f.hostel_id = h.hostel_id
                            WHERE b.is_occupied = 0
                            ORDER BY h.name, f.floor_number, r.room_number, b.bed_number
                        ";
                        $result = $conn->query($sql);
                        while ($row = $result->fetch_assoc()) {
                            echo "<tr data-hostel='{$row['hostel_name']}' data-floor='{$row['floor_number']}' data-room='{$row['room_number']}'>
                                    <td>" . htmlspecialchars($row['hostel_name']) . "</td>
                                    <td>Floor " . htmlspecialchars($row['floor_number']) . "</td>
                                    <td>" . htmlspecialchars($row['room_number']) . "</td>
                                    <td>" . htmlspecialchars($row['bed_number']) . "</td>
                                    <td>" . ucfirst(htmlspecialchars($row['room_type'])) . "</td>
                                    <td>" . htmlspecialchars($row['capacity']) . "</td>
                                    <td>" . htmlspecialchars($row['current_occupancy']) . "</td>
                                    <td>
                                        <a href='assignments.php?bed_id={$row['bed_id']}' class='btn btn-sm btn-primary'>
                                            Assign
                                        </a>
                                    </td>
                                  </tr>";
                        }
                        ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</main>

<!-- DataTables CSS -->
<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">

<!-- jQuery & DataTables JS -->
<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>
$(document).ready(function() {
    let table = $('#bedsTable').DataTable({
        responsive: true,
        dom: 'Bfrtip',
        buttons: [
            { extend: 'excelHtml5', title: 'Available_Beds' },
            { extend: 'csvHtml5', title: 'Available_Beds' }
        ]
    });

    // Load floors when hostel selected
    $('#hostelFilter').on('change', function() {
        let hostelId = $(this).val();
        $('#floorFilter').html('<option value="">All Floors</option>');
        $('#roomFilter').html('<option value="">All Rooms</option>');
        if (hostelId) {
            $.get('get_floors.php', { hostel_id: hostelId }, function(data) {
                $('#floorFilter').append(data);
            });
        }
        filterTable();
    });

    // Load rooms when floor selected
    $('#floorFilter').on('change', function() {
        let floorId = $(this).val();
        $('#roomFilter').html('<option value="">All Rooms</option>');
        if (floorId) {
            $.get('get_rooms.php', { floor_id: floorId }, function(data) {
                $('#roomFilter').append(data);
            });
        }
        filterTable();
    });

    // Filter table when room selected
    $('#roomFilter').on('change', function() {
        filterTable();
    });

    function filterTable() {
        let hostel = $('#hostelFilter option:selected').text();
        let floor = $('#floorFilter option:selected').text().replace('Floor ', '');
        let room = $('#roomFilter option:selected').text();

        table.columns(0).search(hostel !== 'All Hostels' ? hostel : '', true, false);
        table.columns(1).search(floor && floor !== 'All Floors' ? floor : '', true, false);
        table.columns(2).search(room && room !== 'All Rooms' ? room : '', true, false);
        table.draw();
    }
});
</script>

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