<?php
$page_title = 'NOC Control Center';
$UA_FORCE_DESIGN_V2 = true;
require_once __DIR__ . '/auth.php';

$uaAndroidDashboard = isset($_GET['ua_android']) && (string)$_GET['ua_android'] === '1';
if (!$uaAndroidDashboard) {
    $uaAndroidDashboard = stripos((string)($_SERVER['HTTP_USER_AGENT'] ?? ''), 'NetworkCustomersAndroid/') !== false;
}
if ($uaAndroidDashboard) {
    require __DIR__ . '/android_dashboard.php';
    exit;
}

$UA_PAGE_CSS = ['assets/css/noc_dashboard.css'];
define('UA_HIDE_FOOTER', true);
require_once __DIR__ . '/header.php';
require_once __DIR__ . '/sidebar.php';

$js_v  = @filemtime(__DIR__ . '/assets/js/noc_dashboard.js') ?: time();
$nocxAdminName = $adminDisplay ?? ($_SESSION['admin_username'] ?? ($_SESSION['admin_user'] ?? 'Admin'));
$nocxAdminInitial = function_exists('mb_substr') ? mb_substr((string)$nocxAdminName, 0, 1, 'UTF-8') : substr((string)$nocxAdminName, 0, 1);
if ($nocxAdminInitial === '') $nocxAdminInitial = 'A';
$nocxAdminAvatar = isset($adminAvatar) ? (string)$adminAvatar : (string)($_SESSION['admin_avatar'] ?? '');

// اسم الشركة من صفحة بيانات الشركة فقط، بدون الاعتماد على APP_NAME الافتراضي.
$nocxCompanyDisplay = '';
try {
  if (($conn ?? null) instanceof mysqli) {
    if (function_exists('table_exists') && table_exists($conn, 'company_info')) {
      $r = $conn->query("SELECT company_name FROM company_info WHERE id=1 LIMIT 1");
      if ($r && $r->num_rows) $nocxCompanyDisplay = trim((string)($r->fetch_assoc()['company_name'] ?? ''));
      if ($nocxCompanyDisplay === '') {
        $r = $conn->query("SELECT company_name FROM company_info WHERE COALESCE(company_name,'')<>'' LIMIT 1");
        if ($r && $r->num_rows) $nocxCompanyDisplay = trim((string)($r->fetch_assoc()['company_name'] ?? ''));
      }
    }
    if ($nocxCompanyDisplay === '' && function_exists('table_exists') && table_exists($conn, 'system_settings')) {
      if (function_exists('col_exists') && col_exists($conn, 'system_settings', 'company_name')) {
        $r = $conn->query("SELECT company_name FROM system_settings WHERE id=1 LIMIT 1");
        if ($r && $r->num_rows) $nocxCompanyDisplay = trim((string)($r->fetch_assoc()['company_name'] ?? ''));
      }
      if ($nocxCompanyDisplay === '') {
        $r = $conn->query("SELECT setting_value FROM system_settings WHERE setting_key='company_name' LIMIT 1");
        if ($r && $r->num_rows) $nocxCompanyDisplay = trim((string)($r->fetch_assoc()['setting_value'] ?? ''));
      }
    }
  }
} catch (Throwable $e) {}
if ($nocxCompanyDisplay === '') $nocxCompanyDisplay = 'اسم الشركة';

