<?php
/**
 * API-Endpunkt zum Abrufen der Verifikationsdokumente eines Benutzers
 * Für Admin-Dashboard
 */

session_start();
require_once '../../config/database.php';

// Check if user is logged in as admin
if (!isset($_SESSION['admin_logged_in']) || !$_SESSION['admin_logged_in']) {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'Nicht autorisiert']);
    exit;
}

$user_id = $_GET['user_id'] ?? null;

if (!$user_id) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Benutzer-ID erforderlich']);
    exit;
}

try {
    $db = new Database();
    $conn = $db->getConnection();
    
    // Get user documents with review information
    $stmt = $conn->prepare("
        SELECT 
            vd.id,
            vd.user_id,
            vd.document_type,
            vd.file_name,
            vd.file_path,
            vd.file_size,
            vd.mime_type,
            vd.upload_date,
            vd.status,
            vd.reviewed_by,
            vd.reviewed_at,
            vd.admin_notes,
            au.username as reviewed_by_name
        FROM verification_documents vd
        LEFT JOIN admin_users au ON vd.reviewed_by = au.id
        WHERE vd.user_id = ?
        ORDER BY vd.upload_date DESC
    ");
    
    $stmt->execute([$user_id]);
    $documents = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Convert file paths to relative URLs for web access
    foreach ($documents as &$doc) {
        // Convert absolute path to relative path
        if (strpos($doc['file_path'], 'C:\\xampp\\htdocs\\boxenstop\\uploads\\verification_documents\\') === 0) {
            // Extract just the filename for relative path
            $doc['file_path'] = 'uploads/verification_documents/' . basename($doc['file_path']);
        } else {
            // Keep as is if already relative
            $doc['file_path'] = str_replace('\\', '/', $doc['file_path']);
        }
    }
    
    echo json_encode([
        'success' => true,
        'documents' => $documents,
        'count' => count($documents)
    ]);
    
} catch (Exception $e) {
    error_log('Error fetching user documents: ' . $e->getMessage());
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => 'Fehler beim Laden der Dokumente: ' . $e->getMessage()
    ]);
}
?>
