<div class="content-wrapper android-settings-sms">
  <main class="ass-main">
    <header class="ass-heading">
      <div><span>SMS DELIVERY</span><h1>إعدادات SMS</h1><p>إرسال محلي عبر USB أو عبر مزوّد API.</p></div>
      <a href="messages_outbox.php"><i class="fa fa-paper-plane"></i><b>الإرسال</b></a>
    </header>

    <nav class="ass-nav">
      <a 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 class="is-active" href="settings_sms.php"><i class="fa fa-comment"></i><span>SMS</span></a>
    </nav>

    <?php if ($msg): ?><div class="ass-notice is-ok"><?= h($msg) ?></div><?php endif; ?>
    <?php if ($err): ?><div class="ass-notice is-error"><?= h($err) ?></div><?php endif; ?>

    <form class="ass-form" method="post" id="androidSmsSettings" data-ua-android-native-layout>
      <?php if (function_exists('ua_csrf_field')) ua_csrf_field(); ?>

      <section class="ass-card">
        <div class="ass-title"><i class="fa fa-random"></i><div><span>Provider</span><h2>طريقة الإرسال</h2></div></div>
        <label class="ass-switch"><input type="checkbox" name="enabled" value="1" <?= $cfg['enabled']==='1'?'checked':'' ?>><span><b>تفعيل SMS</b><small>الرسائل تبقى في الطابور عند التعطيل.</small></span></label>
        <div class="ass-provider-options">
          <label><input type="radio" name="mode" value="local" <?= $cfg['mode']==='local'?'checked':'' ?>><i class="fa fa-usb"></i><span><b>محلي USB</b><small>مودم GSM عبر Gammu</small></span></label>
          <label><input type="radio" name="mode" value="api" <?= $cfg['mode']==='api'?'checked':'' ?>><i class="fa fa-cloud"></i><span><b>SMS API</b><small>مزوّد رسائل عبر HTTP</small></span></label>
        </div>
      </section>

      <section class="ass-card" data-mode-panel="local">
        <div class="ass-title"><i class="fa fa-usb"></i><div><span>Gammu</span><h2>المودم المحلي</h2></div></div>
        <div class="ass-grid">
          <label><span>المنفذ</span><input id="androidSmsLocalPort" name="local_port" value="<?= h($cfg['local_port']) ?>" dir="ltr" placeholder="COM5" list="androidSmsDetectedPorts" autocomplete="off"><small>اكتشاف تلقائي مع إمكانية كتابة COM يدوياً.</small></label>
          <datalist id="androidSmsDetectedPorts"></datalist>
          <label><span>الاتصال</span><select name="local_connection"><option value="at" <?= $cfg['local_connection']==='at'?'selected':'' ?>>AT</option><option value="at115200" <?= $cfg['local_connection']==='at115200'?'selected':'' ?>>AT 115200</option><option value="at19200" <?= $cfg['local_connection']==='at19200'?'selected':'' ?>>AT 19200</option></select></label>
        </div>
        <div class="ass-grid">
          <label><span>مهلة الإرسال</span><input type="number" min="15" max="180" name="local_timeout" value="<?= (int)$cfg['local_timeout'] ?>"></label>
          <label><span>أقصى أجزاء</span><input type="number" min="1" max="255" name="local_autolen" value="<?= (int)$cfg['local_autolen'] ?>"></label>
        </div>
        <button class="ass-secondary" type="button" id="androidSmsDetectModem"><i class="fa fa-search"></i> اكتشاف منفذ المودم تلقائياً</button>
        <p id="androidSmsDetectionStatus" class="ass-detection-status" role="status" aria-live="polite">سيبدأ الاكتشاف تلقائياً.</p>
        <button class="ass-secondary" name="action" value="check_local"><i class="fa fa-plug"></i> فحص المودم دون إرسال</button>
        <?php if (is_array($localCheck) && !empty($localCheck['details'])): ?><pre dir="ltr"><?= h(json_encode($localCheck['details'],JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES|JSON_PRETTY_PRINT)) ?></pre><?php endif; ?>
      </section>

      <section class="ass-card" data-mode-panel="api">
        <div class="ass-title"><i class="fa fa-cloud"></i><div><span>HTTP API</span><h2>مزوّد الرسائل</h2></div></div>
        <label><span>API URL</span><input name="api_url" value="<?= h($cfg['api_url']) ?>" dir="ltr" placeholder="https://provider.example.com/send"></label>
        <div class="ass-grid">
          <label><span>Method</span><select name="method"><option value="POST" <?= $cfg['method']==='POST'?'selected':'' ?>>POST</option><option value="GET" <?= $cfg['method']==='GET'?'selected':'' ?>>GET</option></select></label>
          <label><span>Body</span><select name="body_type"><option value="json" <?= $cfg['body_type']==='json'?'selected':'' ?>>JSON</option><option value="form" <?= $cfg['body_type']==='form'?'selected':'' ?>>Form</option></select></label>
        </div>
        <div class="ass-grid">
          <label><span>المصادقة</span><select name="auth_type" id="androidSmsAuth"><option value="bearer" <?= $cfg['auth_type']==='bearer'?'selected':'' ?>>Bearer</option><option value="basic" <?= $cfg['auth_type']==='basic'?'selected':'' ?>>Basic</option><option value="param" <?= $cfg['auth_type']==='param'?'selected':'' ?>>API Key</option><option value="none" <?= $cfg['auth_type']==='none'?'selected':'' ?>>بدون</option></select></label>
          <label><span>Timeout</span><input type="number" min="5" max="60" name="timeout" value="<?= (int)$cfg['timeout'] ?>"></label>
        </div>
        <label data-auth-panel="bearer"><span>Bearer Token</span><input type="password" name="token" value="<?= h($cfg['token']) ?>" dir="ltr"></label>
        <div class="ass-grid" data-auth-panel="basic"><label><span>Username</span><input name="username" value="<?= h($cfg['username']) ?>" dir="ltr"></label><label><span>Password</span><input type="password" name="password" value="<?= h($cfg['password']) ?>" dir="ltr"></label></div>
        <div class="ass-grid" data-auth-panel="param"><label><span>Key Name</span><input name="api_key_name" value="<?= h($cfg['api_key_name']) ?>" dir="ltr"></label><label><span>Key Value</span><input type="password" name="api_key_value" value="<?= h($cfg['api_key_value']) ?>" dir="ltr"></label></div>
        <details class="ass-details">
          <summary><span><i class="fa fa-sliders"></i><b>خيارات API المتقدمة</b></span><i class="fa fa-angle-down"></i></summary>
          <div>
            <div class="ass-grid"><label><span>Phone field</span><input name="p_to" value="<?= h($cfg['param_map']['to']) ?>" dir="ltr"></label><label><span>Text field</span><input name="p_text" value="<?= h($cfg['param_map']['text']) ?>" dir="ltr"></label></div>
            <div class="ass-grid"><label><span>Sender field</span><input name="p_sender" value="<?= h($cfg['param_map']['sender']) ?>" dir="ltr"></label><label><span>Sender ID</span><input name="sender_id" value="<?= h($cfg['sender_id']) ?>" dir="ltr"></label></div>
            <label><span>كود الدولة</span><input name="default_country_code" value="<?= h($cfg['default_country_code']) ?>" dir="ltr"></label>
            <label class="ass-switch"><input type="checkbox" name="api_international_numbers" value="1" <?= $cfg['api_international_numbers']==='1'?'checked':'' ?>><span><b>تحويل الأرقام إلى دولية</b><small>خاص بإرسال API.</small></span></label>
            <label><span>Extra Params JSON</span><textarea name="extra_params" dir="ltr"><?= h($cfg['extra_params']) ?></textarea></label>
          </div>
        </details>
      </section>

      <section class="ass-card ass-test">
        <div class="ass-title"><i class="fa fa-paper-plane"></i><div><span>Test</span><h2>اختبار فعلي</h2></div></div>
        <label><span>رقم الاختبار</span><input name="test_to" value="<?= h($_POST['test_to']??$cfg['test_phone']) ?>" dir="ltr" inputmode="tel"></label>
        <label><span>نص الرسالة</span><input name="test_text" value="<?= h($_POST['test_text']??'') ?>"></label>
        <button class="ass-test-send" name="action" value="test_sms" onclick="return confirm('سيتم إرسال SMS. متابعة؟');"><i class="fa fa-paper-plane"></i> إرسال الاختبار</button>
        <?php if (is_array($testResult)): ?><pre dir="ltr"><?= h(json_encode($testResult,JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES|JSON_PRETTY_PRINT)) ?></pre><?php endif; ?>
      </section>

      <section class="ass-card">
        <div class="ass-title"><i class="fa fa-check-square-o"></i><div><span>Queue Control</span><h2>اختبار الطابور والموافقة</h2></div></div>
        <label><span>رقم الاختبار المحفوظ</span><input name="test_phone" value="<?= h($cfg['test_phone']) ?>" dir="ltr" inputmode="tel"></label>
        <label class="ass-switch"><input type="checkbox" name="queue_confirmation_required" value="1" <?= $cfg['queue_confirmation_required']==='1'?'checked':'' ?>><span><b>طلب تأكيد متابعة الطابور</b><small>يتوقف بعد رسالة الاختبار حتى الموافقة.</small></span></label>
      </section>

      <button class="ass-save" name="action" value="save"><i class="fa fa-save"></i> حفظ إعدادات SMS</button>
    </form>
  </main>
