<?php
require_once __DIR__ . '/app/bootstrap.php';
$user = require_auth();
$rawAttachmentId = $_GET['id'] ?? null;
$attachmentId = is_scalar($rawAttachmentId)
    ? filter_var($rawAttachmentId, FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]])
    : false;
if ($attachmentId === false) {
    http_response_code(404);
    exit('Prilog nije pronađen.');
}
$attachmentId = (int)$attachmentId;

$stmt = db()->prepare('SELECT a.id AS attachment_id, a.ticket_id, a.original_name, a.stored_name, a.mime_type, a.file_size, a.is_internal,
        t.id, t.user_id, t.assigned_to, t.responsible_role_code
    FROM ticket_attachments a
    JOIN tickets t ON t.id = a.ticket_id
    WHERE a.id = ? LIMIT 1');
$stmt->execute([$attachmentId]);
$attachment = $stmt->fetch();

$canAccessTicket = $attachment && can_view_ticket($attachment, $user);
$canAccessInternal = $attachment && can_manage_ticket($attachment, $user);
if (!$canAccessTicket || (!$canAccessInternal && (int)$attachment['is_internal'] === 1)) {
    if ($attachment) {
        security_log_event('attachment_download_forbidden', [
            'user_id' => (int)$user['id'],
            'attachment_id' => $attachmentId,
            'ticket_id' => (int)$attachment['ticket_id'],
        ]);
    }
    http_response_code(404);
    exit('Prilog nije pronađen ili nemate dozvolu za pristup.');
}

$storedName = (string)$attachment['stored_name'];
$expectedTicketPrefix = 'ticket-' . (int)$attachment['ticket_id'] . '-';
if (!str_starts_with($storedName, $expectedTicketPrefix)
    || !preg_match('/^ticket-[0-9]+-[a-f0-9]{32}\.(jpg|jpeg|png|pdf|xls|xlsx|txt)$/D', $storedName)) {
    security_log_event('attachment_download_invalid_storage_name', [
        'user_id' => (int)$user['id'],
        'attachment_id' => $attachmentId,
        'ticket_id' => (int)$attachment['ticket_id'],
    ]);
    http_response_code(404);
    exit('Prilog nije pronađen.');
}

$uploadRoot = realpath(__DIR__ . '/uploads/tickets');
$path = $uploadRoot !== false ? realpath($uploadRoot . DIRECTORY_SEPARATOR . $storedName) : false;
$allowedPrefix = $uploadRoot !== false ? rtrim($uploadRoot, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR : '';
if ($path === false || $allowedPrefix === '' || !str_starts_with($path, $allowedPrefix) || !is_file($path) || !is_readable($path)) {
    http_response_code(404);
    exit('Prilog nije pronađen.');
}

$downloadName = basename(str_replace('\\', '/', (string)$attachment['original_name']));
$downloadName = str_replace(["\r", "\n", '"', '\\'], '', $downloadName);
$downloadName = trim((string)preg_replace('/[\x00-\x1F\x7F]/', '', $downloadName));
if ($downloadName === '') {
    $downloadName = 'prilog';
}
$asciiName = preg_replace('/[^A-Za-z0-9._-]+/', '_', $downloadName);
if ($asciiName === '' || $asciiName === null) {
    $asciiName = 'attachment';
}

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