<?php
// auth-export.php - Spezialmodul für den DSGVO-Datenauszug
// Wird von auth.php via require_once eingebunden.

if (!isset($pdo) || !isset($currentUid)) {
    http_response_code(403);
    echo json_encode(['success' => false, 'error' => 'Direkter Zugriff verboten.']);
    exit;
}

try {
    // 1. Passwort aus den übergebenen Daten ziehen
    $pass = $data['password'] ?? '';

    // 2. User-Basisdaten holen (UID kommt aus der Session via auth.php)
    $stmt = $pdo->prepare("SELECT username, created_at, password_hash FROM public.\"{$config['userTable']}\" WHERE uid = ? AND status = 0");
    $stmt->execute([$currentUid]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);

    // 3. Passwort-Validierung (Sicherheits-Check vor Daten-Freigabe)
    if (!$user || !password_verify($pass, $user['password_hash'])) {
        http_response_code(401);
        echo json_encode(['success' => false, 'error' => 'Passwort inkorrekt.', 'uid' => $currentUid]);
        exit;
    }

    // 4. Aktivitäten (Logs) aus der Datenbank sammeln
    $stmtLog = $pdo->prepare("
        SELECT l.action_code, l.changed_at, p.first_name, p.last_name, p.street, p.house_no
        FROM public.\"{$config['logTable']}\" l
        LEFT JOIN public.\"{$config['poiTable']}\" p ON l.poi_gid = p.gid
        WHERE l.uid = ? 
        ORDER BY l.changed_at DESC
    ");
    $stmtLog->execute([$currentUid]);
    $logs = $stmtLog->fetchAll(PDO::FETCH_ASSOC);

    // 5. Fotos aus der Datenbank sammeln
    $stmtPhotos = $pdo->prepare("
        SELECT ph.url AS filename, ph.upload_at AS created_at, ph.description, poi.first_name, poi.last_name, poi.street, poi.house_no
        FROM public.\"{$config['poiPhotoTable']}\" ph
        LEFT JOIN public.\"{$config['poiTable']}\" poi ON ph.gid = poi.gid
        WHERE ph.upload_by = ?
        ORDER BY ph.upload_at DESC
    ");
    $stmtPhotos->execute([$currentUid]);
    $photos = $stmtPhotos->fetchAll(PDO::FETCH_ASSOC);

    // 6. Den Text-Inhalt professionell generieren
    $txt = "DATENAUSZUG GEMÄSS ART. 15 DSGVO\n";
    $txt .= "=================================\n\n";
    $txt .= "Erstellt am:   " . date('d.m.Y H:i:s') . "\n";
    $txt .= "Benutzer:      " . $user['username'] . "\n";
    $txt .= "Registriert:   " . date('d.m.Y', strtotime($user['created_at'])) . "\n\n";

    $txt .= "DEINE AKTIVITÄTEN (LOGS)\n";
    $txt .= "------------------------\n";
    
    if (empty($logs)) {
        $txt .= "Keine Aktivitäten gefunden.\n";
    } else {
        foreach ($logs as $log) {
            $date = date('d.m.Y H:i', strtotime($log['changed_at']));
            
            // Mapping der Action-Codes
            $statusText = "Aktion " . $log['action_code'];
            if ((int)$log['action_code'] === 1) $statusText = "glänzend";
            elseif ((int)$log['action_code'] === 2) $statusText = "stumpf";
            elseif ((int)$log['action_code'] === 3) $statusText = "Patenschaft";
            
            $poiName = trim(($log['first_name'] ?? '') . " " . ($log['last_name'] ?? ''));
            $address = trim(($log['street'] ?? '') . " " . ($log['house_no'] ?? ''));
            
            // Formatierung in Spalten für bessere Lesbarkeit
            $txt .= sprintf("[%s] %-12s | Name: %-25s | %s\n", 
                $date, 
                $statusText, 
                ($poiName ?: 'Unbekannter POI'), 
                $address
            );
        }
    }

    $txt .= "\nDEINE HOCHGELADENEN FOTOS\n";
    $txt .= "-------------------------\n";
    
    if (empty($photos)) {
        $txt .= "Keine Fotos gefunden.\n";
    } else {
        foreach ($photos as $photo) {
            $date = date('d.m.Y H:i', strtotime($photo['created_at']));
            $poiName = trim(($photo['first_name'] ?? '') . " " . ($photo['last_name'] ?? ''));
            $address = trim(($photo['street'] ?? '') . " " . ($photo['house_no'] ?? ''));
            $desc = $photo['description'] ? " | Info: " . $photo['description'] : "";
            
            $txt .= sprintf("[%s] Datei: %-25s | Name: %-20s | %s%s\n", 
                $date, 
                basename($photo['filename']), 
                $poiName, 
                $address,
                $desc
            );
        }
    }

    $txt .= "\n\n--- Ende des Datenauszugs ---\n";

    // 7. DAS FINALE: Buffer leeren und JSON senden
    while (ob_get_level() > 0) ob_end_clean();
    
    header('Content-Type: application/json');
    echo json_encode([
        'success'    => true,
        'uid'        => $currentUid,
        'exportData' => $txt,
        'filename'   => 'meine_daten_' . $user['username'] . '_' . date('Y-m-d') . '.txt'
    ]);

} catch (Exception $e) {
    // Fehler ins Debug-Log schreiben
    file_put_contents($debugLogFile, "[" . date('Y-m-d H:i:s') . "] EXPORT-FATAL: " . $e->getMessage() . "\n", FILE_APPEND);
    http_response_code(500);
    echo json_encode(['success' => false, 'error' => 'Interner Export-Fehler']);
}
exit;