$dashCan = static function (string $permission): bool {
  return !function_exists('has_perm') || has_perm($permission);
};
$dashShowStats = $dashCan('can_view_dashboard_stats');
$dashShowAlerts = $dashCan('can_view_dashboard_alerts');
$dashShowSecurity = $dashCan('can_view_dashboard_security');
$dashShowSummary = $dashCan('can_view_dashboard_summary');
$dashShowTraffic = $dashCan('can_view_dashboard_traffic');
$dashShowRouters = $dashCan('can_view_dashboard_routers');
$dashShowSectors = $dashCan('can_view_dashboard_sectors');
$dashShowReceivers = $dashCan('can_view_dashboard_receivers');
$dashCanSearchSubscribers = $dashCan('can_search_dashboard_subscribers');
$dashMainColumns = (int)$dashShowSummary + (int)$dashShowTraffic + (int)$dashShowRouters;
$dashMainClasses = [
  'nocx-layout',
  'nocx-layout--v8',
  'nocx-layout--visible-' . $dashMainColumns,
  $dashShowSummary ? 'has-summary' : 'without-summary',
  $dashShowTraffic ? 'has-traffic' : 'without-traffic',
  $dashShowRouters ? 'has-routers' : 'without-routers',
];
?>
<div class="content-wrapper nocx-page ua-manual-page ua-dashboard-shell ua-dashboard-v2">
  <section class="content p-3">
    <?php
      $ua_live_stats_context = 'dashboard';
      $ua_live_stats_company = $nocxCompanyDisplay;
      $ua_live_stats_user_name = $nocxAdminName;
      $ua_live_stats_user_avatar = $nocxAdminAvatar;
      $ua_live_stats_user_initial = $nocxAdminInitial;
      $ua_live_stats_show_counts = $dashShowStats;
      $ua_live_stats_show_alerts = $dashShowAlerts;
      require __DIR__ . '/partials/live_stats_bar.php';
      unset($ua_live_stats_context, $ua_live_stats_company, $ua_live_stats_user_name, $ua_live_stats_user_avatar, $ua_live_stats_user_initial, $ua_live_stats_show_counts, $ua_live_stats_show_alerts);
    ?>
          <header class="ua-page-windowbar ua-page-windowbar--dashboard ua-dashboard-windowbar-host" data-ua-shared-windowbar data-ua-shell-region="dashboard-windowbar" aria-label="شريط النوافذ">
            <div class="ua-page-windowbar__title" aria-hidden="true">
              <i class="fa fa-bars" aria-hidden="true"></i>
              <span id="uaCurrentPageTitle">لوحة التحكم الرئيسية</span>
            </div>
            <nav class="ua-page-windowbar__pages" id="uaOpenPagesStrip" aria-label="الصفحات المفتوحة"></nav>
          </header>
    <div class="nocx-shell">
      <?php include __DIR__ . '/partials/section_nav.php'; ?>

      <?php if($dashShowSecurity || $dashCanSearchSubscribers): ?><section class="nocx-dashboard-utility-row <?= $dashShowSecurity ? 'has-security-monitor' : 'without-security-monitor' ?> <?= $dashCanSearchSubscribers ? 'has-subscriber-search' : 'without-subscriber-search' ?>" aria-label="مراقبة الشبكة والبحث">
        <?php if($dashShowSecurity): ?><section class="nocx-security-monitor-row" aria-label="مراقب الشبكة الحي">
          <section class="nocx-panel nocx-panel--security-monitor" aria-label="مراقب الشبكة">
            <a class="nocx-secmon-link" href="security_monitor.php" title="فتح مراقب الشبكة">
              <div class="nocx-secmon-top">
                <div class="nocx-secmon-title">
                  <span class="nocx-secmon-orb" aria-hidden="true"><i class="fa fa-shield"></i></span>
                  <div><strong>مراقب الشبكة</strong><small id="securityMonitorSubtitle">أحداث اليوم فقط</small></div>
                </div>
                <span class="nocx-secmon-state" id="securityMonitorState"><i class="nocx-secmon-dot"></i><span>مستقر</span></span>
              </div>
              <div class="nocx-secmon-grid">
                <div class="nocx-secmon-cell info"><span>غير معرّف</span><strong id="securityMonitorIdentifying">0</strong></div>
                <div class="nocx-secmon-cell pppoe"><span>تعارض PPPoE</span><strong id="securityMonitorPppoe">0</strong></div>
                <div class="nocx-secmon-cell danger"><span>تغيّر الحساب</span><strong id="securityMonitorAccountChanges">0</strong></div>
                <div class="nocx-secmon-cell admin"><span>تغيّر الراوتر</span><strong id="securityMonitorRouterChanges">0</strong></div>
                <div class="nocx-secmon-cell warn"><span>تعارض MAC</span><strong id="securityMonitorMacConflicts">0</strong></div>
                <div class="nocx-secmon-cell danger"><span>دخول خطر</span><strong id="securityMonitorDangerousLogins">0</strong></div>
                <div class="nocx-secmon-cell"><span>إجمالي فعلي</span><strong id="securityMonitorTotal">0</strong></div>
              </div>
              <div class="nocx-secmon-last"><b id="securityMonitorLastText">بانتظار أول قراءة...</b><em id="securityMonitorLastAt">—</em></div>
            </a>
          </section>
        </section><?php endif; ?>

        <?php if($dashCanSearchSubscribers): ?><section class="nocx-dashboard-search-panel" aria-label="بحث المشتركين">
          <label class="nocx-title-search" aria-label="بحث المشتركين">
            <span class="nocx-search__icon"><i class="fa fa-search" aria-hidden="true"></i></span>
            <input id="nocDashboardSearch" type="search" data-ua-subscriber-search placeholder="ID، اسم المشترك، PPP أو الهاتف..." autocomplete="off">
          </label>
          <div class="nocx-dashboard-search-results" id="nocSubscriberSearchResults" hidden></div>
        </section>
        <?php endif; ?>
      </section><?php endif; ?>

      <section class="nocx-message-progress-row" id="dashboardMessageProgress" aria-label="تقدم إرسال الرسائل" hidden>
        <a href="messages_outbox.php" class="nocx-message-progress-link">
          <div class="nocx-message-progress-title">
            <span class="nocx-message-progress-icon"><i class="fa fa-paper-plane"></i></span>
            <span><b id="dashboardMessageProgressLabel">جارٍ إرسال الرسائل</b><small id="dashboardMessageProgressMeta">0 رسالة في الطابور</small></span>
          </div>
          <div class="nocx-message-progress-track"><i id="dashboardMessageProgressBar"></i></div>
          <div class="nocx-message-progress-counts">
            <span>المرسل <b id="dashboardMessageSent">0</b></span>
            <span>الفشل <b id="dashboardMessageFailed">0</b></span>
            <strong id="dashboardMessagePercent">0%</strong>
          </div>
        </a>
      </section>

      <?php if($dashMainColumns > 0): ?><div class="<?= h(implode(' ', $dashMainClasses)) ?>">

        <?php if($dashShowSummary): ?>
        <aside class="nocx-leftbar">
          <section class="nocx-panel nocx-panel--summary">
            <div class="nocx-panel__head compact">
              <div>
                <h3><span class="nocx-ico nocx-ico--summary" aria-hidden="true"></span>الحالة العامة</h3>
                <p>قراءة تشغيلية سريعة</p>
              </div>
            </div>

            <div class="nocx-summary-list">
              <div class="nocx-summary-row">
                <span><i class="nocx-ico nocx-ico--router"></i>الراوترات Online</span>
                <strong id="summaryRoutersOnline">0</strong>
              </div>

              <div class="nocx-summary-row">
                <span><i class="nocx-ico nocx-ico--alert"></i>وضع السرعات العامة</span>
                <strong id="summaryOpenAllMode">طبيعية</strong>
              </div>

              <div class="nocx-summary-row">
                <span><i class="nocx-ico nocx-ico--sector"></i>السكتورات Down</span>
                <strong id="summarySectorsDown">0</strong>
              </div>

              <div class="nocx-summary-row">
                <span><i class="nocx-ico nocx-ico--tower"></i>المستقبلات المرئية</span>
                <strong id="summaryReceivers">0</strong>
              </div>
            </div>

            <div class="nocx-mini-stat nocx-mini-stat--tight ua-u-mt-10">
              <div class="nocx-mini-stat__label">
                <i class="nocx-ico nocx-ico--users"></i>
                <span>مشتركين خلف المستقبلات</span>
              </div>
              <div class="nocx-mini-stat__value" id="subtowerStationsCount">0</div>
            </div>
            <div id="receiverStationsBody" class="nocx-receiver-stations-list">
              <div class="nocx-empty">بانتظار البيانات...</div>
            </div>
          </section>



        </aside>
        <?php endif; ?>

        <?php if($dashShowTraffic): ?>
        <main class="nocx-main">
          <section class="nocx-core-grid">
            <section class="nocx-panel nocx-panel--traffic-rail nocx-panel--traffic-main">
              <div class="nocx-panel__head compact">
                <div>
                  <h3><span class="nocx-ico nocx-ico--traffic" aria-hidden="true"></span>الترافيك</h3>
                  <p id="trafficSourcesLabel">المصادر: —</p>
                </div>
                <div class="nocx-head-meta nocx-card-actions" aria-label="إجراءات الترافيك">
                  <strong class="nocx-inline-value" id="trafficSourcesCount">0</strong>
                  <a class="nocx-icon-action" href="settings_hud.php" title="إعدادات الترافيك" aria-label="إعدادات الترافيك"><span aria-hidden="true">⇅</span></a>
                </div>
              </div>

              <div class="nocx-summary-band nocx-summary-band--traffic">
                <div class="nocx-band-item">
                  <span>الرفع:</span>
                  <strong id="heroTx">0.0 Mbps</strong>
                </div>
                <div class="nocx-band-item">
                  <span>التحميل:</span>
                  <strong id="heroRx">0.0 Mbps</strong>
                </div>
                <div class="nocx-band-item highlight">
                  <span>الإجمالي:</span>
                  <strong id="heroTotal">0.0 Mbps</strong>
                </div>
              </div>

              <div class="nocx-chart-wrap">
                <canvas id="trafficCanvas" width="1200" height="240"></canvas>
              </div>

              <div class="nocx-traffic-rail" id="trafficRailList">
                <div class="nocx-empty">لا توجد مصادر ترافيك معرفة.</div>
              </div>
            </section>
          </section>

        </main>
        <?php endif; ?>

        <?php if($dashShowRouters): ?>
        <aside class="nocx-rightbar">
          <section class="nocx-panel nocx-panel--routers nocx-panel--routers-vertical nocx-panel--routers-rail">
            <div class="nocx-panel__head">
              <div>
                <h3><span class="nocx-ico nocx-ico--router" aria-hidden="true"></span>الراوترات</h3>
                <p>الاسم، الطراز، العنوان، الحالة، المعالج، الذاكرة، ومدة التشغيل</p>
              </div>
              <div class="nocx-head-meta">
                <span class="nocx-soft-badge">Online <strong id="routersOnlineCount">0</strong></span>
                <span class="nocx-soft-badge">Total <strong id="routersTotalCount">0</strong></span>
              </div>
            </div>

            <div class="nocx-router-list" id="routerList">
              <div class="nocx-empty">بانتظار قراءة الراوترات...</div>
            </div>
          </section>
        </aside>
        <?php endif; ?>

      </div><?php endif; ?>

      <?php if($dashShowSectors || $dashShowReceivers): ?><section class="nocx-lower-stack <?= ($dashShowSectors xor $dashShowReceivers) ? 'nocx-lower-stack--single' : '' ?>">
        <?php if($dashShowSectors): ?>
        <section class="nocx-panel nocx-panel--sectors">
          <div class="nocx-panel__head">
            <div>
              <h3><span class="nocx-ico nocx-ico--sector" aria-hidden="true"></span>السكتورات</h3>
            </div>
            <div class="nocx-head-meta nocx-card-actions" aria-label="إجراءات السكتورات و airMAX">
              <span class="nocx-soft-badge">Down <strong id="sectorsDownCount">0</strong></span>
              <span class="nocx-soft-badge">Total <strong id="sectorsTotalCount">0</strong></span>
              <a class="nocx-icon-action" href="airmax_monitor_settings.php" title="إعدادات airMAX" aria-label="إعدادات airMAX"><span aria-hidden="true">⌁</span></a>
            </div>
          </div>

          <div class="nocx-table-wrap">
            <table class="nocx-table nocx-table--airmax">
              <thead>
                <tr>
                  <th>الاسم / العنوان</th>
                  <th>الجهاز</th>
                  <th>CPU</th>
                  <th>RAM</th>
                  <th>الحالة</th>
                </tr>
              </thead>
              <tbody id="sectorTableBody">
                <tr><td colspan="5" class="nocx-empty-cell">لا توجد بيانات سكتورات حالياً.</td></tr>
              </tbody>
            </table>
          </div>
        </section>
        <?php endif; ?>

        <?php if($dashShowReceivers): ?>
        <section class="nocx-panel nocx-panel--receivers">
          <div class="nocx-panel__head">
            <div>
              <h3><span class="nocx-ico nocx-ico--tower" aria-hidden="true"></span>المستقبلات</h3>
            </div>
            <div class="nocx-head-meta nocx-card-actions" aria-label="إجراءات المستقبلات">
              <span class="nocx-soft-badge">Total <strong id="subtowerTotalCount">0</strong></span>
              <button type="button" class="nocx-icon-action" id="receiverMatchRefreshBtn" title="تحديث مطابقة المستقبلات" aria-label="تحديث مطابقة المستقبلات"><span aria-hidden="true">↻</span></button>
            </div>
          </div>

          <div class="nocx-table-wrap">
            <table class="nocx-table nocx-table--airmax">
              <thead>
                <tr>
                  <th>الاسم / العنوان</th>
                  <th>الجهاز</th>
                  <th>Quality</th>
                  <th>Capacity</th>
                  <th>CPU</th>
                  <th>RAM</th>
                  <th>الحالة</th>
                </tr>
              </thead>
              <tbody id="subtowerTableBody">
                <tr><td colspan="7" class="nocx-empty-cell">لا توجد بيانات حالياً.</td></tr>
              </tbody>
            </table>
          </div>
        </section>
        <?php endif; ?>
      </section><?php endif; ?>
    </div>
  </section>
