<?php
// fetch_pois.php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

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

// 1. DER TÜRSTEHER-CHECK
// WICHTIG: Der Türsteher prüft jetzt nur noch 'db' in der URL. 
// start_id und end_id liegen sicher im POST-Body.
enforceValidRequest($debugLogFile);

// 2. KONFIGURATION LADEN
$config = require_once __DIR__ . '/config.php'; 
require_once __DIR__ . '/fetch_poi_select.php';

// ------------------------------------------------------------------
// === DATENAUFNAHME (Hybrid: URL + JSON POST) ===
// ------------------------------------------------------------------
$data = $_GET; // Enthält db
$jsonInput = json_decode(file_get_contents('php://input'), true);
if (is_array($jsonInput)) {
    $data = array_merge($data, $jsonInput);
}

// Parameter für SQL vorbereiten
$startId = isset($data['start_id']) ? (int)$data['start_id'] : 0;
$endId   = isset($data['end_id'])   ? (int)$data['end_id']   : 0;
$limit   = $endId - $startId;
$offset  = $startId;

if ($limit <= 0) {
    header('Content-Type: application/json');
    echo json_encode(['type' => 'FeatureCollection', 'features' => []]);
    exit;
}

$targetTable = $config['poiTable']; 

// ------------------------------------------------------------------
// === DATENBANKVERBINDUNG (PDO) ===
// ------------------------------------------------------------------
$db = require __DIR__ . '/db-connection.php';

try {
    $pdo = new PDO(
        "pgsql:host={$db['host']};port={$db['port']};dbname={$db['dbname']}",
        $db['user'],
        $db['password'],
        [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]
    );

    $poiColumns = getPoiSelectFields();
    
    // PostGIS Query für GeoJSON Export
$geoJsonQuery = "
    SELECT json_build_object(
        'type', 'FeatureCollection',
        'features', COALESCE(
            json_agg(
                json_build_object(
                    'type', 'Feature',
                    'geometry', ST_AsGeoJSON(ST_Transform(geom_geolocation, 4326), 9)::json,
                    'properties', to_jsonb(t.*) - 'geom_geolocation'
                )
            ), '[]'::json
        )
    )
    FROM (
        SELECT $poiColumns, geom_geolocation
        FROM public.{$targetTable}
        -- Sicherstellen, dass wir nur Zeilen mit Geometrie nehmen
        WHERE geom_geolocation IS NOT NULL
        ORDER BY gid ASC 
        LIMIT :limit OFFSET :offset
    ) AS t
";

    $stmt = $pdo->prepare($geoJsonQuery);
    $stmt->bindValue(':limit', $limit, PDO::PARAM_INT);
    $stmt->bindValue(':offset', $offset, PDO::PARAM_INT);
    $stmt->execute();
    
    $result = $stmt->fetch(PDO::FETCH_ASSOC);
    $jsonResultString = $result['json_build_object'] ?? null;

    internal_debug_log("Erfolg: $limit Datensätze geladen.", $debugLogFile);

    header('Content-Type: application/json');
    echo $jsonResultString ?: json_encode(['type' => 'FeatureCollection', 'features' => []]);

} catch (PDOException $e) {
    internal_debug_log("Fehler: " . $e->getMessage(), $debugLogFile);
    http_response_code(500);
    echo json_encode(["error" => "Serverfehler"]);
}