<?php
// get_areas.php: return all areas as JSON

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 {
    $stmt = $pdo->query("
        SELECT Id, Name, Description, BasePricePerPlot
        FROM Areas
        ORDER BY Id DESC
    ");
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

    $areas = [];

    foreach ($rows as $r) {
        $rawBase = $r['BasePricePerPlot'];

        // Keep behaviour compatible:
        // - If DB has NULL or empty string, send null in JSON.
        // - Otherwise send a numeric value (float) so C# decimal? can read it.
        if ($rawBase === null || $rawBase === '') {
            $basePrice = null;
        } else {
            $basePrice = (float)$rawBase;
        }

        $areas[] = [
            'Id' => (int)$r['Id'],
            'Name' => $r['Name'],
            'Description' => $r['Description'],
            'BasePricePerPlot' => $basePrice,
        ];
    }

    echo json_encode($areas);
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        'error' => 'Failed to load areas',
        'details' => $e->getMessage()
    ]);
}
