
<?php
declare(strict_types=1);

// Set header for JSON response
header('Content-Type: application/json; charset=utf-8');

try {
    // 1. Define root if not set
    if (!defined('WX_ROOT')) {
        define('WX_ROOT', dirname(__DIR__, 2) . '/weather');
    }

    // 2. Load database and core bootstraps
    $dbPath = __DIR__ . '/../../weather/php/weather.db.php';
    $locPath = __DIR__ . '/../../weather/php/weather.locations.php';

    if (file_exists($dbPath)) {
        require_once $dbPath;
    }
    if (file_exists($locPath)) {
        require_once $locPath;
    }

    // 3. Fetch locations if function exists
    $locations = [];
    if (function_exists('wx_locations_list')) {
        $locations = wx_locations_list(true); // true = enabled only
    } elseif (function_exists('wx_all')) {
        $locations = wx_all('SELECT * FROM wx_locations WHERE enabled = 1 ORDER BY sort_order, id');
    }

    // 4. Output valid JSON array
    echo json_encode($locations, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);

} catch (Throwable $e) {
    http_response_code(500);
    echo json_encode(['ok' => false, 'error' => $e->getMessage()]);
}
