<?php
require_once __DIR__ . '/../app/bootstrap.php';

use App\Core\Auth;
use App\Core\Database;

Auth::requireLogin('public/login.php');
$mediaId = max(0, (int)($_GET['id'] ?? 0));
$media = $mediaId ? Database::safeFetchOne('SELECT * FROM media_files WHERE id=? LIMIT 1', [$mediaId]) : null;
if (!$media || (string)($media['disk'] ?? '') !== 'private') {
    http_response_code(404);
    exit('File not found.');
}

$role = (string)Auth::role();
$authorized = in_array($role, ['admin', 'staff'], true) || (int)($media['uploaded_by'] ?? 0) === (int)Auth::id();
if (!$authorized) {
    http_response_code(403);
    exit('Access denied.');
}

$relative = str_replace(['..', '\\'], '', (string)$media['file_path']);
$path = ROOT_PATH . '/storage/private_uploads/' . ltrim($relative, '/');
$realBase = realpath(ROOT_PATH . '/storage/private_uploads');
$realPath = realpath($path);
if (!$realBase || !$realPath || !str_starts_with($realPath, $realBase . DIRECTORY_SEPARATOR) || !is_file($realPath)) {
    http_response_code(404);
    exit('File not found.');
}

$downloadName = preg_replace('/[^a-zA-Z0-9._-]+/', '-', (string)($media['file_name'] ?? 'document.pdf')) ?: 'document.pdf';
header('Content-Type: ' . ((string)($media['mime_type'] ?? '') ?: 'application/octet-stream'));
header('Content-Length: ' . filesize($realPath));
header('Content-Disposition: attachment; filename="' . $downloadName . '"');
header('Cache-Control: private, no-store, max-age=0');
header('X-Content-Type-Options: nosniff');
readfile($realPath);
exit;
