<?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);

// ✅ setăm fp cookie (device id)
$fp = ensure_demo_fingerprint_cookie();

// ✅ limitare pe device (cookie)
//rate_limit_demo_by_fp_or_die($fp);

// ✅ (optional) limitare pe IP real (anti-abuz curl fără cookies)
//rate_limit_demo_by_ip_or_die(DEMO_IP_LIMIT_SECONDS);

// 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();

// job demo
$job = [
    'job_id'     => $job_id,
    'mode'       => 'demo',
    'created_at' => gmdate('c'),
    'max_pages'  => DEMO_MAX_PAGES,
    'urls'       => [$url],
    'ip'         => $ip,
    'fp'         => $fp,
];

// scriem in pending
queue_write_pending($job_id, $job);

// scriem lock-ul DEMO pe fp (după ce jobul a fost creat)
write_demo_lock_fp($fp, $job_id);

// răspuns 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,
]);
