<?php
declare(strict_types=1);
require_once __DIR__ . '/_cron_boot.php';

// Allow CLI usage:
// php -q cron/run.php --job=sync_details --key=XXX --max_seconds=20 --limit=12
if (PHP_SAPI === 'cli') {
  $jobCli = (string)cron_param('job', '');
  if ($jobCli !== '') {
    $_GET['job'] = $jobCli;
  }
}

$job = (string)($_GET['job'] ?? '');
if ($job === '') { http_response_code(400); echo "Missing job"; exit; }

$allowed = [
  'sync_leads' => __DIR__ . '/sync_leads.php',
  'sync_details' => __DIR__ . '/sync_details.php',
  'refresh_statuses' => __DIR__ . '/refresh_statuses.php',
  'watch_tracking' => __DIR__ . '/watch_tracking.php',
  'sync_stock' => __DIR__ . '/sync_stock.php',
  'backfill_full' => __DIR__ . '/backfill_full.php',
  'backfill_full_enabled' => __DIR__ . '/backfill_full_enabled.php',
];

if (!isset($allowed[$job])) { http_response_code(400); echo "Unknown job"; exit; }

try {
  cron_key_ok();
  header('Content-Type: text/plain; charset=utf-8');
  echo "RUN: $job @ " . date('Y-m-d H:i:s') . "\n\n";
  require $allowed[$job];
} catch (Throwable $e) {
  http_response_code(500);
  header('Content-Type: text/plain; charset=utf-8');
  echo "[ERROR] " . $e->getMessage() . "\n";
}
