<?php
$aamTab = in_array($activeTab,['devices','router-match','device-log'],true) ? $activeTab : 'devices';
$aamEnabled = count(array_filter($devices,static fn($d)=>!empty($d['is_enabled'])));
$aamAccess = count(array_filter($devices,static fn($d)=>(string)($d['device_type']??'access')==='access'));
$aamStations = count($devices)-$aamAccess;
?>
<div class="content-wrapper android-airmax-settings" data-android-airmax-settings>
  <main class="aam-main">
    <header class="aam-heading"><div><span>AirMAX / Mimosa</span><h1>إدارة الأجهزة</h1><p>إضافة الهوائيات وفحص الاتصال ومراجعة المطابقة والسجلات.</p></div><a href="receiver_match_report.php"><i class="fa fa-signal"></i><b>التقرير</b></a></header>
    <div class="aam-stats"><div><strong><?= count($devices) ?></strong><span>الأجهزة</span></div><div class="is-green"><strong><?= $aamEnabled ?></strong><span>مفعّل</span></div><div class="is-cyan"><strong><?= $aamAccess ?></strong><span>Access</span></div><div class="is-gold"><strong><?= $aamStations ?></strong><span>Station</span></div></div>
    <?php if ($msg): ?><div class="aam-message is-<?= h($msgType) ?>"><i class="fa fa-info-circle"></i><span><?= h($msg) ?></span></div><?php endif; ?>
    <nav class="aam-tabs"><a class="<?= $aamTab==='devices'?'is-active':'' ?>" href="?tab=devices"><i class="fa fa-wifi"></i><span>الأجهزة</span></a><a class="<?= $aamTab==='router-match'?'is-active':'' ?>" href="?tab=router-match"><i class="fa fa-random"></i><span>مطابقة الراوتر</span></a><a class="<?= $aamTab==='device-log'?'is-active':'' ?>" href="?tab=device-log"><i class="fa fa-list-alt"></i><span>السجل</span></a></nav>

    <?php if ($aamTab==='devices'): ?>
      <section class="aam-section"><div class="aam-section-head"><div><span>الهوائيات المسجلة</span><h2>قائمة الأجهزة</h2></div><b><?= count($devices) ?></b></div><div class="aam-device-list">
        <?php foreach ($devices as $d): ?><?php $did=(int)$d['id'];$status=(string)($d['probe_status']??'idle');$role=(string)($d['device_type']??'access'); ?>
          <details class="aam-device is-<?= h($status) ?>">
            <summary><span class="aam-device-icon"><i class="fa fa-wifi"></i></span><div><h3><?= h($d['name']??('#'.$did)) ?></h3><p>#<?= $did ?> · <?= h(airmax_device_type_text($role)) ?> · <span dir="ltr"><?= h($d['host']??'') ?></span></p></div><b id="probe-badge-<?= $did ?>"><?= h(airmax_probe_badge_text($status)) ?></b><i class="fa fa-chevron-down aam-device-chevron"></i></summary>
            <form method="post" id="aam-form-<?= $did ?>" data-ua-android-native-layout>
              <input type="hidden" name="id" value="<?= $did ?>"><input type="hidden" name="protocol" value="<?= h($d['protocol']??'https') ?>"><input type="hidden" name="port" value="<?= (int)($d['port']??443) ?>"><input type="hidden" name="sector_id" value="<?= (int)($d['sector_id']??0) ?>"><input type="hidden" name="notes" value="<?= h($d['notes']??'') ?>">
              <label><span>اسم الجهاز</span><input name="name" value="<?= h($d['name']??'') ?>" required></label>
              <div class="aam-pair"><label><span>النوع</span><select name="device_type"><option value="access" <?= $role==='access'?'selected':'' ?>>Access / قطاع</option><option value="station" <?= $role==='station'?'selected':'' ?>>Station / مستقبل</option></select></label><label><span>العنوان</span><input name="host" dir="ltr" value="<?= h($d['host']??'') ?>" required></label></div>
              <div class="aam-pair"><label><span>الشركة</span><select name="preferred_vendor"><?php foreach($vendorOptions as $vk=>$vl): ?><option value="<?= h($vk) ?>" <?= (string)($d['preferred_vendor']??'auto')===$vk?'selected':'' ?>><?= h($vl) ?></option><?php endforeach; ?></select></label><label><span>متصل خلف</span><select name="parent_device_id"><option value="0">متصل مباشرة</option><?php foreach(airmax_parent_select_options($devices,$did) as $pid=>$pl): ?><option value="<?= (int)$pid ?>" <?= (int)($d['parent_device_id']??0)===(int)$pid?'selected':'' ?>><?= h($pl) ?></option><?php endforeach; ?></select></label></div>
              <div class="aam-pair"><label><span>المستخدم</span><input name="username" dir="ltr" value="<?= h($d['username']??'') ?>"></label><label><span>كلمة المرور</span><input type="password" name="password" dir="ltr" value="<?= h($d['password']??'') ?>"></label></div>
              <label class="aam-snmp"><span>SNMP Community</span><input name="snmp_community" dir="ltr" value="<?= h($d['snmp_community']??'public') ?>"></label>
              <div class="aam-pair"><label><span>الترتيب</span><input type="number" name="sort_order" value="<?= (int)($d['sort_order']??0) ?>"></label><label class="aam-enabled"><input type="checkbox" name="is_enabled" value="1" <?= !empty($d['is_enabled'])?'checked':'' ?>><span>الجهاز مفعّل</span></label></div>
              <div class="aam-probe"><div><span id="route-<?= $did ?>"><?= h(($d['detected_route']??'') ?: strtoupper((string)($d['protocol']??'https')).':'.(int)($d['port']??443)) ?></span><strong id="probe-result-<?= $did ?>"><?= h(($d['probe_message']??'') ?: 'بانتظار الفحص') ?></strong></div></div>
              <footer><button name="save_device" value="1" type="submit"><i class="fa fa-save"></i><span>حفظ</span></button><button name="pull_device_log" value="1" type="submit"><i class="fa fa-list-alt"></i><span>قراءة السجل</span></button><button class="aam-probe-btn" data-id="<?= $did ?>" type="button"><i class="fa fa-plug"></i><span>فحص</span></button><button class="is-delete" name="delete_device" value="1" type="submit" onclick="return confirm('حذف الجهاز؟')"><i class="fa fa-trash"></i><span>حذف</span></button></footer>
            </form>
          </details>
        <?php endforeach; ?><?php if(!$devices): ?><div class="aam-empty"><i class="fa fa-wifi"></i><h3>لا توجد أجهزة</h3><p>أضف أول جهاز من النموذج التالي.</p></div><?php endif; ?>
      </div></section>

      <section class="aam-section aam-add"><div class="aam-section-head"><div><span>اتصال جديد</span><h2>إضافة جهاز</h2></div><i class="fa fa-plus-circle"></i></div><form method="post" data-ua-android-native-layout>
        <label><span>اسم الجهاز</span><input name="name" placeholder="اسم الهوائي" required></label><div class="aam-pair"><label><span>النوع</span><select name="device_type"><option value="access">Access / قطاع</option><option value="station">Station / مستقبل</option></select></label><label><span>IP</span><input name="host" dir="ltr" placeholder="10.30.99.x" required></label></div>
        <div class="aam-pair"><label><span>الشركة</span><select name="preferred_vendor"><?php foreach($vendorOptions as $vk=>$vl): ?><option value="<?= h($vk) ?>"><?= h($vl) ?></option><?php endforeach; ?></select></label><label><span>متصل خلف</span><select name="parent_device_id"><option value="0">متصل مباشرة</option><?php foreach(airmax_parent_select_options($devices,0) as $pid=>$pl): ?><option value="<?= (int)$pid ?>"><?= h($pl) ?></option><?php endforeach; ?></select></label></div>
        <div class="aam-pair"><label><span>المستخدم</span><input name="username" dir="ltr"></label><label><span>كلمة المرور</span><input type="password" name="password" dir="ltr"></label></div><label><span>SNMP Community</span><input name="snmp_community" dir="ltr" value="public"></label><input type="hidden" name="protocol" value="https"><input type="hidden" name="port" value="443"><input type="hidden" name="sector_id" value="0"><input type="hidden" name="notes" value=""><input type="hidden" name="sort_order" value="99"><label class="aam-enabled"><input type="checkbox" name="is_enabled" value="1" checked><span>الجهاز مفعّل</span></label><button class="aam-save" name="save_device" value="1" type="submit"><i class="fa fa-plus"></i><span>إضافة الجهاز</span></button>
      </form></section>
    <?php elseif ($aamTab==='router-match'): ?>
      <section class="aam-section"><div class="aam-section-head"><div><span>MikroTik Bridge Host</span><h2>الجلب والمطابقة من الراوتر</h2></div><i class="fa fa-random"></i></div><div class="aam-router-controls"><label><span>الراوتر</span><select id="rxrRouterSelect"><option value="">اختر الراوتر</option><?php foreach($rxrRouters as $rt): ?><option value="<?= (int)($rt['id']??0) ?>"><?= h(($rt['name']??'Router').' - '.($rt['host']??'')) ?></option><?php endforeach; ?></select></label><label><span>المنفذ</span><select id="rxrInterfaceSelect" disabled><option value="">اختر الراوتر أولاً</option></select></label><button id="rxrPortMatchBtn" type="button" disabled><i class="fa fa-download"></i><span>جلب ومطابقة المنفذ</span></button><p id="rxrPortStatus">جاهز.</p><div id="rxrPortSummary" class="aam-match-summary" hidden></div><div id="rxrPortResults" class="aam-match-results" hidden></div></div></section>
      <section class="aam-section"><div class="aam-section-head"><div><span>المصادر المعتمدة</span><h2>منافذ الراوتر المسجلة</h2></div><b><?= count($rxrRouterPortSources) ?></b></div><div class="aam-source-list"><?php foreach($rxrRouterPortSources as $rp): ?><article><span><i class="fa fa-sitemap"></i></span><div><h3><?= h($rp['display_name']??$rp['name']??$rp['interface']??'منفذ') ?></h3><p><?= h(($rp['router_name']??'Router').' · '.($rp['interface']??'')) ?></p></div></article><?php endforeach; ?><?php if(!$rxrRouterPortSources): ?><div class="aam-empty"><i class="fa fa-sitemap"></i><h3>لا توجد منافذ مسجلة</h3><p>اختر راوتراً ومنفذاً لبدء المطابقة.</p></div><?php endif; ?></div></section>
    <?php else: ?>
      <section class="aam-section"><div class="aam-section-head"><div><span>السجل الأصلي</span><h2>قراءة سجل جهاز</h2></div><b><?= count($deviceLogRows) ?></b></div><form method="post" class="aam-log-pull" data-ua-android-native-layout><input type="hidden" name="open_tab" value="device-log"><select name="id"><?php foreach($devices as $dev): ?><option value="<?= (int)$dev['id'] ?>" <?= $selectedDeviceLogId===(int)$dev['id']?'selected':'' ?>><?= h(($dev['name']??('#'.$dev['id'])).' - '.($dev['host']??'')) ?></option><?php endforeach; ?></select><button name="pull_device_log" value="1" type="submit"><i class="fa fa-refresh"></i><span>قراءة وحفظ السجل</span></button></form></section>
      <section class="aam-section"><div class="aam-section-head"><div><span>آخر القراءات</span><h2>سجل الأجهزة</h2></div><a href="device_activity_log.php">السجل الكامل</a></div><div class="aam-log-list"><?php foreach(array_slice($deviceLogRows,0,30) as $lr): ?><?php $st=strtolower((string)($lr['status']??'')); ?><article class="is-<?= h(airmax_device_log_status_class($st)) ?>"><header><div><h3><?= h($lr['device_name']??('#'.$lr['device_id'])) ?></h3><p><?= h(airmax_device_log_action_text((string)($lr['event_key']??''),(string)($lr['event_source']??''),(string)($lr['raw_event']??''))) ?></p></div><b><?= h(airmax_device_log_status_text($st)) ?></b></header><p><?= h(($lr['arabic_summary']??'') ?: ($lr['raw_event']??'')) ?></p><time dir="ltr"><?= h($lr['event_at']??'') ?></time></article><?php endforeach; ?><?php if(!$deviceLogRows): ?><div class="aam-empty"><i class="fa fa-list-alt"></i><h3>لا توجد سجلات</h3><p>اختر جهازاً واقرأ سجله من النموذج أعلاه.</p></div><?php endif; ?></div></section>
    <?php endif; ?>
  </main>
