<?php
// api/download.php
declare(strict_types=1);

require __DIR__ . '/config.php';

cors_headers();
ensure_dirs();

$method = $_SERVER['REQUEST_METHOD'] ?? '';

// ✅ Preflight
if ($method === 'OPTIONS') {
    respond(['ok' => true]);
}

// ✅ Acceptăm GET + HEAD (curl -I = HEAD)
if (!in_array($method, ['GET', 'HEAD'], true)) {
    respond(['ok' => false, 'error' => 'Method not allowed'], 405);
}

$job_id = trim((string)($_GET['job'] ?? ''));
if ($job_id === '' || !preg_match('~^[a-f0-9]{24}$~i', $job_id)) {
    // acceptăm și job ids "test" pentru debug
    if (!preg_match('~^[a-zA-Z0-9_\-]{3,64}$~', $job_id)) {
        respond(['ok' => false, 'error' => 'Invalid job id'], 400);
    }
}

// implicit: xlsx = <job_id>.xlsx
$xlsx = OUTPUTS_DIR . '/xlsx/' . $job_id . '.xlsx';

// Permitem download doar dacă jobul este done (sau fișierul există)
$found = find_job_state($job_id);
$state = $found['state'];
$path  = $found['path'];

if ($state !== 'done' && !file_exists($xlsx)) {
    respond(['ok' => false, 'error' => 'Not ready'], 425);
}

// Dacă jobul e done, încercăm să citim done json ca să aflăm numele real al xlsx (dacă există)
if ($state === 'done' && $path && file_exists($path)) {
    $raw = @file_get_contents($path);
    if ($raw !== false) {
        $data = json_decode($raw, true);
        if (is_array($data)) {
            $hint = (string)($data['xlsx'] ?? $data['xlsx_file'] ?? $data['output_file'] ?? '');
            // acceptăm doar nume de fișier simplu
            if ($hint !== '' && preg_match('~^[a-zA-Z0-9_\-\.]+\.xlsx$~', $hint)) {
                $candidate = OUTPUTS_DIR . '/xlsx/' . $hint;
                if (file_exists($candidate)) $xlsx = $candidate;
            }
        }
    }
}

if (!file_exists($xlsx)) {
    respond(['ok' => false, 'error' => 'File not found'], 404);
}

// nume friendly la download
$download_name = 'Audit-SEO-eTimpulSEO-' . $job_id . '.xlsx';

header('X-Content-Type-Options: nosniff');
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);

// ✅ IMPORTANT: la HEAD trimitem doar headere, fără conținut
if ($method === 'HEAD') {
    exit;
}

@readfile($xlsx);
exit;
