<?php
// delete_floor_process.php - Handles deleting a floor 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 floor_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);

    $floorId = filter_var($data['floor_id'] ?? '', FILTER_VALIDATE_INT);

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

    // Prepare a DELETE SQL statement
    $sql = "DELETE FROM floors WHERE floor_id = :floor_id";

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

        if ($stmt->execute()) {
            if ($stmt->rowCount() > 0) {
                echo json_encode(['success' => true, 'message' => 'Floor deleted successfully!']);
            } else {
                echo json_encode(['success' => false, 'message' => 'Floor not found or already deleted.']);
            }
        } else {
            echo json_encode(['success' => false, 'message' => 'Failed to delete floor. Please try again.']);
        }
    } catch (PDOException $e) {
        error_log("Database error deleting floor: " . $e->getMessage());
        echo json_encode(['success' => false, 'message' => 'A database error occurred during deletion. It might be linked to rooms or other records.']);
    }
} else {
    echo json_encode(['success' => false, 'message' => 'Invalid request method.']);
}
