<?php
// api/download.php
declare(strict_types=1);

require __DIR__ . '/config.php';

ensure_dirs();

$job_id = trim((string)($_GET['job'] ?? ''));
if ($job_id === '' || !preg_match('~^[a-f0-9]{24}$~i', $job_id)) {
    http_response_code(400);
    echo 'Invalid job id';
    exit;
}

$file = OUTPUT_DIR . '/xlsx/' . $job_id . '.xlsx';

if (!file_exists($file)) {
    http_response_code(404);
    echo 'File not ready';
    exit;
}

$size = filesize($file);
$filename = 'audit_seo_full_' . $job_id . '.xlsx';

header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment; filename="'.$filename.'"');
header('Content-Length: '.$size);
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Pragma: no-cache');

readfile($file);
exit;
