<div class="content-wrapper android-messages-outbox"><main class="amo-main">
  <header class="amo-heading"><div><span>Message Queue</span><h1>صندوق الإرسال</h1><p>متابعة الرسائل المجدولة وحالة الإرسال والمحاولات.</p></div><a href="messages_templates.php"><i class="fa fa-envelope"></i><b>القوالب</b></a></header>
  <nav class="amo-nav"><a class="is-active" href="messages_outbox.php"><i class="fa fa-paper-plane"></i><span>الإرسال</span></a><a href="messages_templates.php"><i class="fa fa-file-text"></i><span>القوالب</span></a><a href="settings_whatsapp.php"><i class="fa fa-whatsapp"></i><span>WhatsApp</span></a><a href="settings_sms.php"><i class="fa fa-comment"></i><span>SMS</span></a></nav>
  <section class="amo-actions"><form method="get" data-ua-android-native-layout><select name="status" onchange="this.form.submit()"><option value="">كل الحالات</option><?php foreach($allowed as $outboxStatus): ?><option value="<?= h($outboxStatus) ?>" <?= $status===$outboxStatus?'selected':'' ?>><?= h($outboxStatusLabels[$outboxStatus] ?? $outboxStatus) ?></option><?php endforeach; ?></select></form><button type="button" id="androidRunMessageQueue"><i class="fa fa-play"></i><span>تشغيل الإرسال</span></button></section>
  <div id="androidMessageRunResult" class="amo-result" hidden></div>
  <section class="amo-stats">
    <button data-detail-type="missing_phone"><i class="fa fa-phone"></i><b><?= (int)$messageStats['missing_phone'] ?></b><span>دون هاتف</span></button>
    <button data-detail-type="sent"><i class="fa fa-check"></i><b><?= (int)$messageStats['sent'] ?></b><span>المرسل</span></button>
    <button data-detail-type="failed"><i class="fa fa-exclamation-triangle"></i><b><?= (int)$messageStats['failed'] ?></b><span>الفشل</span></button>
  </section>
  <section class="amo-progress" id="androidQueueProgress" <?= $activeMessageRunPublic ? '' : 'hidden' ?>><header><b id="androidQueueLabel">حالة الطابور</b><strong id="androidQueuePercent">0%</strong></header><div><i id="androidQueueBar"></i></div><footer><span>الكل <b id="androidQueueTotal">0</b></span><span>أُرسل <b id="androidQueueSent">0</b></span><span>فشل <b id="androidQueueFailed">0</b></span></footer></section>
  <section class="amo-card"><div class="amo-title"><div><span>Outbox Messages</span><h2>الرسائل</h2></div><b><?= count($androidOutboxRows) ?></b></div><div class="amo-list">
    <?php if(!$androidOutboxRows): ?><p class="amo-empty">لا توجد رسائل ضمن الحالة المحددة.</p><?php else: foreach($androidOutboxRows as $messageRow): $messageStatus=(string)$messageRow['status']; ?>
    <article class="is-<?= strtolower(h($messageStatus)) ?>"><header><div><span>#<?= (int)$messageRow['id'] ?> · <?= h($messageRow['channel']) ?></span><b dir="ltr"><?= h($messageRow['to_phone']) ?></b></div><strong><?= h($outboxStatusLabels[$messageStatus] ?? $messageStatus) ?></strong></header><div class="amo-meta"><span><small>القالب</small><b><?= h($messageRow['template_key']?:'—') ?></b></span><span><small>المحاولات</small><b><?= (int)$messageRow['try_count'] ?></b></span></div><?php if(!empty($messageRow['last_error'])): ?><details><summary><i class="fa fa-exclamation-triangle"></i> آخر خطأ</summary><p><?= h($messageRow['last_error']) ?></p></details><?php endif; ?><footer><span><i class="fa fa-clock-o"></i><b dir="ltr"><?= h($messageRow['created_at']) ?></b></span><?php if(!empty($messageRow['sent_at'])): ?><span><i class="fa fa-check"></i><b dir="ltr"><?= h($messageRow['sent_at']) ?></b></span><?php endif; ?></footer></article>
    <?php endforeach; endif; ?>
  </div></section>
