<?php
declare(strict_types=1);
require_once __DIR__ . '/../../src/bootstrap.php';

if (!Auth::user()) {
    http_response_code(401);
    echo 'Unauthorized';
    exit;
}

try {
    Database::requireTicketsTable();
} catch (RuntimeException $e) {
    http_response_code(503);
    echo 'Tickets unavailable';
    exit;
}

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

$att = TicketAttachmentRepository::getById($id);
if (!$att || ($att['kind'] ?? '') !== 'file') {
    http_response_code(404);
    exit;
}

$path = TicketAttachmentRepository::filePath($att);
if ($path === null) {
    http_response_code(404);
    exit;
}

$name = (string) ($att['original_name'] ?? 'download');
$mime = (string) ($att['mime_type'] ?? 'application/octet-stream');
header('Content-Type: ' . $mime);
header('Content-Length: ' . (string) filesize($path));
header('Content-Disposition: attachment; filename="' . str_replace('"', '', $name) . '"');
header('X-Content-Type-Options: nosniff');
readfile($path);