</div>
<script>
(function(){
  const form=document.getElementById('androidSmsSettings');
  if(!form)return;
  const modes=[...form.querySelectorAll('input[name="mode"]')],panels=[...form.querySelectorAll('[data-mode-panel]')],auth=form.querySelector('#androidSmsAuth'),authPanels=[...form.querySelectorAll('[data-auth-panel]')];
  const modemPort=form.querySelector('#androidSmsLocalPort'),modemPorts=form.querySelector('#androidSmsDetectedPorts'),detectButton=form.querySelector('#androidSmsDetectModem'),detectStatus=form.querySelector('#androidSmsDetectionStatus');
  let detecting=false;
  function syncMode(){const value=modes.find(x=>x.checked)?.value||'local';panels.forEach(x=>x.hidden=x.dataset.modePanel!==value);}
  function syncAuth(){const value=auth?.value||'none';authPanels.forEach(x=>x.hidden=x.dataset.authPanel!==value);}
  async function detectModem(){if(!modemPort||detecting)return;detecting=true;if(detectButton)detectButton.disabled=true;if(detectStatus)detectStatus.textContent='جارٍ اكتشاف منافذ COM والتحقق من المودم…';try{const response=await fetch('api/sms_modem_detect.php',{headers:{'Accept':'application/json','X-Requested-With':'XMLHttpRequest'},cache:'no-store'}),data=await response.json(),ports=Array.isArray(data.ports)?data.ports:[];if(modemPorts)modemPorts.replaceChildren(...ports.map(device=>{const option=document.createElement('option');option.value=String(device.port||'');option.label=String(device.name||device.port||'');return option;}));if(data.verified&&data.port){modemPort.value=String(data.port).toUpperCase();const connection=form.querySelector('select[name="local_connection"]');if(connection&&data.connection)connection.value=data.connection;}if(detectStatus)detectStatus.textContent=data.message||'انتهى فحص المنافذ.';}catch(error){if(detectStatus)detectStatus.textContent='تعذر الاكتشاف التلقائي. يمكنك إدخال COM يدوياً.';}finally{detecting=false;if(detectButton)detectButton.disabled=false;}}
  modes.forEach(x=>x.addEventListener('change',syncMode));auth?.addEventListener('change',syncAuth);detectButton?.addEventListener('click',detectModem);syncMode();syncAuth();detectModem();
})();
</script>
