<?php
declare(strict_types=1);

require_once __DIR__ . '/bootstrap_public.php';

$pdo = getPDO();

$id = (int)($_GET['id'] ?? 0);
if ($id <= 0) { http_response_code(404); exit('Not found'); }

$st = $pdo->prepare("
    SELECT id, stored_path, original_name, mime_type, is_shareable
    FROM beneficiary_documents
    WHERE id=?
    LIMIT 1
");
$st->execute([$id]);
$doc = $st->fetch(PDO::FETCH_ASSOC);

if (!$doc || (int)$doc['is_shareable'] !== 1) {
    http_response_code(403);
    exit('Forbidden');
}

// stored_path is relative to /htdocs/zaka/documents/
$documentsRoot = realpath(__DIR__ . '/../../documents');
if (!$documentsRoot) { http_response_code(500); exit('Server error'); }

$rel = (string)$doc['stored_path'];
$abs = $documentsRoot . '/' . ltrim(str_replace('\\','/',$rel), '/');
$real = realpath($abs);

if (!$real || !is_file($real) || strpos($real, $documentsRoot) !== 0) {
    http_response_code(404);
    exit('File missing');
}

$mime = (string)($doc['mime_type'] ?? 'application/octet-stream');
$downloadName = (string)($doc['original_name'] ?? ('file_' . $id));

header('Content-Type: ' . $mime);
header('Content-Length: ' . filesize($real));
header('Content-Disposition: inline; filename="' . str_replace('"', '', $downloadName) . '"');

readfile($real);
exit;