<?php
require_once __DIR__ . '/../lib/auth.php';
require_login();

$id = (int) ($_GET['id'] ?? 0);
if ($id <= 0) { http_response_code(400); echo 'Ungültige Anfrage.'; exit; }

$stmt = db()->prepare('SELECT * FROM dokumente WHERE id = ?');
$stmt->execute([$id]);
$doc = $stmt->fetch();

if (!$doc) { http_response_code(404); echo 'Dokument nicht gefunden.'; exit; }

$user = current_user();
if ((int) $doc['user_id'] !== (int) $user['id'] && !is_admin()) {
    http_response_code(403);
    echo 'Keine Berechtigung.';
    exit;
}

$path = dirname(__DIR__) . '/uploads/' . $doc['filename'];
if (!is_file($path)) { http_response_code(404); echo 'Datei nicht gefunden.'; exit; }

$display         = $doc['original_name'];
$safe_display    = addslashes($display);
$safe_encoded    = rawurlencode($display);

header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . $safe_display . '"; filename*=UTF-8\'\'' . $safe_encoded);
header('Content-Length: ' . filesize($path));
header('X-Content-Type-Options: nosniff');
header('Cache-Control: private, no-store');
readfile($path);
exit;
