<?php
// delete_room_process.php - Handles deleting a room from the database

// Enable full error reporting for debugging. REMOVE IN PRODUCTION!
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

require_once 'config.php'; // Include database configuration
header('Content-Type: application/json'); // Set header to return JSON response

// Check if the request method is POST and if room_id is provided
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Get the raw POST data (JSON sent from fetch API)
    $input = file_get_contents('php://input');
    $data = json_decode($input, true);

    $roomId = filter_var($data['room_id'] ?? '', FILTER_SANITIZE_NUMBER_INT);

    // Server-side validation
    if (empty($roomId)) {
        echo json_encode(['success' => false, 'message' => 'Room ID is required for deletion.']);
        exit;
    }

    // Prepare a DELETE SQL statement
    // Due to ON DELETE CASCADE on beds table, associated beds will also be deleted.
    $sql = "DELETE FROM rooms WHERE room_id = :room_id";

    try {
        $stmt = $pdo->prepare($sql);
        $stmt->bindParam(':room_id', $roomId, PDO::PARAM_INT);

        if ($stmt->execute()) {
            // Check if any rows were actually affected by the deletion
            if ($stmt->rowCount() > 0) {
                echo json_encode(['success' => true, 'message' => 'Room and associated beds deleted successfully!']);
            } else {
                echo json_encode(['success' => false, 'message' => 'Room not found or already deleted.']);
            }
        } else {
            // This case is less common with PDO, but handles generic execution failures
            echo json_encode(['success' => false, 'message' => 'Failed to delete room. Please try again.']);
        }
    } catch (PDOException $e) {
        // Catch PDO exceptions (e.g., foreign key constraints if other tables depend on rooms, like student assignments)
        error_log("Database error deleting room: " . $e->getMessage());
        echo json_encode(['success' => false, 'message' => 'A database error occurred during deletion. It might be linked to student assignments.']);
    }
} else {
    // If the request method is not POST, deny access
    echo json_encode(['success' => false, 'message' => 'Invalid request method.']);
}

