<?php
declare(strict_types=1);
require __DIR__ . '/../lib/helpers.php';
$app = require __DIR__ . '/../config/app.php';
$db  = require __DIR__ . '/../config/db.php';

$id = (int)($_GET['id'] ?? 0);
if ($id <= 0) { http_response_code(400); exit('Bad request'); }

$stmt = $db->prepare("SELECT filename, filepath FROM documents WHERE id = :id LIMIT 1");
$stmt->execute([':id' => $id]);
$row = $stmt->fetch();
if (!$row) { http_response_code(404); exit('Not found'); }

$abs = rtrim($app['storage_dir'],'/') . '/' . ltrim($row['filepath'],'/');
if (!is_file($abs)) { http_response_code(404); exit('File missing'); }

$mime = (new finfo(FILEINFO_MIME_TYPE))->file($abs) ?: 'application/octet-stream';
header('Content-Type: ' . $mime);
header('Content-Length: ' . filesize($abs));
header('Content-Disposition: inline; filename="" . rawurlencode($row['filename']) . ""');
header('X-Content-Type-Options: nosniff');
readfile($abs);
