<?php
// Fetches live hurricane data from NOAA/NHC and returns as GeoJSON
header('Content-Type: application/json');

// Base URL for the NHC's ArcGIS REST service
$baseUrl = 'https://services9.arcgis.com/RHVPKKiFTONKtxq3/arcgis/rest/services/Active_Hurricanes_v1/FeatureServer/';

// Function to fetch data from a URL
function get_json($url) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_USERAGENT, 'worldsphere.ai bot');
    curl_setopt($ch, CURLOPT_TIMEOUT, 15);
    $response = curl_exec($ch);
    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    if ($http_code !== 200) {
        return null;
    }
    return json_decode($response, true);
}

// Main function to get all active hurricane data
function get_active_hurricanes() {
    global $baseUrl;
    $features = [];

    // Layer IDs for forecast points, tracks, and cones
    $layerIds = [
        0, // Forecast Position
        2, // Forecast Track
        4, // Forecast Error Cone
    ];

    foreach ($layerIds as $layerId) {
        $queryUrl = "{$baseUrl}{$layerId}/query?where=1%3D1&outFields=*&f=geojson";
        $data = get_json($queryUrl);

        if ($data && !empty($data['features'])) {
            foreach($data['features'] as $feature) {
                $features[] = $feature;
            }
        }
    }

    return [
        'type' => 'FeatureCollection',
        'features' => $features
    ];
}

$data = get_active_hurricanes();
echo json_encode($data);

?>