<?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 = "Assignments to Bed";
include_once '_header.php';
include_once '_sidebar.php';

// If bed is preselected from floor plan
$bed_id = isset($_GET['bed_id']) ? intval($_GET['bed_id']) : 0;
?>
<main class="container mt-4">
    <div class="card">
        <div class="card-header">
            Assign Student to Bed
        </div>
        <div class="card-body">
            <form action="assign_student_action.php" method="POST">
                <input type="hidden" name="bed_id" value="<?php echo $bed_id; ?>">

                <!-- Class dropdown -->
                <div class="mb-3">
                    <label class="form-label">Select Class</label>
                    <select class="form-select" id="classSelect" required>
                        <option value="">Choose...</option>
                        <?php
                        $classes = $conn->query("SELECT DISTINCT class_grade FROM students ORDER BY class_grade ASC");
                        while ($c = $classes->fetch_assoc()) {
                            echo "<option value='".htmlspecialchars($c['class_grade'])."'>".htmlspecialchars($c['class_grade'])."</option>";
                        }
                        ?>
                    </select>
                </div>

                <!-- Student dropdown -->
                <div class="mb-3">
                    <label class="form-label">Select Student</label>
                    <select class="form-select" name="unique_reg_number" id="studentSelect" required>
                        <option value="">Choose class first...</option>
                    </select>
                </div>

                <button type="submit" class="btn btn-primary"><i class="fas fa-user-plus"></i> Assign</button>
            </form>
        </div>
    </div>
</main>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
// Load students by class
$('#classSelect').change(function() {
    let classGrade = $(this).val();
    if (!classGrade) {
        $('#studentSelect').html('<option value="">Choose class first...</option>');
        return;
    }
    $.get('get_students_by_class.php', {class_grade: classGrade}, function(data) {
        $('#studentSelect').html(data);
    });
});
</script>

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