<?php
// api/status.php
declare(strict_types=1);

require __DIR__ . '/config.php';

cors_headers();
ensure_dirs();

if (($_SERVER['REQUEST_METHOD'] ?? '') === 'OPTIONS') respond(['ok'=>true]);
if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'GET') 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)) {
    respond(['ok'=>false,'error'=>'Invalid job id'],400);
}

// =====================================================
// CAUTAM JOBUL IN ORDINE LOGICA: pending -> running -> done
// =====================================================

$pending = QUEUE_DIR . '/pending/' . $job_id . '.json';
$running = QUEUE_DIR . '/running/' . $job_id . '.json';
$xlsx    = OUTPUT_DIR . '/xlsx/' . $job_id . '.xlsx';

// ---------- DONE ----------
if (file_exists($xlsx)) {
    respond([
        'ok' => true,
        'job_id' => $job_id,
        'status' => 'done',
        'ready' => true,
        'download' => true
    ]);
}

// ---------- RUNNING ----------
if (file_exists($running)) {
    respond([
        'ok' => true,
        'job_id' => $job_id,
        'status' => 'running'
    ]);
}

// ---------- PENDING ----------
if (file_exists($pending)) {
    respond([
        'ok' => true,
        'job_id' => $job_id,
        'status' => 'pending'
    ]);
}

// ---------- NOT FOUND ----------
respond([
    'ok' => false,
    'job_id' => $job_id,
    'status' => 'missing',
    'error' => 'Job not found'
],404);
