<?php
$page_title = 'صندوق الإرسال';
$UA_FORCE_DESIGN_V2 = true;
$uaAndroidMessagesOutbox = ((string)($_GET['ua_android'] ?? '') === '1')
  || stripos((string)($_SERVER['HTTP_USER_AGENT'] ?? ''), 'NetworkCustomersAndroid/') !== false;
$UA_PAGE_CSS = [$uaAndroidMessagesOutbox ? 'assets/css/android_messages_outbox.css' : 'assets/css/messages_outbox.css'];
require_once __DIR__ . '/auth.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');
ensure_message_queue_tables($conn);
$messageStats = messages_queue_statistics($conn);
$activeMessageRun = messages_queue_active_run($conn, true);
$activeMessageRunPublic = messages_queue_run_public($activeMessageRun);

require_once __DIR__ . '/header.php';
require_once __DIR__ . '/sidebar.php';
$active_tab = 'outbox';
if (!$uaAndroidMessagesOutbox) {
  include __DIR__ . '/messages_tabs.php';
  echo '<div class="content-wrapper ua-manual-page"><section class="content"><div class="container-fluid"><div class="ua-msg-page">';
}

$status = trim((string)($_GET['status'] ?? ''));
$allowed = ['QUEUED','PAUSED','RETRY','SENDING','SENT','FAILED'];
$outboxStatusLabels = [
  'QUEUED'=>'في الطابور',
  'PAUSED'=>'موقوفة',
  'RETRY'=>'إعادة محاولة',
  'SENDING'=>'قيد الإرسال',
  'SENT'=>'مرسلة',
  'FAILED'=>'فشل الإرسال',
];
$where = '';
if ($status !== '' && in_array($status, $allowed, true)) {
  $st = $conn->real_escape_string($status);
  $where = "WHERE status='$st'";
}

$rs = $conn->query("SELECT * FROM message_outbox $where ORDER BY id DESC LIMIT 200");
if ($uaAndroidMessagesOutbox) {
  $androidOutboxRows = $rs ? $rs->fetch_all(MYSQLI_ASSOC) : [];
  require __DIR__ . '/android_messages_outbox.php';
  require_once __DIR__ . '/footer.php';
  return;
}
?>

