<?php
// api/submit_demo.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'] ?? '') !== 'POST') respond(['ok' => false, 'error' => 'Method not allowed'], 405);

// 1) limitare DEMO 24h (fingerprint: cookie + UA + lang)
rate_limit_demo_or_die();

// 2) parse JSON
$raw = file_get_contents('php://input') ?: '';
$payload = json_decode($raw, true);

if (!is_array($payload)) respond(['ok' => false, 'error' => 'Invalid JSON'], 400);

$url = (string)($payload['url'] ?? '');
$url = normalize_url($url);

if ($url === '' || !is_valid_url($url)) {
    respond(['ok' => false, 'error' => 'Invalid or missing url'], 400);
}

$job_id = make_job_id();
$ip = get_client_ip();

// 3) job demo (max 50 pagini)
$job = [
    'job_id'     => $job_id,
    'mode'       => 'demo',
    'created_at' => gmdate('c'),
    'max_pages'  => DEMO_MAX_PAGES,
    'urls'       => [$url],
    'ip'         => $ip,
];

// 4) scriem in pending
queue_write_pending($job_id, $job);

// 5) scriem lock-ul DEMO (dupa ce jobul a fost creat)
write_demo_lock($job_id);

// 6) raspuns pentru UI
respond([
    'ok'          => true,
    'job_id'      => $job_id,
    'status_url'  => '/api/status.php?job=' . $job_id,
    'download_url'=> '/api/download.php?job=' . $job_id,
]);
