<?php
ob_start();
require_once dirname(__DIR__) . '/auth.php';
require_once dirname(__DIR__) . '/helpers.php';
require_once dirname(__DIR__) . '/agent_edit_request_lib.php';
if (ob_get_length()) ob_clean();
header('Content-Type: application/json; charset=utf-8');
require_login();
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  if (function_exists('require_perm')) require_perm('can_edit_subscriber');
} elseif (function_exists('require_any_perm')) {
  require_any_perm(['can_edit_subscriber', 'can_view_subscribers']);
} elseif (function_exists('require_perm')) {
  require_perm('can_view_subscribers');
}
$conn = ensure_db(true);
ua_agent_edit_request_ensure_schema($conn);

function aer_reply(array $data, int $status = 200): void {
  http_response_code($status);
  echo json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
  exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  if (!ua_csrf_verify()) aer_reply(['ok'=>false,'message'=>'انتهت صلاحية الطلب. أعد تحميل الصفحة.'], 419);
  $id = (int)($_POST['request_id'] ?? 0);
  $decision = strtoupper(trim((string)($_POST['decision'] ?? '')));
  $adminId = (int)($_SESSION['admin_id'] ?? $_SESSION['admin_user_id'] ?? $_SESSION['user_id'] ?? 0);
  $result = ua_agent_edit_request_decide($conn, $id, $decision, $adminId);
  if (empty($result['ok'])) aer_reply(['ok'=>false,'message'=>$result['error'] ?? 'تعذر تنفيذ القرار.'], 422);
  aer_reply(['ok'=>true,'message'=>$decision === 'APPROVED' ? 'تمت الموافقة ومنح صلاحية التعديل لمدة 30 دقيقة.' : 'تم رفض طلب التعديل.']);
}

$rows = [];
$rs = @$conn->query("SELECT r.id,r.agent_id,r.subscriber_id,r.request_scope,r.request_note,r.created_at,
  COALESCE(NULLIF(a.full_name,''),a.name) agent_name,
  COALESCE(NULLIF(s.full_name,''),TRIM(CONCAT_WS(' ',s.first_name,s.father_name,s.last_name))) subscriber_name
  FROM agent_subscriber_edit_requests r
  JOIN agents a ON a.id=r.agent_id
  LEFT JOIN subscribers s ON s.id=r.subscriber_id
  WHERE r.status='PENDING'
  ORDER BY r.id DESC LIMIT 20");
if ($rs) while ($row = $rs->fetch_assoc()) $rows[] = $row;
aer_reply([
  'ok'=>true,
  'count'=>count($rows),
  'requests'=>$rows,
  'can_decide'=>function_exists('has_perm') ? has_perm('can_edit_subscriber') : true,
  'csrf'=>function_exists('ua_csrf_token') ? ua_csrf_token() : ($_SESSION['csrf_token'] ?? ''),
]);
