<?php
// get_wiki_coord.php
// Sucht Koordinaten zu Stolpersteinen in der Wikipedia

// === FEHLERBERICHTERSTATTUNG & LOGGING ===
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

function getHtml($url) {
    global $debugLogFile;
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) StolperCleanBot/1.0');
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 15); 

    $res = curl_exec($ch);
    
    if ($res === false) {
        internal_debug_log("cURL Fehler bei URL ($url): " . curl_error($ch), $debugLogFile);
    }
    
    curl_close($ch);
    return $res;
}

$debugLogFile = __DIR__ . '/get_wiki_coord_debug.log';

if (file_exists(__DIR__ . '/logging_functions.php')) {
    require_once __DIR__ . '/logging_functions.php';
} else {
    if (!function_exists('internal_debug_log')) {
        function internal_debug_log(string $message, string $logFile = '') {
            $timestamp = date('Y-m-d H:i:s');
            file_put_contents($logFile, "[$timestamp] $message\n", FILE_APPEND);
        }
    }
}

internal_debug_log("--- " . basename(__FILE__) . " START ---", $debugLogFile);

// === HEADER ===
header('Content-Type: application/json; charset=utf-8');

// === PARAMETER ===
$district = $_GET['district'] ?? '';
$name     = $_GET['name'] ?? ''; 
$street   = $_GET['street'] ?? '';

if (!$district) {
    internal_debug_log("Fehler: Bezirk (district) fehlt.", $debugLogFile);
    echo json_encode(['success' => false, 'error' => 'District missing']);
    exit;
}

// === WIKIPEDIA FETCH ===
$wikiUrl = "https://de.wikipedia.org/wiki/Liste_der_Stolpersteine_in_Berlin-" . urlencode($district);
internal_debug_log("Lade Wikipedia Liste: $wikiUrl", $debugLogFile);

$mainHtml = getHtml($wikiUrl);

if (!$mainHtml) {
    internal_debug_log("Fehler: Wikipedia-HTML konnte nicht geladen werden.", $debugLogFile);
    echo json_encode(['success' => false, 'error' => 'Could not fetch Wikipedia']);
    exit;
}

// === PARSING ===
try {
    $dom = new DOMDocument();
    @$dom->loadHTML(mb_convert_encoding($mainHtml, 'HTML-ENTITIES', 'UTF-8'));
    $xpath = new DOMXPath($dom);

    $rows = $xpath->query("//table[contains(@class, 'wikitable')]//tr");
    internal_debug_log("Suche nach: $name in $street. Tabellenzeilen: " . $rows->length, $debugLogFile);

    foreach ($rows as $index => $row) {
        $cells = $row->getElementsByTagName('td');
        if ($cells->length < 3) continue;

        $nameInTable = trim($cells->item(1)->textContent);
        $addressInTable = $cells->item(2)->textContent;

        if (stripos($nameInTable, $name) !== false && stripos($addressInTable, $street) !== false) {
            internal_debug_log("Treffer in Zeile $index: $nameInTable", $debugLogFile);
            
            $linkNode = $xpath->query(".//a[contains(@class, 'mw-file-description')]", $cells->item(0))->item(0);
            if ($linkNode) {
                $rawHref = $linkNode->getAttribute('href');
                
                // FIX: Robuster URL-Zusammenbau (Double-Domain-Prüfung)
                if (strpos($rawHref, 'http') === 0) {
                    $fileUrl = $rawHref;
                } elseif (strpos($rawHref, '//') === 0) {
                    $fileUrl = "https:" . $rawHref;
                } else {
                    $fileUrl = "https://de.wikipedia.org" . (strpos($rawHref, '/') === 0 ? '' : '/') . $rawHref;
                }

                internal_debug_log("Lade Detailseite: $fileUrl", $debugLogFile);
                
                $fileHtml = getHtml($fileUrl);
                if ($fileHtml && preg_match('/data-lat="([^"]+)" data-lon="([^"]+)"/', $fileHtml, $coords)) {
                    internal_debug_log("Koordinaten gefunden: Lat " . $coords[1] . ", Lng " . $coords[2], $debugLogFile);
                    echo json_encode([
                        'success' => true, 
                        'lat' => (float)$coords[1], 
                        'lng' => (float)$coords[2],
                        'source' => $fileUrl
                    ]);
                    internal_debug_log("--- END (Erfolg) ---", $debugLogFile);
                    exit;
                }
            }
        }
    }
} catch (Exception $e) {
    internal_debug_log("Fataler Fehler beim Parsing: " . $e->getMessage(), $debugLogFile);
}

internal_debug_log("Keine passenden Koordinaten gefunden.", $debugLogFile);
echo json_encode(['success' => false]);
internal_debug_log("--- END ---", $debugLogFile);