</main></div>
<div class="amo-modal" id="androidQueueModal" hidden><div class="amo-modal__box"><h3 id="androidQueueModalTitle">تأكيد متابعة الطابور</h3><p id="androidQueueModalText"></p><div id="androidQueueModalList"></div><footer><button id="androidQueueApprove">متابعة الإرسال</button><button id="androidQueueClose">إغلاق</button></footer></div></div>
<script>
(function(){
  const button=document.getElementById('androidRunMessageQueue'),result=document.getElementById('androidMessageRunResult'),progress=document.getElementById('androidQueueProgress'),modal=document.getElementById('androidQueueModal');
  let run=<?= json_encode($activeMessageRunPublic,JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES) ?>,pumping=false;
  const csrf=<?= json_encode(function_exists('ua_csrf_token') ? ua_csrf_token() : '',JSON_UNESCAPED_SLASHES) ?>;
  const esc=v=>String(v??'').replace(/[&<>"']/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]));
  async function post(action,id=0){const body=new URLSearchParams({action,ua_csrf:csrf});if(id)body.set('run_id',id);if(action==='step')body.set('limit','2');return (await fetch('api/message_queue_run.php',{method:'POST',body,credentials:'same-origin'})).json();}
  function render(value){run=value||null;if(!run){progress.hidden=true;return;}progress.hidden=false;const labels={WAITING_CONFIRMATION:'بانتظار الموافقة',RUNNING:'جارٍ الإرسال',COMPLETED:'اكتمل الطابور',TEST_FAILED:'فشل الاختبار',CANCELLED:'أُلغي الطابور'};document.getElementById('androidQueueLabel').textContent=labels[run.status]||'فحص الطابور';document.getElementById('androidQueuePercent').textContent=(run.percent||0)+'%';document.getElementById('androidQueueBar').style.width=(run.percent||0)+'%';document.getElementById('androidQueueTotal').textContent=run.total||0;document.getElementById('androidQueueSent').textContent=run.sent||0;document.getElementById('androidQueueFailed').textContent=run.failed||0;}
  function approval(){const failed=run?.status==='TEST_FAILED';document.getElementById('androidQueueModalTitle').textContent=failed?'فشل إرسال رسالة الاختبار':'تم إرسال رسالة الاختبار';document.getElementById('androidQueueModalText').textContent=failed?(run.test_error||'تحقق من إعدادات SMS وأعد المحاولة.'):`راجع الرسالة على ${run.test_phone} ثم وافق على متابعة ${run.total} رسالة.`;document.getElementById('androidQueueModalList').innerHTML='';document.getElementById('androidQueueApprove').hidden=failed;document.getElementById('androidQueueClose').textContent=failed?'إلغاء وإعادة الرسائل للطابور':'إغلاق';modal.hidden=false;}
  async function pump(){if(pumping||run?.status!=='RUNNING')return;pumping=true;try{const data=await post('step',run.id);if(!data.ok)throw new Error(data.error);render(data.run);if(run.status==='RUNNING')setTimeout(()=>{pumping=false;pump()},400);else{pumping=false;result.hidden=false;result.className='amo-result is-ok';result.textContent=`اكتمل الإرسال: ${run.sent}، فشل: ${run.failed}`;setTimeout(()=>location.reload(),1000);}}catch(error){pumping=false;result.hidden=false;result.className='amo-result is-error';result.textContent=error.message;}}
  button?.addEventListener('click',async()=>{button.disabled=true;result.hidden=false;result.className='amo-result';result.textContent='جارٍ إرسال رسالة الاختبار…';try{const data=await post('start');render(data.run);result.className='amo-result '+(data.ok?'is-ok':'is-error');result.textContent=data.message||data.error||'';if(run?.status==='WAITING_CONFIRMATION'||run?.status==='TEST_FAILED')approval();if(data.ok&&run.status==='RUNNING')pump();}catch(error){result.className='amo-result is-error';result.textContent=error.message;}finally{button.disabled=false;}});
  document.getElementById('androidQueueApprove')?.addEventListener('click',async()=>{const data=await post('approve',run.id);if(data.ok){modal.hidden=true;render(data.run);pump();}});
  document.getElementById('androidQueueClose')?.addEventListener('click',async()=>{if(run?.status==='TEST_FAILED'){const data=await post('cancel',run.id);if(data.ok)render(data.run);}modal.hidden=true;});
  document.querySelectorAll('[data-detail-type]').forEach(item=>item.addEventListener('click',async()=>{const type=item.dataset.detailType,titles={missing_phone:'المشتركون دون هاتف',sent:'الرسائل المرسلة',failed:'الرسائل الفاشلة'};document.getElementById('androidQueueModalTitle').textContent=titles[type];document.getElementById('androidQueueModalText').textContent='';document.getElementById('androidQueueApprove').hidden=true;const list=document.getElementById('androidQueueModalList');list.innerHTML='<p>جارٍ التحميل…</p>';modal.hidden=false;try{const data=await(await fetch(`api/message_queue_details.php?type=${type}`,{credentials:'same-origin'})).json();list.innerHTML=data.rows?.length?data.rows.map(row=>`<article><b>${esc(row.subscriber_name||row.to_phone||'—')}</b><small>${esc(row.subscriber_username||row.to_phone||'—')}</small></article>`).join(''):'<p>لا توجد بيانات.</p>';}catch(e){list.innerHTML=`<p>${esc(e.message)}</p>`;}}));
  render(run);if(run?.status==='WAITING_CONFIRMATION'||run?.status==='TEST_FAILED')approval();if(run?.status==='RUNNING')pump();
})();
</script>
