<?php
declare(strict_types=1);
require_once __DIR__ . "/../app/db.php";
require_once __DIR__ . "/../app/auth.php";

$pdo = smm_db();
$action = $_GET["action"] ?? "enqueue";

if ($action === "list") {
  $rows = $pdo->query("SELECT id,job_type,run_at,status,attempts,last_error,created_at,updated_at FROM cron_queue ORDER BY id DESC LIMIT 200")->fetchAll(PDO::FETCH_ASSOC);
  smm_json_response(["ok"=>true,"rows"=>$rows]);
}

if ($action === "enqueue") {
  $b = smm_read_json_body();
  $job_type = smm_str($b["job_type"] ?? "");
  $run_at = smm_str($b["run_at"] ?? "");
  $payload_json = json_encode($b["payload"] ?? new stdClass(), JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE);

  if ($job_type===""||$run_at==="") smm_json_response(["ok"=>false,"error"=>"job_type and run_at are required"], 400);

  $now = smm_now_iso();
  $st=$pdo->prepare("INSERT INTO cron_queue (job_type,payload_json,run_at,status,attempts,last_error,created_at,updated_at)
    VALUES (:t,:p,:r,'queued',0,'',:c,:u)");
  $st->execute([":t"=>$job_type,":p"=>$payload_json,":r"=>$run_at,":c"=>$now,":u"=>$now]);
  smm_json_response(["ok"=>true,"id"=>intval($pdo->lastInsertId())]);
}

if ($action === "delete") {
  $b=smm_read_json_body();
  $id=intval($b["id"]??0);
  if($id<=0) smm_json_response(["ok"=>false,"error"=>"id required"],400);
  $st=$pdo->prepare("DELETE FROM cron_queue WHERE id=:id");
  $st->execute([":id"=>$id]);
  smm_json_response(["ok"=>true]);
}

smm_json_response(["ok"=>false,"error"=>"Unknown action"], 400);
