<?php
declare(strict_types=1);

require_once $_SERVER['DOCUMENT_ROOT'] . '/includes/session_bootstrap.php';
require_once $_SERVER['DOCUMENT_ROOT'] . '/includes/file_api_client.php';
require_once $_SERVER['DOCUMENT_ROOT'] . '/includes/user_avatar.php';

if (empty($_SESSION['logged_in'])) {
    http_response_code(403);
    header('Content-Type: text/plain; charset=UTF-8');
    echo 'Brak dostepu.';
    exit();
}

$storedName = trim((string)($_GET['f'] ?? ''));
$requestedByFile = $storedName !== '';
$userId = isset($_GET['u']) ? (int)$_GET['u'] : 0;

if ($storedName === '' && $userId > 0) {
    $pdo = og_session_get_pdo();
    if ($pdo instanceof PDO) {
        $storedName = (string)(og_get_user_avatar_file($pdo, $userId) ?? '');
    }
}

if ($storedName === '' || !preg_match('/^[A-Za-z0-9._-]{1,255}$/', $storedName)) {
    http_response_code(404);
    header('Content-Type: text/plain; charset=UTF-8');
    echo 'Zdjecie nie zostalo znalezione.';
    exit();
}

try {
    if ($requestedByFile) {
        // Nazwa pliku jest unikalna (UUID), więc można bezpiecznie cache'ować dłużej.
        header('Cache-Control: private, max-age=31536000, immutable');
    } else {
        // URL po userId może zmienić wskazywany plik po aktualizacji avatara.
        header('Cache-Control: private, max-age=300, stale-while-revalidate=60');
    }
    get_file_api_client()->proxyFile('user_files/profile', $storedName, true);
} catch (Throwable $e) {
    http_response_code(404);
    header('Content-Type: text/plain; charset=UTF-8');
    echo 'Zdjecie nie zostalo znalezione.';
}

exit();
