<?php
// delete_area.php: delete area only if it has no plots

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');

require_once __DIR__ . '/../../config.php';

try {
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        throw new Exception('Invalid method');
    }

    $raw = file_get_contents('php://input');
    $data = json_decode($raw, true);
    if (!is_array($data)) {
        throw new Exception('Invalid JSON body');
    }

    $id = isset($data['id']) ? (int)$data['id'] : 0;
    if ($id <= 0) {
        throw new Exception('Invalid area id');
    }

    // Check for plots
    $stmt = $pdo->prepare("SELECT COUNT(*) FROM Plots WHERE AreaId = :id");
    $stmt->execute([':id' => $id]);
    $count = (int)$stmt->fetchColumn();

    if ($count > 0) {
        throw new Exception('Cannot delete area: there are plots registered in this area.');
    }

    // Delete area
    $del = $pdo->prepare("DELETE FROM Areas WHERE Id = :id");
    $del->execute([':id' => $id]);

    echo json_encode(['success' => true]);
} catch (Exception $e) {
    http_response_code(400);
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}
