<?php
/**
 * insert-upload-poi-photo.php - Korrigiert für Session-Sicherheit
 */

$debugLogFile = __DIR__ . '/insert-upload-poi-photo-debug.log';
require_once __DIR__ . '/logging_functions.php';
require_once __DIR__ . '/validation_functions.php';

// --- NEU: SESSION STARTEN ---
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

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

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

try {
    $config = require __DIR__ . '/config.php';
    $env = $config['env']; 
    $photoTable = $config['poiPhotoTable']; 
    
    $dbConfig = require __DIR__ . '/db-connection.php';
    
    $dsn = "pgsql:host={$dbConfig['host']};port={$dbConfig['port']};dbname={$dbConfig['dbname']}";
    $pdo = new PDO($dsn, $dbConfig['user'], $dbConfig['password']);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    // Parameter aus dem POST-Body
    $gid = $_POST['gid'] ?? null;
    $description = $_POST['description'] ?? '';
    $file = $_FILES['photo'] ?? null;

    // --- KORREKTUR: UID AUS DER SESSION STATT AUS POST ---
    // Wenn keine Session-UID da ist, Fallback auf Gast (1)
    $uid = isset($_SESSION['uid']) ? (int)$_SESSION['uid'] : 1; 

    if (!$gid || !$file) {
        throw new Exception("Daten unvollständig: GID oder Foto fehlt.");
    }

    $now = date('Y-m-d H:i:s');
    $timestamp = date('YmdHis');
    
    // Dateiname generieren
    $customUrl = $gid . "_" . $timestamp . ".jpg";
    
    $subFolder = ($env === 'test') ? 'test' : 'prod';
    $targetDir = __DIR__ . '/../uploads/poi_photos/' . $subFolder . '/';
    $targetPath = $targetDir . $customUrl;

    $pdo->beginTransaction();

    // SQL mit sicherem Tabellennamen
    $sql = "INSERT INTO \"$photoTable\" (url, gid, upload_by, description, upload_at) 
            VALUES (?, ?, ?, ?, ?)";
    
    $stmt = $pdo->prepare($sql);
    $stmt->execute([
        $customUrl, 
        $gid, 
        $uid, // Verwendet jetzt die sichere $uid aus der Session
        $description, 
        $now
    ]);

    if (!is_dir($targetDir)) {
        mkdir($targetDir, 0777, true);
    }

    if (!move_uploaded_file($file['tmp_name'], $targetPath)) {
        throw new Exception("Upload-Fehler: Datei konnte nicht verschoben werden.");
    }

    $pdo->commit();

    echo json_encode(['success' => true, 'url' => $customUrl]);

} catch (Throwable $e) {
    if (isset($pdo) && $pdo->inTransaction()) $pdo->rollBack();
    if (isset($targetPath) && file_exists($targetPath)) unlink($targetPath);

    internal_debug_log("Upload Error: " . $e->getMessage(), $debugLogFile);
    http_response_code(500);
    echo json_encode(['success' => false, 'error' => $e->getMessage()]);
}