inline-file.php<?php

require_once __DIR__ . '/../../../config/database.php';
require_once __DIR__ . '/../../../config/helpers.php';
require_once __DIR__ . '/../../../middleware/admin.php';
require_once __DIR__ . '/MailboxRepository.php';

requireAdmin();

if (getMethod() !== 'GET') {
    jsonResponse(false, 'method.not_allowed', null, 405);
}

$route = getApiRouteSegments();
$mailboxId = isset($route[2]) && ctype_digit((string) $route[2]) ? (int) $route[2] : 0;
$messageId = isset($route[4]) && ctype_digit((string) $route[4]) ? (int) $route[4] : 0;
$attachmentId = isset($route[6]) && ctype_digit((string) $route[6]) ? (int) $route[6] : 0;

global $pdo;
$repo = new MailboxRepository($pdo);

$message = $repo->getMessageById($mailboxId, $messageId);
if (!$message) {
    jsonResponse(false, 'mailboxes.message_not_found', null, 404);
}

$attachment = $repo->getAttachmentById($messageId, $attachmentId);
if (!$attachment) {
    jsonResponse(false, 'mailboxes.attachment_not_found', null, 404);
}

$absolute = dirname(__DIR__, 3) . str_replace('/', DIRECTORY_SEPARATOR, (string) $attachment['storage_path']);
if (!is_file($absolute)) {
    jsonResponse(false, 'mailboxes.attachment_not_found', null, 404);
}

header('Content-Type: ' . ($attachment['mime_type'] ?: 'application/octet-stream'));
header('Content-Length: ' . filesize($absolute));
header('Content-Disposition: inline; filename="' . basename((string) ($attachment['original_name'] ?: $attachment['filename'])) . '"');
readfile($absolute);
exit;