<?php

declare(strict_types=1);

require DENTAL_ROOT . '/app/bootstrap.php';
require_login();
require_documentation_schema();
require_permission('uploads.manage', ['super_admin','clinic_admin']);

$id = (int) ($_GET['id'] ?? 0);
$stmt = db()->prepare('SELECT * FROM `' . table('system_uploads') . '` WHERE id=? LIMIT 1');
$stmt->execute([$id]);
$file = $stmt->fetch();
if (!$file) {
    http_response_code(404);
    exit('File not found.');
}
$path = private_system_upload_directory() . '/' . basename((string) $file['stored_name']);
if (!is_file($path)) {
    http_response_code(404);
    exit('Stored file is missing.');
}
audit('system_file_downloaded', 'system_upload', $id, ['file'=>(string)$file['file_name']]);
header('X-Content-Type-Options: nosniff');
header('Content-Type: ' . (string) $file['mime_type']);
header('Content-Disposition: attachment; filename="' . str_replace('"', '', basename((string) $file['file_name'])) . '"');
header('Content-Length: ' . filesize($path));
readfile($path);
