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

// Get parameters from the request
$layer = $_GET['layer'] ?? 'clouds_new';
$z = $_GET['z'] ?? 0;
$x = $_GET['x'] ?? 0;
$y = $_GET['y'] ?? 0;

// Validate parameters (basic validation)
if (!is_numeric($z) || !is_numeric($x) || !is_numeric($y)) {
    header("HTTP/1.1 400 Bad Request");
    echo "Invalid tile coordinates.";
    exit;
}

// Construct the OpenWeatherMap API URL
$apiKey = defined('OWM_API_KEY') ? OWM_API_KEY : '';
if (empty($apiKey)) {
    header("HTTP/1.1 500 Internal Server Error");
    echo "API key is not configured.";
    exit;
}

$url = "https://tile.openweathermap.org/map/{$layer}/{$z}/{$x}/{$y}.png?appid={$apiKey}";

// Fetch the tile using cURL
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
// Follow redirects, as OWM might use them
curl_setopt($ch, CURLOPT_TIMEOUT, 20);
// Set a reasonable timeout

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

// Check for errors and serve the tile
if ($http_code == 200 && !empty($tile_data)) {
    header('Content-Type: image/png');
    header('Content-Length: ' . strlen($tile_data));
    echo $tile_data;
} else {
    // Always return a 200 OK with a transparent pixel to prevent breaking the map.
    header("HTTP/1.1 200 OK");
    $transparent_pixel = base64_decode('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=');
    header('Content-Type: image/png');
    header('Content-Length: ' . strlen($transparent_pixel));
    echo $transparent_pixel;
}
exit;
?>