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

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header("Location: assignments.php");
    exit;
}

$student = $_POST['unique_reg_number'] ?? '';
$bed_id  = intval($_POST['bed_id'] ?? 0);

if (empty($student) || $bed_id === 0) {
    $_SESSION['error'] = "Please select all fields before assigning.";
    header("Location: assignments.php");
    exit;
}

// Assign student to bed
$stmt = $conn->prepare("INSERT INTO student_assignments (unique_reg_number, bed_id) VALUES (?, ?)");
$stmt->bind_param("si", $student, $bed_id);
if ($stmt->execute()) {
    // Mark bed as occupied
    $conn->query("UPDATE beds SET is_occupied = 1 WHERE bed_id = $bed_id");
    $_SESSION['success'] = "Student assigned successfully.";
} else {
    $_SESSION['error'] = "Error assigning student.";
}
$stmt->close();

header("Location: floor_plan.php");
exit;
?>
