<?php
/**
 * Wetter per Open-Meteo: Geocoding (PLZ/Ort) -> Koordinaten, dann Forecast.
 * Aufruf: api_wetter.php?plz=80331 oder api_wetter.php?plz=München
 */
header('Content-Type: application/json; charset=utf-8');

$plz = isset($_GET['plz']) ? trim((string) $_GET['plz']) : '';
if ($plz === '') {
    echo json_encode(['ok' => false, 'error' => 'Parameter plz fehlt']);
    exit;
}

$search = $plz;
if (preg_match('/^\d{4,6}$/', $plz)) {
    $search = $plz . ' Germany';
}

$geoUrl = 'https://geocoding-api.open-meteo.com/v1/search?' . http_build_query([
    'name' => $search,
    'count' => 1,
    'language' => 'de',
    'format' => 'json'
]);

$ctx = stream_context_create(['http' => ['timeout' => 8]]);
$geoJson = @file_get_contents($geoUrl, false, $ctx);
if ($geoJson === false) {
    echo json_encode(['ok' => false, 'error' => 'Geocoding nicht erreichbar']);
    exit;
}

$geo = json_decode($geoJson, true);
if (empty($geo['results'][0])) {
    echo json_encode(['ok' => false, 'error' => 'Ort nicht gefunden']);
    exit;
}

$lat = (float) $geo['results'][0]['latitude'];
$lon = (float) $geo['results'][0]['longitude'];
$tz = $geo['results'][0]['timezone'] ?? 'Europe/Berlin';

$forecastUrl = 'https://api.open-meteo.com/v1/forecast?' . http_build_query([
    'latitude' => $lat,
    'longitude' => $lon,
    'current' => 'temperature_2m,weather_code',
    'daily' => 'temperature_2m_max,temperature_2m_min,weather_code,time',
    'timezone' => $tz
]);

$forecastJson = @file_get_contents($forecastUrl, false, $ctx);
if ($forecastJson === false) {
    echo json_encode(['ok' => false, 'error' => 'Wetter nicht erreichbar']);
    exit;
}

$forecast = json_decode($forecastJson, true);
if (empty($forecast['current'])) {
    echo json_encode(['ok' => false, 'error' => 'Keine Wetterdaten']);
    exit;
}

function wmoBeschreibung($code) {
    $map = [
        0 => 'Klar', 1 => 'Überwiegend klar', 2 => 'Teilweise bewölkt', 3 => 'Bewölkt',
        45 => 'Nebel', 48 => 'Nebel', 51 => 'Nieselregen', 53 => 'Nieselregen', 55 => 'Nieselregen',
        61 => 'Regen', 63 => 'Regen', 65 => 'Starkregen',
        71 => 'Schnee', 73 => 'Schnee', 75 => 'Starkschnee',
        77 => 'Schnee', 80 => 'Regenschauer', 81 => 'Regenschauer', 82 => 'Regenschauer',
        85 => 'Schneeschauer', 86 => 'Schneeschauer',
        95 => 'Gewitter', 96 => 'Gewitter mit Hagel', 99 => 'Gewitter mit Hagel'
    ];
    foreach ($map as $k => $v) { if ((int) $code === $k) return $v; }
    return 'Unbekannt';
}

$current = $forecast['current'];
$daily = $forecast['daily'] ?? [];

$out = [
    'ok' => true,
    'current' => [
        'temp' => round($current['temperature_2m'] ?? 0, 1),
        'beschreibung' => wmoBeschreibung($current['weather_code'] ?? 0)
    ],
    'daily' => []
];

if (!empty($daily['time']) && !empty($daily['temperature_2m_max'])) {
    for ($i = 0; $i < min(count($daily['time']), 7); $i++) {
        $datum = $daily['time'][$i];
        $out['daily'][] = [
            'datum' => date('D, d.m.', strtotime($datum)),
            'temp_max' => isset($daily['temperature_2m_max'][$i]) ? round($daily['temperature_2m_max'][$i], 0) : null,
            'temp_min' => isset($daily['temperature_2m_min'][$i]) ? round($daily['temperature_2m_min'][$i], 0) : null,
            'beschreibung' => wmoBeschreibung($daily['weather_code'][$i] ?? 0)
        ];
    }
}

echo json_encode($out);
