<?php
// --- Fehlerberichterstattung (DEBUG) ---
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// --- Interne Debugging-Log-Funktion ---
$debugLogFile = __DIR__ . '/validate_address_details_debug.log';

function internal_debug_log($message, $logFile) {
    file_put_contents($logFile, date('[Y-m-d H:i:s]') . ' ' . $message . PHP_EOL, FILE_APPEND);
}

internal_debug_log("--- " . basename(__FILE__) . " START (Nominatim q= Query - FINAL FORMAT) ---", $debugLogFile);

// --- CORS FIX & Header setzen ---
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Origin: https://www.app.stolperclean.de");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type");

// ----- Hauptlogik: Nominatim-Anfrage verarbeiten -----

if (isset($_GET['street']) && isset($_GET['house_no']) && isset($_GET['localdistrict'])) {
    internal_debug_log("Received GET parameters: " . print_r($_GET, true), $debugLogFile);

    // Parameter aus $_GET DEKODIEREN (gegen doppelte Kodierung)
    $street = urldecode($_GET['street']);
    $house_no = urldecode($_GET['house_no']);
    $localdistrict = urldecode($_GET['localdistrict']);
    $city = urldecode($_GET['city'] ?? "Berlin");
    $country = urldecode($_GET['country'] ?? "Deutschland");
    
    internal_debug_log("Decoded values: Street={$street}, HouseNo={$house_no}, District={$localdistrict}", $debugLogFile);

    // STRATEGIE: Freitext-Abfrage (q=) für bessere Interpolation
    $full_query = "{$street} {$house_no}, {$localdistrict}, {$city}, {$country}";

    $nominatim_url_params = [
        'q' => $full_query, 
        'format' => 'json',
        'addressdetails' => '1',
        'dedup' => '1',
        'limit' => '1'
    ];

    $nominatim_url = "https://nominatim.openstreetmap.org/search?" . http_build_query($nominatim_url_params);
    
    internal_debug_log("Generated Nominatim URL: " . $nominatim_url, $debugLogFile);

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $nominatim_url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
        'User-Agent: Stolperclean/1.0 (Stolperclean@gmail.com)'
    ));

    $response = curl_exec($ch);

    if (curl_errno($ch)) {
        $error_msg = curl_error($ch);
        curl_close($ch);
        internal_debug_log("cURL Error: " . $error_msg, $debugLogFile);
        http_response_code(500);
        echo json_encode(['error' => 'Interner Serverfehler (cURL): ' . $error_msg]);
        exit;
    }

    curl_close($ch);
    internal_debug_log("Raw Nominatim Response: " . $response, $debugLogFile);
    
    // --- WICHTIGE KORREKTUR: Konvertierung in das vom Frontend erwartete {items: [...]} Objekt ---
    $nominatim_array = json_decode($response, true);

    if (json_last_error() !== JSON_ERROR_NONE) {
        // Falls Nominatim kein gültiges JSON liefert
        internal_debug_log("JSON Decode Error on Nominatim response: " . json_last_error_msg(), $debugLogFile);
        $final_response = ['items' => []];
    } else {
        // Verpackt das Nominatim-Array in das vom Client erwartete 'items'-Objekt.
        // Wenn $response [] ist (kein Treffer), ist $nominatim_array [] und 'items' wird []
        $final_response = ['items' => $nominatim_array];
    }
    
    internal_debug_log("Converted Frontend Response: " . json_encode($final_response), $debugLogFile);

    // Geben Sie die konvertierte Antwort zurück
    echo json_encode($final_response); 

} else {
    internal_debug_log("Missing required GET parameters.", $debugLogFile);
    http_response_code(400);
    echo json_encode(['error' => 'Fehlende Adress-Parameter. street, house_no und localdistrict sind erforderlich.']);
}

internal_debug_log("--- " . basename(__FILE__) . " END ---", $debugLogFile);
?>