<?php
// fetch_pois_by_name.php
// Sucht Stolpersteine basierend auf Namensähnlichkeit und Geburtsjahr.
// Nutzt PostgreSQL pg_trgm (similarity) für eine fehlertolerante Suche.

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

$debugLogFile = __DIR__ . '/fetch_pois_by_name_debug.log';
require_once __DIR__ . '/logging_functions.php'; 
require_once __DIR__ . '/validation_functions.php'; 
require_once __DIR__ . '/fetch_poi_select.php';

// 1. DER TÜRSTEHER-CHECK
// Prüft die URL auf ?db=prod|test. Der POST-Body wird hier ignoriert.
enforceValidRequest($debugLogFile);

internal_debug_log("--- START FLEXIBLE SUCHE ---", $debugLogFile);
header('Content-Type: application/json');

try {
    // --- Konfiguration & DB-Verbindung laden ---
    $config = require __DIR__ . '/config.php';
    $dbConfig = require __DIR__ . '/db-connection.php';
    
    // Dynamische Tabellenwahl basierend auf der Config (die vom Türsteher validiert wurde)
    $targetTable = $config['poiTable'] ?? '';

    // ------------------------------------------------------------------
    // === DATENQUELLEN-ZUSAMMENFÜHRUNG (GET + JSON POST) ===
    // ------------------------------------------------------------------
    // Wir nehmen GET (für db) und ergänzen es um den POST-Body (für Suche)
    $data = $_GET;
    $jsonInput = json_decode(file_get_contents('php://input'), true);
    if (is_array($jsonInput)) {
        $data = array_merge($data, $jsonInput);
    }

    // Variablen-Extraktion
    $nameParts = (isset($data['name_parts']) && is_array($data['name_parts'])) ? $data['name_parts'] : [];
    $yearOfBirth = (isset($data['year_of_birth']) && is_numeric($data['year_of_birth'])) ? (int)$data['year_of_birth'] : null;

    if (empty($nameParts)) {
        throw new Exception('Keine Namensteile für die Suche empfangen.');
    }

    // Suchstring für similarity() zusammenbauen
    $searchString = implode(' ', $nameParts);
    if ($yearOfBirth) {
        $searchString .= ' ' . $yearOfBirth;
    }

    // --- Datenbankverbindung ---
    $connStr = "host={$dbConfig['host']} port={$dbConfig['port']} dbname={$dbConfig['dbname']} user={$dbConfig['user']} password={$dbConfig['password']}";
    $dbconn = pg_connect($connStr);
    if (!$dbconn) throw new Exception('DB-Verbindung fehlgeschlagen');
    pg_set_client_encoding($dbconn, "UTF8");

    $poiColumns = getPoiSelectFields();

    // --- SQL-Logik ---
    // Wir vergleichen gegen Vorname+Nachname UND Nachname+Vorname für maximale Trefferquote
    $dbFieldExpr = "first_name || ' ' || last_name || ' ' || last_name || ' ' || first_name";
    if ($yearOfBirth) {
        $dbFieldExpr .= " || ' ' || CAST(year_of_birth AS TEXT)";
    }

    $query = "
        SELECT 
            $poiColumns,    
            ST_X(geom_geolocation) AS lng,
            ST_Y(geom_geolocation) AS lat,
            similarity({$dbFieldExpr}, $1) as rank_score
        FROM public.\"{$targetTable}\" 
        WHERE similarity({$dbFieldExpr}, $1) > 0.25
        ORDER BY rank_score DESC
        LIMIT 15;
    ";
    
    internal_debug_log("Suche in $targetTable nach: $searchString", $debugLogFile);

    $result = pg_query_params($dbconn, $query, [$searchString]);
    if (!$result) throw new Exception(pg_last_error($dbconn));

    $rows = pg_fetch_all($result) ?: [];
    pg_close($dbconn);

    // --- Transformation für das Frontend ---
    $transformedRows = array_map(function($row) { 
        $yob = (int)($row['year_of_birth'] ?? 0);
        $yobText = ($yob > 0) ? " (geb. $yob)" : "";
        
        return [
            'gid'           => $row['gid'],
            'source'        => 'POI',
            'lat'           => (float)$row['lat'],
            'lng'           => (float)$row['lng'],
            'first_name'    => $row['first_name'] ?? '',
            'last_name'     => $row['last_name'] ?? '',
            'year_of_birth' => $yob,
            'display_name'  => "{$row['first_name']} {$row['last_name']}{$yobText}, {$row['street']} {$row['house_no']}",
            'rank_score'    => (float)$row['rank_score'],
            'original_poi'  => $row
        ];
    }, $rows); 

    echo json_encode(['success' => true, 'data' => $transformedRows], JSON_PRETTY_PRINT);

} catch (Exception $e) {
    internal_debug_log("Fehler in fetch_pois_by_name: " . $e->getMessage(), $debugLogFile);
    http_response_code(500); // Oder 400, falls Parameter fehlten
    echo json_encode(['success' => false, 'error' => $e->getMessage()]);
    if (isset($dbconn)) pg_close($dbconn);
}

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