<?php
/**
 * Wetter-Debug: Geocoding und Forecast Schritt für Schritt testen.
 */
require_once __DIR__ . '/../../config.php';
require_once __DIR__ . '/auth.php';
require_once FUNCTIONS_ROOT . '/functions_common.php';

function_admin_login_erfordern();

if (!defined('DatabaseDEBUG') || DatabaseDEBUG !== true) {
    http_response_code(403);
    exit('Access denied');
}

$plz = isset($_REQUEST['plz']) ? trim((string) $_REQUEST['plz']) : '';
$debugSteps = [];
$finalError = null;
$finalResult = null;

if ($plz !== '') {
    $search = preg_match('/^\d{4,6}$/', $plz) ? $plz . ', Germany' : $plz . ', Germany';
    $lat = null;
    $lon = null;
    $tz = 'Europe/Berlin';

    // Schritt 1: Open-Meteo Geocoding
    $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]]);
    $debugSteps[] = [
        'title' => '1. Open-Meteo Geocoding',
        'url' => $geoUrl,
        'request' => ['Suchbegriff' => $search],
    ];
    $geoJson = @file_get_contents($geoUrl, false, $ctx);
    if ($geoJson === false) {
        $err = error_get_last();
        $debugSteps[count($debugSteps) - 1]['error'] = 'HTTP-Anfrage fehlgeschlagen. ' . ($err ? $err['message'] : 'Unbekannter Fehler');
    } else {
        $geo = json_decode($geoJson, true);
        $debugSteps[count($debugSteps) - 1]['response_raw'] = $geoJson;
        $debugSteps[count($debugSteps) - 1]['response_parsed'] = $geo;
        if (!empty($geo['results'][0])) {
            $lat = (float) $geo['results'][0]['latitude'];
            $lon = (float) $geo['results'][0]['longitude'];
            $tz = $geo['results'][0]['timezone'] ?? 'Europe/Berlin';
            $debugSteps[count($debugSteps) - 1]['result'] = "OK: lat=$lat, lon=$lon, tz=$tz";
        } else {
            $debugSteps[count($debugSteps) - 1]['result'] = 'Keine Treffer (results leer oder fehlend)';
        }
    }

    // Schritt 2: Fallback Nominatim
    if ($lat === null && $lon === null) {
        $nominatimUrl = 'https://nominatim.openstreetmap.org/search?' . http_build_query([
            'q' => $search,
            'format' => 'json',
            'limit' => 1
        ]);
        $ctxNom = stream_context_create([
            'http' => [
                'timeout' => 8,
                'header' => "User-Agent: Wecker-App/1.0 (PHP)\r\n"
            ]
        ]);
        $debugSteps[] = [
            'title' => '2. Fallback: Nominatim (OSM)',
            'url' => $nominatimUrl,
        ];
        $nomJson = @file_get_contents($nominatimUrl, false, $ctxNom);
        if ($nomJson === false) {
            $err = error_get_last();
            $debugSteps[count($debugSteps) - 1]['error'] = 'HTTP-Anfrage fehlgeschlagen. ' . ($err ? $err['message'] : 'Unbekannter Fehler');
        } else {
            $nom = json_decode($nomJson, true);
            $debugSteps[count($debugSteps) - 1]['response_raw'] = $nomJson;
            $debugSteps[count($debugSteps) - 1]['response_parsed'] = $nom;
            if (!empty($nom[0]['lat']) && !empty($nom[0]['lon'])) {
                $lat = (float) $nom[0]['lat'];
                $lon = (float) $nom[0]['lon'];
                $debugSteps[count($debugSteps) - 1]['result'] = "OK: lat=$lat, lon=$lon";
            } else {
                $debugSteps[count($debugSteps) - 1]['result'] = 'Keine Treffer';
            }
        }
    }

    if ($lat === null || $lon === null) {
        $finalError = 'Ort nicht gefunden (weder Open-Meteo noch Nominatim).';
    } else {
        // Schritt 3: Open-Meteo Forecast
        $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',
            'timezone' => $tz
        ]);
        $debugSteps[] = [
            'title' => '3. Open-Meteo Forecast',
            'url' => $forecastUrl,
            'request' => ['lat' => $lat, 'lon' => $lon, 'timezone' => $tz],
        ];
        $forecastJson = @file_get_contents($forecastUrl, false, $ctx);
        if ($forecastJson === false) {
            $err = error_get_last();
            $debugSteps[count($debugSteps) - 1]['error'] = 'HTTP-Anfrage fehlgeschlagen. ' . ($err ? $err['message'] : 'Wetter-API nicht erreichbar (Timeout/Netzwerk?)');
            $finalError = 'Wetter nicht erreichbar.';
        } else {
            $forecast = json_decode($forecastJson, true);
            $debugSteps[count($debugSteps) - 1]['response_parsed'] = $forecast;
            if (empty($forecast['current'])) {
                $debugSteps[count($debugSteps) - 1]['result'] = 'Antwort ohne current-Daten';
                $finalError = 'Keine Wetterdaten in der Antwort.';
            } else {
                $current = $forecast['current'];
                $daily = $forecast['daily'] ?? [];
                $out = [
                    'ok' => true,
                    'current' => [
                        'temp' => round($current['temperature_2m'] ?? 0, 1),
                        'beschreibung' => function_wmo_beschreibung($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' => function_wmo_beschreibung($daily['weather_code'][$i] ?? 0)
                        ];
                    }
                }
                $debugSteps[count($debugSteps) - 1]['result'] = 'OK';
                $finalResult = $out;
            }
        }
    }
}
?>
<!DOCTYPE html>
<html lang="de">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Wetter-Debug</title>
<style>
body { margin: 0; font-family: system-ui, sans-serif; background: #0f1115; color: #e6e6e6; padding: 16px; }
h1 { margin-top: 0; font-size: 1.25rem; }
a { color: #4da3ff; }
.debug-section { background: #151922; border: 1px solid #2a2f3a; border-radius: 8px; padding: 12px; margin-bottom: 16px; }
.debug-section h2 { margin: 0 0 8px 0; font-size: 1rem; color: #8b949e; }
.debug-section .url { word-break: break-all; font-size: 0.85rem; color: #4da3ff; margin-bottom: 8px; }
.debug-section pre { background: #0d1117; padding: 10px; border-radius: 6px; overflow-x: auto; font-size: 0.8rem; margin: 8px 0; white-space: pre-wrap; }
.debug-section .error { color: #ff6b6b; }
.debug-section .ok { color: #3fb950; }
form { margin-bottom: 20px; display: flex; gap: 8px; flex-wrap: wrap; align-items: center; }
form input[type="text"] { padding: 8px 12px; background: #1c2130; border: 1px solid #2a2f3a; color: #e6e6e6; border-radius: 6px; min-width: 200px; }
form button { padding: 8px 16px; background: #238636; border: none; color: #fff; border-radius: 6px; cursor: pointer; }
form button:hover { background: #2ea043; }
.result-ok { background: #0d1117; border: 1px solid #3fb950; color: #3fb950; padding: 12px; border-radius: 8px; margin-bottom: 16px; }
.result-err { background: #0d1117; border: 1px solid #ff6b6b; color: #ff6b6b; padding: 12px; border-radius: 8px; margin-bottom: 16px; }
</style>
</head>
<body>

<h1>Wetter-Debug</h1>
<p>Ort oder PLZ eingeben und testen. Zeigt Geocoding und Forecast-Anfragen sowie Antworten.</p>

<form method="get">
    <input type="text" name="plz" value="<?= htmlspecialchars($plz) ?>" placeholder="z.B. 97478 oder Knetzgau">
    <button type="submit">Testen</button>
</form>

<?php if ($plz !== ''): ?>
    <?php if ($finalError): ?>
        <div class="result-err"><strong>Fehler:</strong> <?= htmlspecialchars($finalError) ?></div>
    <?php endif; ?>
    <?php if ($finalResult): ?>
        <div class="result-ok">
            <strong>Ergebnis (wie in der App):</strong>
            <pre><?= htmlspecialchars(json_encode($finalResult, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE)) ?></pre>
        </div>
    <?php endif; ?>

    <?php foreach ($debugSteps as $step): ?>
        <div class="debug-section">
            <h2><?= htmlspecialchars($step['title']) ?></h2>
            <div class="url"><?= htmlspecialchars($step['url']) ?></div>
            <?php if (!empty($step['request'])): ?>
                <div>Request: <pre><?= htmlspecialchars(json_encode($step['request'], JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE)) ?></pre></div>
            <?php endif; ?>
            <?php if (!empty($step['error'])): ?>
                <div class="error"><?= htmlspecialchars($step['error']) ?></div>
            <?php endif; ?>
            <?php if (isset($step['result'])): ?>
                <div class="ok"><?= htmlspecialchars($step['result']) ?></div>
            <?php endif; ?>
            <?php if (!empty($step['response_raw'])): ?>
                <details>
                    <summary>Rohantwort (<?= strlen($step['response_raw']) ?> Zeichen)</summary>
                    <pre><?= htmlspecialchars(strlen($step['response_raw']) > 2000 ? substr($step['response_raw'], 0, 2000) . "\n... (gekürzt)" : $step['response_raw']) ?></pre>
                </details>
            <?php endif; ?>
            <?php if (!empty($step['response_parsed'])): ?>
                <details>
                    <summary>Geparste Antwort</summary>
                    <pre><?= htmlspecialchars(json_encode($step['response_parsed'], JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE)) ?></pre>
                </details>
            <?php endif; ?>
        </div>
    <?php endforeach; ?>
<?php endif; ?>

<p><a href="index.php">Zurück zu Debug-Tools</a></p>

</body>
</html>
