<?php
declare(strict_types=1);

$config = require __DIR__ . '/app/config.php';
require __DIR__ . '/app/db.php';
require __DIR__ . '/app/auth.php';
require __DIR__ . '/app/upload.php';

require_login($config);

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

$st = $pdo->prepare("SELECT * FROM documents WHERE id=?");
$st->execute([$docId]);
$doc = $st->fetch();
if (!$doc) { http_response_code(404); exit('Not found'); }

$vehicleId = (int)($doc['vehicle_id'] ?? 0);
if ($vehicleId <= 0) { http_response_code(404); exit('File not linked'); }

$path = vehicle_docs_dir($config, $vehicleId) . '/' . $doc['stored_filename'];
if (!is_file($path)) { http_response_code(404); exit('Missing file'); }

header('Content-Type: '.$doc['mime_type']);
header('Content-Length: '.filesize($path));
header('Content-Disposition: attachment; filename="'.rawurlencode($doc['original_filename']).'"');
readfile($path);
exit;