</div>



<script>
(function(){
  const alertDetails = document.getElementById('nocAlertDetails');
  if (!alertDetails) return;
  document.addEventListener('click', function(ev){
    if (!alertDetails.contains(ev.target)) alertDetails.removeAttribute('open');
  });
  document.addEventListener('keydown', function(ev){
    if (ev.key === 'Escape') alertDetails.removeAttribute('open');
  });
})();
</script>

<!-- تم حذف شريط التمرير الذهبي المخصص للداشبورد حتى تبقى حافة المحتوى نظيفة بجانب السايدبار. -->



<script>
(function(){
  'use strict';
  function normalizeAlertBadge(){
    var badge = document.getElementById('nocAlertCount');
    if (!badge) return;
    var raw = (badge.textContent || '').trim();
    var n = parseInt(raw, 10);
    var zero = !raw || !Number.isFinite(n) || n <= 0;
    if (zero) {
      badge.textContent = '';
      badge.classList.add('is-zero');
      badge.setAttribute('aria-hidden', 'true');
    } else {
      badge.classList.remove('is-zero');
      badge.removeAttribute('aria-hidden');
    }
  }
  document.addEventListener('DOMContentLoaded', function(){
    var badge = document.getElementById('nocAlertCount');
    if (!badge) return;
    normalizeAlertBadge();
    new MutationObserver(normalizeAlertBadge).observe(badge, { childList:true, characterData:true, subtree:true });
  });
})();
</script>