<div class="ua-card ua-clean-card-pad">
  <div class="ua-u-toolbar-between">
    <div>
      <h2 class="ua-u-title-gap6">صندوق الإرسال</h2>
    </div>

    <div class="ua-u-flex-wrap-center">
      <select id="st" class="ua-input ua-u-minw-160">
        <option value="">كل الحالات</option>
        <?php foreach($allowed as $a): ?>
          <option value="<?= h($a) ?>" <?= $status===$a?'selected':'' ?>><?= h($outboxStatusLabels[$a] ?? $a) ?></option>
        <?php endforeach; ?>
      </select>
      <button class="ua-btn" id="btnRun" type="button">تشغيل الإرسال الآن</button>
    </div>
  </div>

  <div class="ua-u-mt-10" id="runResult"></div>

  <section class="mo-stats" aria-label="إحصاءات الرسائل">
    <button type="button" class="mo-stat is-missing" data-detail-type="missing_phone">
      <i class="fa fa-phone"></i><span><b><?= (int)$messageStats['missing_phone'] ?></b><small>مشترك دون رقم هاتف</small></span>
    </button>
    <button type="button" class="mo-stat is-sent" data-detail-type="sent">
      <i class="fa fa-check"></i><span><b><?= (int)$messageStats['sent'] ?></b><small>رسالة مرسلة</small></span>
    </button>
    <button type="button" class="mo-stat is-failed" data-detail-type="failed">
      <i class="fa fa-exclamation-triangle"></i><span><b><?= (int)$messageStats['failed'] ?></b><small>رسالة فاشلة</small></span>
    </button>
  </section>

  <section class="mo-run-progress" id="messageRunProgress" <?= $activeMessageRunPublic ? '' : 'hidden' ?>>
    <div class="mo-run-progress__head">
      <span><i class="fa fa-paper-plane"></i><b id="messageRunLabel">حالة طابور الإرسال</b></span>
      <strong id="messageRunPercent">0%</strong>
    </div>
    <div class="mo-run-progress__bar"><i id="messageRunBar"></i></div>
    <div class="mo-run-progress__numbers">
      <span>الطابور <b id="messageRunTotal">0</b></span>
      <span>المرسل <b id="messageRunSent">0</b></span>
      <span>الفشل <b id="messageRunFailed">0</b></span>
    </div>
  </section>

  <div class="ua-u-table-scroll mt-ua-table-scroll">
    <table class="ua-table ua-u-table-wide-1100">
      <thead>
        <tr>
          <th>ID</th>
          <th>الحالة</th>
          <th>القناة</th>
          <th>الهاتف</th>
          <th>القالب</th>
          <th>محاولات</th>
          <th>آخر خطأ</th>
          <th>تاريخ الإنشاء</th>
          <th>تاريخ الإرسال</th>
        </tr>
      </thead>
      <tbody>
      <?php if($rs && $rs->num_rows): while($r = $rs->fetch_assoc()): ?>
        <tr>
          <td><?= (int)$r['id'] ?></td>
          <td><b><?= h($outboxStatusLabels[$r['status']] ?? $r['status']) ?></b></td>
          <td><?= htmlspecialchars($r['channel']) ?></td>
          <td dir="ltr"><?= htmlspecialchars($r['to_phone']) ?></td>
          <td><?= htmlspecialchars($r['template_key'] ?? '') ?></td>
          <td><?= (int)$r['try_count'] ?></td>
          <td class="ua-u-ellipsis-320">
            <?= htmlspecialchars((string)($r['last_error'] ?? '')) ?>
          </td>
          <td><?= htmlspecialchars($r['created_at']) ?></td>
          <td><?= htmlspecialchars((string)($r['sent_at'] ?? '')) ?></td>
        </tr>
      <?php endwhile; else: ?>
        <tr><td class="ua-u-empty-center" colspan="9">لا توجد رسائل</td></tr>
      <?php endif; ?>
      </tbody>
    </table>
  </div>
</div>

<div class="mo-modal" id="messageApprovalModal" hidden>
  <div class="mo-modal__backdrop"></div>
  <section class="mo-modal__dialog" role="dialog" aria-modal="true" aria-labelledby="messageApprovalTitle">
    <i class="mo-modal__hero fa fa-mobile"></i>
    <h3 id="messageApprovalTitle">تم إرسال رسالة الاختبار</h3>
    <p id="messageApprovalText">راجع الرسالة ومضمونها على رقم الاختبار، ثم وافق على متابعة الطابور.</p>
    <div class="mo-modal__actions">
      <button type="button" class="is-primary" id="approveMessageRun"><i class="fa fa-check"></i> متابعة الإرسال</button>
      <button type="button" id="cancelMessageRun"><i class="fa fa-times"></i> إلغاء الطابور</button>
    </div>
  </section>
</div>

<div class="mo-modal" id="messageDetailsModal" hidden>
  <div class="mo-modal__backdrop" data-close-details></div>
  <section class="mo-modal__dialog mo-modal__dialog--wide" role="dialog" aria-modal="true" aria-labelledby="messageDetailsTitle" dir="rtl">
    <header><div><span>MESSAGE DETAILS</span><h3 id="messageDetailsTitle">تفاصيل الرسائل</h3></div><button type="button" data-close-details aria-label="إغلاق"><i class="fa fa-times"></i></button></header>
    <div class="mo-detail-list" id="messageDetailsList"></div>
  </section>
</div>

