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

// Ensure admin is logged in
if (!isset($_SESSION['admin_logged_in']) || $_SESSION['admin_logged_in'] !== true) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit;
}

// Check if bed_id is sent
if (!isset($_POST['bed_id'])) {
    echo json_encode(['success' => false, 'message' => 'Invalid request']);
    exit;
}

$bed_id = intval($_POST['bed_id']);

try {
    // Find active assignment for this bed
    $stmt = $conn->prepare("SELECT assignment_id 
                            FROM student_assignments 
                            WHERE bed_id = ? AND status = 'assigned' 
                            LIMIT 1");
    $stmt->bind_param("i", $bed_id);
    $stmt->execute();
    $result = $stmt->get_result();
    $assignment = $result->fetch_assoc();

    if (!$assignment) {
        echo json_encode(['success' => false, 'message' => 'No active assignment found for this bed']);
        exit;
    }

    $assignment_id = $assignment['assignment_id'];

    // Begin transaction
    $conn->begin_transaction();

    // Mark assignment as vacated
    $stmt1 = $conn->prepare("UPDATE student_assignments 
                             SET status = 'vacated' 
                             WHERE assignment_id = ?");
    $stmt1->bind_param("i", $assignment_id);
    $stmt1->execute();

    // Mark bed as available
    $stmt2 = $conn->prepare("UPDATE beds 
                             SET is_occupied = 0 
                             WHERE bed_id = ?");
    $stmt2->bind_param("i", $bed_id);
    $stmt2->execute();

    $conn->commit();

    echo json_encode(['success' => true, 'message' => 'Bed has been vacated successfully.']);
} catch (Exception $e) {
    $conn->rollback();
    echo json_encode(['success' => false, 'message' => 'Error: ' . $e->getMessage()]);
}