</div>
<script>
(function(){
 const esc=v=>String(v??'').replace(/[&<>"']/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]));
 document.querySelectorAll('.aam-probe-btn').forEach(btn=>btn.addEventListener('click',async function(){const id=this.dataset.id;this.disabled=true;const result=document.getElementById('probe-result-'+id);if(result)result.textContent='جاري فحص الاتصال…';try{const r=await fetch('api/airmax_probe.php?id='+encodeURIComponent(id),{headers:{'X-Requested-With':'XMLHttpRequest'}});const d=await r.json();if(result)result.textContent=d.message||'اكتمل الفحص';if(d.route&&d.route.display){const route=document.getElementById('route-'+id);if(route)route.textContent=d.route.display;}}catch(e){if(result)result.textContent='فشل الاتصال بواجهة الفحص';}finally{this.disabled=false;}}));
 const router=document.getElementById('rxrRouterSelect'),iface=document.getElementById('rxrInterfaceSelect'),match=document.getElementById('rxrPortMatchBtn'),status=document.getElementById('rxrPortStatus'),summary=document.getElementById('rxrPortSummary'),results=document.getElementById('rxrPortResults');
 if(router)router.addEventListener('change',async()=>{iface.innerHTML='<option value="">جاري جلب المنافذ…</option>';iface.disabled=true;match.disabled=true;if(!router.value)return;try{const r=await fetch('api/router_port_interfaces.php?router_id='+encodeURIComponent(router.value),{headers:{'X-Requested-With':'XMLHttpRequest'}});const d=await r.json();if(!d.ok)throw new Error(d.message||'تعذر جلب المنافذ');iface.innerHTML='<option value="">اختر المنفذ</option>'+d.interfaces.map(x=>`<option value="${esc(x.name)}">${esc(x.label||x.name)}</option>`).join('');iface.disabled=false;status.textContent='تم جلب '+d.interfaces.length+' منفذ.';}catch(e){status.textContent=e.message;}});
 if(iface)iface.addEventListener('change',()=>match.disabled=!(router.value&&iface.value));
 if(match)match.addEventListener('click',async()=>{match.disabled=true;status.textContent='جاري قراءة المنفذ ومطابقته…';const fd=new FormData();fd.append('router_id',router.value);fd.append('interface',iface.value);try{const r=await fetch('api/router_port_match.php',{method:'POST',body:fd,headers:{'X-Requested-With':'XMLHttpRequest'}});const d=await r.json();if(!d.ok)throw new Error(d.message||'فشلت المطابقة');const s=d.summary||{};summary.hidden=false;summary.innerHTML=['raw_mac_total','client_mac_total','matched_total','unknown_total','conflict_total'].map((k,i)=>`<div><strong>${esc(s[k]||0)}</strong><span>${['MAC خام','MAC منفذ','مطابق','غير معروف','تعارض'][i]}</span></div>`).join('');results.hidden=false;results.innerHTML=[...(d.matched||[]).map(x=>`<article class="is-match"><b>${esc(x.mac)}</b><span>${esc(x.full_name||x.username||'مطابق')}</span></article>`),...(d.unknown||[]).map(x=>`<article><b>${esc(x)}</b><span>غير معروف</span></article>`)].join('');status.textContent='اكتملت المطابقة وحُفظ المصدر.';}catch(e){status.textContent=e.message;}finally{match.disabled=false;}});
})();
</script>