<script>
(function(){
  const st = document.getElementById('st');
  st.addEventListener('change', ()=>{
    const v = st.value;
    const url = new URL(window.location.href);
    if(v) url.searchParams.set('status', v); else url.searchParams.delete('status');
    window.location.href = url.toString();
  });

  const btn = document.getElementById('btnRun');
  const out = document.getElementById('runResult');
  const progress = document.getElementById('messageRunProgress');
  const approvalModal = document.getElementById('messageApprovalModal');
  const detailsModal = document.getElementById('messageDetailsModal');
  document.body.append(approvalModal, detailsModal);
  let currentRun = <?= json_encode($activeMessageRunPublic, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES) ?>;
  let pumping = false;
  const csrf = <?= json_encode(function_exists('ua_csrf_token') ? ua_csrf_token() : '', JSON_UNESCAPED_SLASHES) ?>;

  const esc = value => String(value ?? '').replace(/[&<>"']/g, ch => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[ch]));
  async function postQueue(action, runId = 0){
    const body = new URLSearchParams({action, ua_csrf:csrf});
    if(runId) body.set('run_id', String(runId));
    if(action === 'step') body.set('limit', '2');
    const response = await fetch('api/message_queue_run.php', {method:'POST', body, credentials:'same-origin'});
    return response.json();
  }
  function statusLabel(run){
    if(!run) return 'حالة طابور الإرسال';
    const labels = {
      TESTING:'إرسال رسالة الاختبار',
      WAITING_CONFIRMATION:'بانتظار تأكيد متابعة الطابور',
      RUNNING:'جارٍ إرسال الرسائل',
      COMPLETED:'اكتمل إرسال الطابور',
      TEST_FAILED:'فشل إرسال رسالة الاختبار',
      CANCELLED:'أُلغي طابور الإرسال'
    };
    return labels[run.status] || run.status;
  }
  function renderRun(run){
    currentRun = run || null;
    if(!progress || !run){ if(progress) progress.hidden = true; return; }
    progress.hidden = false;
    document.getElementById('messageRunLabel').textContent = statusLabel(run);
    document.getElementById('messageRunPercent').textContent = `${run.percent || 0}%`;
    document.getElementById('messageRunBar').style.width = `${run.percent || 0}%`;
    document.getElementById('messageRunTotal').textContent = run.total || 0;
    document.getElementById('messageRunSent').textContent = run.sent || 0;
    document.getElementById('messageRunFailed').textContent = run.failed || 0;
    progress.classList.toggle('is-failed', run.status === 'TEST_FAILED');
  }
  function showApproval(run){
    renderRun(run);
    document.getElementById('messageApprovalTitle').textContent = 'تم إرسال رسالة الاختبار';
    document.getElementById('approveMessageRun').hidden = false;
    document.getElementById('cancelMessageRun').innerHTML = '<i class="fa fa-times"></i> إلغاء الطابور';
    document.getElementById('messageApprovalText').textContent =
      `تم إرسال نسخة الاختبار إلى ${run.test_phone}. راجع الرسالة ومضمونها قبل متابعة ${run.total} رسالة في الطابور.`;
    approvalModal.hidden = false;
  }
  function showTestFailure(run, message){
    renderRun(run);
    document.getElementById('messageApprovalTitle').textContent = 'فشل إرسال رسالة الاختبار';
    document.getElementById('messageApprovalText').textContent = message || run.test_error || 'تحقق من إعدادات SMS ثم ألغِ الدورة وأعد تشغيلها.';
    document.getElementById('approveMessageRun').hidden = true;
    document.getElementById('cancelMessageRun').innerHTML = '<i class="fa fa-undo"></i> إلغاء وإعادة الرسائل للطابور';
    approvalModal.hidden = false;
  }
  async function pumpQueue(){
    if(pumping || !currentRun || currentRun.status !== 'RUNNING') return;
    pumping = true;
    try{
      const data = await postQueue('step', currentRun.id);
      if(!data.ok) throw new Error(data.error || 'تعذر متابعة الطابور');
      renderRun(data.run);
      if(data.run?.status === 'RUNNING') setTimeout(()=>{ pumping=false; pumpQueue(); }, 350);
      else {
        pumping=false;
        if(data.run?.status === 'COMPLETED'){
          out.innerHTML = `<div class="ua-alert ua-ok">اكتمل الطابور: أُرسل ${data.run.sent} وفشل ${data.run.failed}.</div>`;
          setTimeout(()=>location.reload(), 1100);
        }
      }
    }catch(error){
      pumping=false;
      out.innerHTML = `<div class="ua-alert ua-bad">${esc(error.message)}</div>`;
    }
  }

  btn.addEventListener('click', async ()=>{
    btn.disabled = true;
    out.innerHTML = '<div class="ua-alert">جارٍ الإرسال...</div>';
    try{
      const j = await postQueue('start');
      if(j.ok){
        renderRun(j.run);
        out.innerHTML = `<div class="ua-alert ua-ok">${esc(j.message || 'تم تجهيز طابور الإرسال.')}</div>`;
        if(j.run?.status === 'WAITING_CONFIRMATION') showApproval(j.run);
        if(j.run?.status === 'RUNNING') pumpQueue();
      } else {
        renderRun(j.run);
        out.innerHTML = `<div class="ua-alert ua-bad">${esc(j.error || j.message || 'فشل تشغيل الطابور')}</div>`;
        if(j.run?.status === 'TEST_FAILED') showTestFailure(j.run, j.error);
      }
    }catch(e){
      out.innerHTML = `<div class="ua-alert ua-bad">${esc(e.message)}</div>`;
    }finally{
      btn.disabled = false;
    }
  });

  document.getElementById('approveMessageRun')?.addEventListener('click', async ()=>{
    if(!currentRun) return;
    const data = await postQueue('approve', currentRun.id);
    if(!data.ok){ out.innerHTML=`<div class="ua-alert ua-bad">${esc(data.error)}</div>`; return; }
    approvalModal.hidden = true;
    renderRun(data.run);
    pumpQueue();
  });
  document.getElementById('cancelMessageRun')?.addEventListener('click', async ()=>{
    if(!currentRun) return;
    const data = await postQueue('cancel', currentRun.id);
    if(data.ok){
      approvalModal.hidden=true;
      renderRun(data.run);
      out.innerHTML='<div class="ua-alert">تم إلغاء الطابور مع إبقاء الرسائل غير المرسلة.</div>';
    }
  });

  const detailTitles = {missing_phone:'المشتركون دون رقم هاتف',sent:'الرسائل المرسلة',failed:'الرسائل الفاشلة'};
  document.querySelectorAll('[data-detail-type]').forEach(button=>button.addEventListener('click', async ()=>{
    const type=button.dataset.detailType;
    const list=document.getElementById('messageDetailsList');
    document.getElementById('messageDetailsTitle').textContent=detailTitles[type] || 'التفاصيل';
    detailsModal.hidden=false;
    list.innerHTML='<div class="mo-detail-empty">جارٍ تحميل التفاصيل…</div>';
    try{
      const response=await fetch(`api/message_queue_details.php?type=${encodeURIComponent(type)}`,{credentials:'same-origin',cache:'no-store'});
      const data=await response.json();
      if(!data.ok) throw new Error(data.error || 'تعذر تحميل التفاصيل');
      if(!data.rows?.length){list.innerHTML='<div class="mo-detail-empty">لا توجد بيانات ضمن هذه الحالة.</div>';return;}
      list.innerHTML=data.rows.map(row=>type==='missing_phone'
        ? `<article><i class="fa fa-user"></i><span><b>${esc(row.subscriber_name)}</b>${row.subscriber_username && row.subscriber_username !== row.subscriber_name ? `<small>${esc(row.subscriber_username)}</small>` : ''}</span><em>#${esc(row.id)}</em></article>`
        : `<article><i class="fa ${type==='sent'?'fa-check':'fa-exclamation-triangle'}"></i><span><b>${esc(row.subscriber_name || row.to_phone || '—')}</b><small dir="ltr">${esc(row.to_phone || '—')} · ${esc(row.template_key || '—')}</small>${row.last_error?`<small class="is-error">${esc(row.last_error)}</small>`:''}</span><em>#${esc(row.id)}</em></article>`
      ).join('');
    }catch(error){list.innerHTML=`<div class="mo-detail-empty is-error">${esc(error.message)}</div>`;}
  }));
  document.querySelectorAll('[data-close-details]').forEach(el=>el.addEventListener('click',()=>detailsModal.hidden=true));

  renderRun(currentRun);
  if(currentRun?.status === 'WAITING_CONFIRMATION') showApproval(currentRun);
  if(currentRun?.status === 'TEST_FAILED') showTestFailure(currentRun, currentRun.test_error);
  if(currentRun?.status === 'RUNNING') pumpQueue();
})();
</script>

</div></div></section></div>
<?php require_once __DIR__ . '/footer.php'; ?>
