<?php
declare(strict_types=1);

require __DIR__ . '/../../config/bootstrap.php';

$db = \App\Core\Database::getInstance();

$jobs = $db->query("SELECT * FROM jobs WHERE status='queued' ORDER BY id ASC LIMIT 20")->fetchAll();
echo "Found ".count($jobs)." queued jobs\n";

foreach ($jobs as $j) {
  $id=(int)$j['id'];
  try {
    $db->prepare("UPDATE jobs SET status='running' WHERE id=:id")->execute([':id'=>$id]);

    $type=(string)$j['job_type'];
    $payload=json_decode((string)($j['payload_json']??'{}'), true) ?: [];

    if ($type==='email_send_queue') {
      // reuse your existing email_queue worker if exists:
      // mark done only here
      // (integration point)
    }

    $db->prepare("UPDATE jobs SET status='done' WHERE id=:id")->execute([':id'=>$id]);
    echo "Job#$id done\n";
  } catch (\Throwable $e) {
    $db->prepare("UPDATE jobs SET status='failed', error_message=:m WHERE id=:id")
       ->execute([':m'=>$e->getMessage(),':id'=>$id]);
    echo "Job#$id failed: ".$e->getMessage()."\n";
  }
}