<script>
(function(){
  'use strict';
  function esc(v){
    return String(v || '').replace(/[&<>"']/g, function(ch){return {'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[ch];});
  }
  function norm(v){ return String(v || '').replace(/\s+/g, ' ').trim(); }
  document.addEventListener('DOMContentLoaded', function(){
    var input = document.getElementById('nocDashboardSearch');
    var box = document.getElementById('nocSubscriberSearchResults');
    if (!input || !box) return;
    var timer = null;
    var lastQ = '';
    var items = [];
    function hide(){ box.hidden = true; box.innerHTML = ''; }
    function statusClass(item){ return item.disabled ? ' is-disabled' : (item.online ? ' is-online' : ''); }
    function render(list, q){
      items = Array.isArray(list) ? list : [];
      if (!q) { hide(); return; }
      if (!items.length) {
        box.innerHTML = '<div class="nocx-dash-search-empty">لا توجد نتائج مطابقة</div>';
        box.hidden = false;
        return;
      }
      box.innerHTML = items.map(function(item, i){
        var name = item.name || item.username || item.ppp_username || ('#' + (item.id || ''));
        return '<button type="button" class="nocx-dash-search-item" data-url="' + esc(item.url || '') + '" data-index="' + i + '">' +
          '<span class="nocx-dash-search-main">' + esc(name) + ' <small>#' + esc(item.id || '') + '</small></span>' +
          '<span class="nocx-dash-search-status' + statusClass(item) + '">' + esc(item.status || '') + '</span>' +
        '</button>';
      }).join('');
      box.hidden = false;
    }
    async function search(q){
      q = norm(q);
      lastQ = q;
      if (q.length < 2 && !/^\d+$/.test(q)) { hide(); return; }
      box.hidden = false;
      box.innerHTML = '<div class="nocx-dash-search-empty">جاري البحث...</div>';
      try {
        var res = await fetch('api/dashboard_subscriber_search.php?q=' + encodeURIComponent(q) + '&_=' + Date.now(), {credentials:'same-origin', headers:{'Accept':'application/json'}});
        var data = await res.json().catch(function(){ return null; });
        if (q !== lastQ) return;
        render(data && data.ok ? data.items : [], q);
      } catch(e) {
        if (q === lastQ) box.innerHTML = '<div class="nocx-dash-search-empty">تعذر تنفيذ البحث</div>';
      }
    }
    function go(url){
      url = url || ('subscribers.php?filter=all&q=' + encodeURIComponent(norm(input.value)));
      if (!url) return;
      window.location.href = url;
    }
    input.addEventListener('input', function(){
      clearTimeout(timer);
      timer = setTimeout(function(){ search(input.value); }, 180);
    });
    input.addEventListener('focus', function(){ var q = norm(input.value); if (q.length >= 2 || /^\d+$/.test(q)) search(q); });
    input.addEventListener('keydown', function(ev){
      if (ev.key !== 'Enter') return;
      ev.preventDefault();
      var first = box.querySelector('.nocx-dash-search-item');
      go(first ? first.getAttribute('data-url') : '');
    });
    box.addEventListener('click', function(ev){
      var item = ev.target.closest('.nocx-dash-search-item');
      if (!item) return;
      ev.preventDefault();
      go(item.getAttribute('data-url') || '');
    });
    document.addEventListener('click', function(ev){
      if (ev.target === input || ev.target.closest('#nocSubscriberSearchResults') || ev.target.closest('.nocx-title-search')) return;
      hide();
    });
  });
})();
</script>

<script>
window.NOC_DASHBOARD_ACCESS = <?= json_encode([
  'counts' => $dashShowStats || $dashShowSummary,
  'routers' => $dashShowRouters || $dashShowSummary,
  'sectors' => $dashShowSectors || $dashShowSummary,
  'receivers' => $dashShowReceivers || $dashShowSummary,
  'receiverRefresh' => $dashShowReceivers,
  'traffic' => $dashShowTraffic || $dashShowStats,
  'billing' => $dashShowAlerts,
  'networkAlerts' => $dashShowAlerts,
  'securityAlerts' => $dashShowAlerts,
  'securityMonitor' => $dashShowSecurity,
], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) ?>;
window.NOC_CSRF = <?= json_encode(function_exists('ua_csrf_token') ? ua_csrf_token() : '', JSON_UNESCAPED_SLASHES) ?>;
</script>
<script src="assets/js/noc_dashboard.js?v=<?= (int)$js_v ?>" defer></script>
<?php require_once __DIR__ . '/footer.php'; ?>
