<?php
$page_title = 'لوحة MikroTik';
require_once __DIR__ . '/auth.php';
require_once __DIR__ . '/helpers.php';
require_once __DIR__ . '/mikrotik_lib.php';

require_login();
if(function_exists('require_perm')) require_perm('can_settings');

$UA_FORCE_DESIGN_V2 = true;
$uaAndroidMikrotikDashboard = ((string)($_GET['ua_android'] ?? '') === '1')
  || stripos((string)($_SERVER['HTTP_USER_AGENT'] ?? ''), 'NetworkCustomersAndroid/') !== false;
$UA_PAGE_CSS = ['assets/css/pages/mikrotik_dashboard_admin.css'];
if ($uaAndroidMikrotikDashboard) $UA_PAGE_CSS[] = 'assets/css/android_mikrotik_dashboard.css';
include __DIR__ . '/header.php';
include __DIR__ . '/sidebar.php';

$ms = mt_get_settings($conn);

if ($uaAndroidMikrotikDashboard) {
  require __DIR__ . '/android_mikrotik_dashboard.php';
  include __DIR__ . '/footer.php';
  exit;
}

?>

<div class="content-wrapper mk-dashboard ua-extracted-page" data-ua-help-skip="1">
  <section class="content">
    <div class="ua-studio-wrap">
      <div class="ua-studio-hero">
        <div>
          <h1>لوحة MikroTik</h1>
          <p>متابعة حالة الاتصال، جلسات PPPoE، Simple Queues، وترافيك المشتركين من واجهة واحدة.</p>
        </div>
        <div class="ua-studio-actions">
          <a href="mikrotik.php" class="btn btn-primary"><i class="fa fa-cog"></i> إعدادات MikroTik</a>
          <a href="automation_billing.php#run" class="btn btn-danger"><i class="fa fa-bolt"></i> فحص الحصة الآن</a>
        </div>
      </div>

      <div class="ua-studio-grid">
        <article class="ua-studio-card ua-compact mk-stat-card">
          <div class="ua-studio-card-head">
            <h3 class="ua-studio-title"><i class="fa fa-heartbeat"></i> الحالة</h3>
            <span class="ua-studio-meta">Live</span>
          </div>
          <div class="ua-studio-body">
            <div id="mkStatus" class="ua-studio-kpi-value">...</div>
            <div class="ua-studio-footer">
              <button type="button" class="btn btn-default" id="btnApiAny" title="فتح API لأي عنوان">API Any</button>
            </div>
          </div>
        </article>

        <article class="ua-studio-card ua-compact mk-stat-card">
          <div class="ua-studio-card-head">
            <h3 class="ua-studio-title"><i class="fa fa-exchange"></i> الإنترنت الصادر</h3>
            <span class="ua-studio-meta">Subscribers TX</span>
          </div>
          <div class="ua-studio-body">
            <div id="subsTraffic" class="ua-studio-kpi-value gold">0 Mbps</div>
            <p class="ua-studio-text">قياس الإرسال على منفذ المشتركين.</p>
          </div>
        </article>

        <article class="ua-studio-card ua-wide ua-full">
          <div class="ua-studio-card-head">
            <h3 class="ua-studio-title"><i class="fa fa-wifi"></i> PPPoE Active Sessions</h3>
            <span class="ua-studio-meta">آخر الجلسات</span>
          </div>
          <div class="ua-studio-body table-responsive">
            <table class="table table-bordered table-striped" id="pppTable">
              <thead><tr><th>Username</th><th>IP</th><th>Uptime</th><th>Service</th></tr></thead>
              <tbody><tr><td colspan="4" class="text-center text-muted">...</td></tr></tbody>
            </table>
          </div>
        </article>

        <article class="ua-studio-card ua-wide ua-full">
          <div class="ua-studio-card-head">
            <h3 class="ua-studio-title"><i class="fa fa-tasks"></i> Simple Queues</h3>
            <span class="ua-studio-meta">Queues</span>
          </div>
          <div class="ua-studio-body table-responsive">
            <table class="table table-bordered table-striped" id="qTable">
              <thead><tr><th>Name</th><th>Target</th><th>Max-Limit</th><th>Bytes</th><th>Disabled</th></tr></thead>
              <tbody><tr><td colspan="5" class="text-center text-muted">...</td></tr></tbody>
            </table>
          </div>
        </article>
      </div>

      <script>
      (function(){
        const elStatus = document.getElementById('mkStatus');
        const elTraffic = document.getElementById('subsTraffic');
        const pppBody = document.querySelector('#pppTable tbody');
        const qBody = document.querySelector('#qTable tbody');
        const btnApiAny = document.getElementById('btnApiAny');

        function fmtMbps(bps){
          const mbps = (bps||0)/1e6;
          return mbps.toFixed(2) + ' Mbps';
        }
        function esc(s){
          return String(s??'').replace(/[&<>"']/g, c => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;','\'':'&#39;'}[c]));
        }

        async function fetchJson(url){
          const r = await fetch(url, {credentials:'same-origin'});
          return await r.json();
        }

        async function postJson(url, data){
          const r = await fetch(url, {
            method: 'POST',
            headers: {'Content-Type':'application/json'},
            credentials:'same-origin',
            body: JSON.stringify(data||{})
          });
          return await r.json();
        }

        if(btnApiAny){
          btnApiAny.addEventListener('click', async function(){
            if(!confirm('هل تريد جعل خدمة API على الراوتر متاحة لأي عنوان (0.0.0.0/0)؟')) return;
            btnApiAny.disabled = true;
            try{
              const res = await postJson('api/mikrotik_set_api_any.php', {});
              if(res && res.ok){
                alert('تم ضبط API على Any ✅');
              } else {
                alert('فشل: ' + (res && (res.error||res.msg) ? (res.error||res.msg) : 'خطأ غير معروف'));
              }
            } catch(e){
              alert('فشل الاتصال: ' + e.message);
            } finally {
              btnApiAny.disabled = false;
            }
          });
        }

        async function refresh(){
          try {
            const st = await fetchJson('api/mikrotik_status.php');
            elStatus.textContent = st.connected ? 'متصل ✅' : 'غير متصل ❌';
          } catch(e){
            elStatus.textContent = 'غير متصل ❌';
          }

          try {
            const d = await fetchJson('api/mikrotik_monitor.php');
            if(!d.ok) throw new Error(d.error||'');
            elTraffic.textContent = fmtMbps((d.traffic||{}).tx_bps||0);

            const ppp = d.pppoe_active||[];
            if(ppp.length===0){
              pppBody.innerHTML = '<tr><td colspan="4" class="text-center text-muted">لا يوجد جلسات حالياً</td></tr>';
            } else {
              pppBody.innerHTML = ppp.slice(0,20).map(r =>
                `<tr><td>${esc(r.name)}</td><td>${esc(r.address)}</td><td>${esc(r.uptime)}</td><td>${esc(r.service)}</td></tr>`
              ).join('');
            }

            const qs = d.queues||[];
            if(qs.length===0){
              qBody.innerHTML = '<tr><td colspan="5" class="text-center text-muted">لا توجد Queues</td></tr>';
            } else {
              qBody.innerHTML = qs.slice(0,30).map(r =>
                `<tr><td>${esc(r.name)}</td><td>${esc(r.target)}</td><td>${esc(r.max_limit)}</td><td>${esc(r.bytes)}</td><td>${esc(r.disabled)}</td></tr>`
              ).join('');
            }
          } catch(e){
            elTraffic.textContent = '0 Mbps';
            pppBody.innerHTML = '<tr><td colspan="4" class="text-center text-muted">تعذر جلب البيانات</td></tr>';
            qBody.innerHTML = '<tr><td colspan="5" class="text-center text-muted">تعذر جلب البيانات</td></tr>';
          }
        }

        refresh();
        setInterval(refresh, 10000);
      })();
      </script>

    </div>
  </section>
</div>

<?php include __DIR__ . '/footer.php'; ?>
