<?php
declare(strict_types=1);

require_once __DIR__ . '/app.php';

app_boot();
$jobId = trim((string)($_GET['id'] ?? ''));
$job = $jobId !== '' ? find_job($jobId) : null;

if (!$job || ($job['status'] ?? '') !== 'completed' || !job_output_exists($job)) {
    http_response_code(404);
    header('Content-Type: text/plain; charset=utf-8');
    echo 'File not found.';
    exit;
}

$downloadName = preg_replace('/[^A-Za-z0-9._-]/', '-', job_download_name($job)) ?: 'converted-file.' . job_target_format($job);
$filePath = (string) $job['output_path'];
$contentLength = filesize($filePath);
$mime = job_output_mime($job);

header('Content-Type: ' . $mime);
if ($contentLength !== false) {
    header('Content-Length: ' . $contentLength);
}
header('Content-Disposition: attachment; filename="' . $downloadName . '"');
header('X-Content-Type-Options: nosniff');
readfile($filePath);
exit;
