<?php
@ini_set('display_errors','0');
@ini_set('log_errors','1');
error_reporting(E_ALL);
require_once __DIR__ . '/api_common.php';
require_once __DIR__ . '/../auth.php';
require_once __DIR__ . '/../security.php';
require_once __DIR__ . '/../db_bootstrap.php';
require_once __DIR__ . '/../messages_lib.php';

require_login();
$conn = ensure_db(true);
if(function_exists('require_perm')) { require_perm('can_manage_messages'); }
if (function_exists('ua_csrf_verify') && !ua_csrf_verify()) {
  out(['ok'=>false,'error'=>'انتهت صلاحية الطلب. أعد تحميل الصفحة وحاول مجدداً.'], 419);
}

$action = strtolower(trim((string)($_POST['action'] ?? 'start')));
$runId = (int)($_POST['run_id'] ?? 0);
$campaignId = (int)($_POST['campaign_id'] ?? 0);
$actorId = (int)($_SESSION['admin_id'] ?? ($_SESSION['admin_user_id'] ?? 0));

if ($action === 'start') {
  $res = messages_queue_create_run($conn, $actorId, null, $campaignId > 0 ? $campaignId : null);
} elseif ($action === 'approve' || $action === 'cancel') {
  $res = messages_queue_control_run($conn, $runId, $action);
} elseif ($action === 'step') {
  $limit = (int)($_POST['limit'] ?? 2);
  $res = messages_queue_process_step($conn, $runId, $limit);
} else {
  $res = ['ok'=>false,'error'=>'إجراء طابور الرسائل غير معروف.'];
  out($res, 400);
}

out($res);
