<?php
// get_available_plots.php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

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

if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
    http_response_code(405);
    echo json_encode(['success' => false, 'message' => 'Method not allowed']);
    exit;
}

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

$areaId = isset($_GET['areaId']) ? (int)$_GET['areaId'] : 0;
if ($areaId <= 0) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'areaId is required']);
    exit;
}

try {
    // Accept both text and numeric representations of "available"
        $stmt = $pdo->prepare("
        SELECT Id, Code, FullPrice
        FROM Plots
        WHERE AreaId = :areaId
          AND Status = 'Available'
        ORDER BY Code
    ");

    $stmt->execute([':areaId' => $areaId]);
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

    echo json_encode($rows);
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => 'Failed to load plots.',
        'details' => $e->getMessage()
    ]);
}
