<?php
/**
 * fetch_poi_photos.php - Korrigiert für Verzeichnistreue
 */

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

// --- DER TÜRSTEHER ---
enforceValidRequest($debugLogFile);

// Konfiguration laden
$config = require __DIR__ . '/config.php'; 
$dbConfig = require __DIR__ . '/db-connection.php';

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

// Parameter abgreifen (gid oder poi_id)
$gid = isset($_GET['poi_id']) ? (int)$_GET['poi_id'] : (isset($_GET['gid']) ? (int)$_GET['gid'] : 0);

$photoTable = $config['poiPhotoTable']; 
$userTable  = $config['userTable'];
$env        = $config['env']; 

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

    $query = "SELECT 
                p.url, 
                p.upload_by, 
                p.description, 
                p.upload_at, 
                u.username 
              FROM \"$photoTable\" p 
              LEFT JOIN \"$userTable\" u ON p.upload_by = u.uid 
              WHERE p.gid = :gid 
              ORDER BY p.upload_at DESC";
              
    $stmt = $pdo->prepare($query);
    $stmt->execute([':gid' => $gid]);
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // --- PFAD-LOGIK SYNCHRON ZUR INSERT-FUNKTION ---
    $subFolder = ($env === 'test') ? 'test' : 'prod';
    
    // WICHTIG: Nutze relative Pfade für das Frontend, 
    // damit es egal ist, ob du über www. oder direkt zugreifst.
    $baseUrl = "https://www.app.stolperclean.de/webapp/uploads/poi_photos/{$subFolder}/";

    $results = [];
    foreach ($rows as $row) {
        $results[] = [
            // Wir hängen den Dateinamen an die Basis-URL an
            'url'         => $baseUrl . $row['url'],
            'username'    => $row['username'] ?? 'Gast',
            'description' => $row['description'] ?? '',
            'upload_at'   => $row['upload_at']
        ];
    }

    echo json_encode($results);

} catch (Throwable $e) {
    internal_debug_log("Fetch Error: " . $e->getMessage(), $debugLogFile);
    http_response_code(500);
    echo json_encode(["success" => false, "error" => "Datenbankfehler"]);
}