<?php
// We no longer need to display errors to the user, we will handle them.
ini_set('display_errors', 0);
ini_set('log_errors', 1);
ini_set('error_log', 'cross_section_php_error.log');
error_reporting(E_ALL);

header('Content-Type: application/json');

// Define a default empty structure for the response
$empty_response = [
    'hourly' => [
        'pressure_level' => [],
        'temperature' => [],
        'relative_humidity' => [],
        'wind_speed' => [],
    ]
];

// Basic validation for latitude and longitude
if (!isset($_GET['lat']) || !is_numeric($_GET['lat']) || $_GET['lat'] < -90 || $_GET['lat'] > 90) {
    http_response_code(400);
    echo json_encode(['error' => 'Invalid or missing latitude']);
    exit;
}

if (!isset($_GET['lon']) || !is_numeric($_GET['lon']) || $_GET['lon'] < -180 || $_GET['lon'] > 180) {
    http_response_code(400);
    echo json_encode(['error' => 'Invalid or missing longitude']);
    exit;
}

$lat = $_GET['lat'];
$lon = $_GET['lon'];

// Request only a single, simple variable.
$variables = 'temperature_2m';
$url = "https://api.open-meteo.com/v1/forecast?latitude=$lat&longitude=$lon&hourly=$variables&models=gfs_global";

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// Use a shorter 10-second timeout.
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_USERAGENT, 'MyWeatherApp/1.0');

$response = curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$curl_error = curl_error($ch);
curl_close($ch);

// If there's a cURL error (like a timeout) or a non-200 response,
// return the empty structure instead of a server error.
if ($curl_error || $http_code !== 200) {
    echo json_encode($empty_response);
    exit;
}

$data = json_decode($response, true);

if (json_last_error() !== JSON_ERROR_NONE || !isset($data['hourly']['temperature_2m'])) {
    // If the response is not valid JSON or is missing data, return the empty structure.
    echo json_encode($empty_response);
    exit;
}

// The API only gives us one variable, so we will only populate that one.
// The frontend chart will have to handle the missing data for other variables.
$output = [
    'hourly' => [
        'pressure_level' => [1000], // Placeholder pressure level
        'temperature' => $data['hourly']['temperature_2m'],
        'relative_humidity' => [], // Empty data
        'wind_speed' => [], // Empty data
    ]
];

echo json_encode($output);

?>