<?php
// api/download.php (NO COOKIE / NO FP)
declare(strict_types=1);

require __DIR__ . '/config.php';

cors_headers();
ensure_dirs();

$method = $_SERVER['REQUEST_METHOD'] ?? '';

if ($method === 'OPTIONS') {
    respond(['ok' => true]);
}
if ($method !== 'GET' && $method !== 'HEAD') {
    respond(['ok' => false, 'error' => 'Method not allowed'], 405);
}

$job = trim((string)($_GET['job'] ?? ''));
if ($job === '' || !preg_match('~^[a-f0-9]{24,64}$~i', $job)) {
    respond(['ok' => false, 'error' => 'Invalid job'], 400);
}

// cale către xlsx (în config.php ai WORKER_BASE / OUTPUTS_DIR)
$xlsxDir = defined('OUTPUTS_DIR') ? (OUTPUTS_DIR . '/xlsx') : (WORKER_BASE . '/outputs/xlsx');
$xlsx = $xlsxDir . '/' . $job . '.xlsx';

if (!is_file($xlsx)) {
    respond(['ok' => false, 'error' => 'File not found'], 404);
}

$download_name = $job . '.xlsx';

header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment; filename="' . $download_name . '"');
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
header('Pragma: no-cache');

$size = @filesize($xlsx);
if ($size !== false) {
    header('Content-Length: ' . $size);
}

// la HEAD trimitem doar headere
if ($method === 'HEAD') {
    exit;
}

@readfile($xlsx);
exit;
