<?php
@ini_set('display_errors','0');
error_reporting(E_ALL & ~E_WARNING & ~E_NOTICE);
if (session_status() === PHP_SESSION_NONE) session_start();
header('Content-Type: application/json; charset=utf-8');
require_once __DIR__ . '/../helpers.php';
require_once __DIR__ . '/../auth.php';
require_once __DIR__ . '/../db_bootstrap.php';
require_once __DIR__ . '/../super_admin_guard.php';
require_once __DIR__ . '/../subscribers_queue_lib.php';

function outq(array $a,int $code=200){ http_response_code($code); echo json_encode($a,JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES); exit; }
require_login('index.php?login=1');
if (function_exists('require_perm')) @require_perm('can_manage_subscribers');
if (!function_exists('super_admin_ok') || !super_admin_ok('api/subscribers_queue_enqueue.php')) outq(['ok'=>false,'message'=>'انتهت جلسة الحماية أو لم يتم التحقق من كلمة مرور السوبر أدمن.'],403);
$conn=ensure_db(true);
try{
  $action=strtolower(trim((string)($_POST['action']??'')));
  $ids=$_POST['ids']??[];
  $ids=array_values(array_unique(array_filter(array_map('intval',(array)$ids),fn($v)=>$v>0)));
  if(!$ids || !in_array($action,['cut','restore','cancel','open_speed'],true)) outq(['ok'=>false,'message'=>'طلب غير صالح'],400);
  sq_ensure_schema($conn);
  // Do not block enqueue if router is temporarily offline; worker will report it. But give early warning status.
  $routerStatus = function_exists('mt_router_online_status') ? mt_router_online_status($conn, 2) : ['ok'=>true,'message'=>'ok'];
  $jobId=sq_enqueue_job($conn,$action,$ids,sq_request_user());
  sq_log('enqueue job='.$jobId.' action='.$action.' total='.count($ids));
  outq(['ok'=>true,'job_id'=>$jobId,'message'=>'تم إنشاء مهمة '.sq_action_label($action).' لعدد '.count($ids).' مشترك. سيتم التنفيذ عبر العامل الآمن.','router'=>$routerStatus]);
}catch(Throwable $e){ sq_log('enqueue failed: '.$e->getMessage()); outq(['ok'=>false,'message'=>$e->getMessage()],500); }
