<?php
$asmGroups = [
  ['id'=>'watch','icon'=>'fa-search','kicker'=>'الرصد المبكر اليوم','title'=>'التعرف والاشتباه','rows'=>array_slice($watchRows,0,30),'total'=>count($watchRows),'empty'=>'لا توجد حالات قيد التعرف أو الاشتباه اليوم.'],
  ['id'=>'pppoe','icon'=>'fa-random','kicker'=>'PPPoE اليوم','title'=>'تعارضات الدخول','rows'=>array_slice($pppoeRows,0,30),'total'=>count($pppoeRows),'empty'=>'لا توجد تعارضات PPPoE اليوم.'],
  ['id'=>'network','icon'=>'fa-warning','kicker'=>'الشبكة اليوم','title'=>'التنبيهات المؤكدة','rows'=>array_slice($networkRows,0,30),'total'=>count($networkRows),'empty'=>'لا توجد تنبيهات شبكة مؤكدة اليوم.'],
  ['id'=>'admin','icon'=>'fa-shield','kicker'=>'الإدارة والراوتر اليوم','title'=>'أحداث الأمان','rows'=>array_slice($adminRows,0,20),'total'=>count($adminRows),'empty'=>'لا توجد أحداث أمان اليوم.'],
  ['id'=>'eventlog','icon'=>'fa-inbox','kicker'=>'المراجعة اللاحقة','title'=>'سجل معالجة الأحداث','rows'=>array_slice($eventLogRows,0,30),'total'=>count($eventLogRows),'empty'=>'لا توجد أحداث بانتظار المعالجة.'],
  ['id'=>'allow','icon'=>'fa-check-circle','kicker'=>'القواعد الموثوقة','title'=>'قائمة السماح','rows'=>array_slice($allowRows,0,20),'total'=>count($allowRows),'empty'=>'لا توجد عناصر سماح.'],
];
$asmDefaultOpen = $watchRows ? 'watch' : ($pppoeRows ? 'pppoe' : ($networkRows ? 'network' : ($adminRows ? 'admin' : 'watch')));
?>
<div class="content-wrapper android-security-monitor" data-android-security-monitor>
  <main class="asm-main">
    <header class="asm-heading is-<?= h($status) ?>">
      <div><span>مراقبة ذكية</span><h1>مركز الأمان</h1><p>أحداث اليوم فقط، مع سجل مستقل للمعالجة والتجاهل والسماح لاحقاً.</p></div>
      <div class="asm-overall"><i></i><strong><?= h($statusLabel) ?></strong></div>
    </header>

    <div class="asm-stats">
      <div class="is-info"><strong><?= (int)$identifying ?></strong><span>تعرف اليوم</span></div>
      <div class="is-warn"><strong><?= (int)$suspect ?></strong><span>اشتباه اليوم</span></div>
      <div class="is-danger"><strong><?= (int)$confirmed ?></strong><span>مؤكد اليوم</span></div>
      <div class="is-warn"><strong><?= (int)$pppoeOpen ?></strong><span>PPPoE اليوم</span></div>
      <div class="is-danger"><strong><?= (int)$adminOpen ?></strong><span>أمان اليوم</span></div>
      <div class="is-ok"><strong><?= (int)$allowCount ?></strong><span>سماح</span></div>
    </div>

    <?php if (!empty($macAllowDisabled)): ?><div class="asm-message is-ok"><i class="fa fa-check-circle"></i><span>تم إيقاف <?= (int)$macAllowDisabled ?> سماح MAC قديم بانتظار مراجعة الملكية.</span></div><?php endif; ?>
    <?php if ($msg): ?><div class="asm-message is-ok"><i class="fa fa-check-circle"></i><span><?= h($msg) ?></span></div><?php endif; ?>
    <?php if ($err): ?><div class="asm-message is-danger"><i class="fa fa-exclamation-circle"></i><span><?= h($err) ?></span></div><?php endif; ?>

    <?php foreach ($asmGroups as $group): ?>
      <?php $rows=$group['rows']; $isOpen=$group['id']===$asmDefaultOpen||$focusType===$group['id']||($focusType==='network'&&in_array($group['id'],['pppoe','network'],true)); ?>
      <details class="asm-group" <?= $isOpen?'open':'' ?> id="asm-<?= h($group['id']) ?>">
        <summary>
          <span class="asm-group-icon"><i class="fa <?= h($group['icon']) ?>"></i></span>
          <div><small><?= h($group['kicker']) ?></small><h2><?= h($group['title']) ?></h2></div>
          <b><?= (int)$group['total'] ?></b><i class="fa fa-chevron-down asm-chevron"></i>
        </summary>
        <div class="asm-group-body">
          <?php if (!$rows): ?><div class="asm-empty"><i class="fa fa-check-circle"></i><strong>لا توجد حالات مفتوحة</strong><span><?= h($group['empty']) ?></span></div><?php endif; ?>

          <?php foreach ($rows as $row): ?>
            <?php
              $rid=(int)($row['id']??0);
              $stage=(string)($row['stage']??'');
              $severity=(string)($row['severity']??'');
              $tone=$stage?smp_stage_class($stage):($severity==='danger'?'danger':($severity==='warn'?'warn':($severity==='info'?'info':'ok')));
              if ($group['id']==='allow') $tone=((int)($row['enabled']??0)===1?'ok':'muted');
              if ($group['id']==='eventlog') $tone=((string)($row['review_status']??'pending')==='pending'?'warn':'ok');
            ?>
            <article class="asm-alert-card is-<?= h($tone) ?> <?= (($focusType===$group['id']||($focusType==='network'&&in_array($group['id'],['pppoe','network'],true)))&&$focusId===$rid)?'asm-focus':'' ?>">
              <header>
                <div><span>#<?= $rid ?></span><h3><?= h((string)($row['title']??$row['label']??$row['username']??$row['ip_address']??'حالة مراقبة')) ?></h3></div>
                <b><?= h($group['id']==='allow'?((int)($row['enabled']??0)===1?'فعال':'متوقف'):($group['id']==='eventlog'?smp_review_label((string)($row['review_status']??'pending')):($stage?smp_stage_label($stage):($severity?:$group['kicker'])))) ?></b>
              </header>

              <?php if (!empty($row['message'])||!empty($row['decision_note'])||!empty($row['note'])): ?><p class="asm-description"><?= h((string)($row['message']??$row['decision_note']??$row['note'])) ?></p><?php endif; ?>

              <div class="asm-data">
                <?php if (!empty($row['ip_address'])): ?><div><span>IP</span><strong dir="ltr"><?= h($row['ip_address']) ?></strong></div><?php endif; ?>
                <?php if (!empty($row['mac_address'])): ?><div><span>MAC</span><strong dir="ltr"><?= h($row['mac_address']) ?></strong></div><?php endif; ?>
                <?php if (!empty($row['username'])): ?><div><span>Username</span><strong dir="ltr"><?= h($row['username']) ?></strong></div><?php endif; ?>
                <?php if (!empty($row['interface_name'])): ?><div><span>Interface</span><strong dir="ltr"><?= h($row['interface_name']) ?></strong></div><?php endif; ?>
                <?php if (!empty($row['source'])): ?><div><span>المصدر</span><strong dir="ltr"><?= h($row['source']) ?></strong></div><?php endif; ?>
                <?php if (!empty($row['alert_type'])): ?><div><span>النوع</span><strong dir="ltr"><?= h($row['alert_type']) ?></strong></div><?php endif; ?>
                <?php if (!empty($row['kind'])): ?><div><span>النوع</span><strong dir="ltr"><?= h($row['kind']) ?></strong></div><?php endif; ?>
                <?php if (!empty($row['value1'])): ?><div><span>القيمة</span><strong dir="ltr"><?= h($row['value1']) ?></strong></div><?php endif; ?>
                <?php if (!empty($row['last_seen_at'])): ?><div><span>آخر ظهور</span><strong dir="ltr"><?= h($row['last_seen_at']) ?></strong></div><?php endif; ?>
                <?php if (isset($row['hit_count'])||isset($row['seen_count'])): ?><div><span>التكرار</span><strong><?= (int)($row['hit_count']??$row['seen_count']??1) ?></strong></div><?php endif; ?>
              </div>

              <?php if ($group['id']==='eventlog'): ?>
                <footer>
                  <form method="post"><?php if(function_exists('ua_csrf_field'))ua_csrf_field(); ?><input type="hidden" name="act" value="review_event"><input type="hidden" name="event_id" value="<?= $rid ?>"><button name="review_action" value="resolve" type="submit"><i class="fa fa-check"></i><span>معالجة</span></button></form>
                  <form method="post"><?php if(function_exists('ua_csrf_field'))ua_csrf_field(); ?><input type="hidden" name="act" value="review_event"><input type="hidden" name="event_id" value="<?= $rid ?>"><button name="review_action" value="ignore" type="submit"><i class="fa fa-eye-slash"></i><span>تجاهل</span></button></form>
                  <?php if(!empty($row['username'])||!empty($row['ip_address'])): ?><form method="post"><?php if(function_exists('ua_csrf_field'))ua_csrf_field(); ?><input type="hidden" name="act" value="review_event"><input type="hidden" name="event_id" value="<?= $rid ?>"><button name="review_action" value="allow" type="submit"><i class="fa fa-check-circle"></i><span>سماح</span></button></form><?php endif; ?>
                  <form method="post" onsubmit="return confirm('حذف الحدث من قائمة العمل؟')"><?php if(function_exists('ua_csrf_field'))ua_csrf_field(); ?><input type="hidden" name="act" value="review_event"><input type="hidden" name="event_id" value="<?= $rid ?>"><button name="review_action" value="delete" class="is-close" type="submit"><i class="fa fa-trash"></i><span>حذف</span></button></form>
                </footer>
              <?php elseif ($group['id']!=='allow'): ?>
                <footer>
                  <?php if (!empty($row['ip_address'])): ?><form method="post"><?php if(function_exists('ua_csrf_field'))ua_csrf_field(); ?><input type="hidden" name="act" value="allow"><input type="hidden" name="kind" value="ip"><input type="hidden" name="value1" value="<?= h($row['ip_address']) ?>"><input type="hidden" name="value2" value=""><input type="hidden" name="label" value="مراقبة سماح IP"><input type="hidden" name="note" value="إضافة من مراقب الشبكة"><button type="submit"><i class="fa fa-check"></i><span>سماح IP</span></button></form><?php endif; ?>
                  <?php if (!empty($row['username'])): ?><form method="post"><?php if(function_exists('ua_csrf_field'))ua_csrf_field(); ?><input type="hidden" name="act" value="allow"><input type="hidden" name="kind" value="username"><input type="hidden" name="value1" value="<?= h($row['username']) ?>"><input type="hidden" name="value2" value=""><input type="hidden" name="label" value="مراقبة سماح Username"><input type="hidden" name="note" value="إضافة من مراقب الشبكة"><button type="submit"><i class="fa fa-user-plus"></i><span>سماح مستخدم</span></button></form><?php endif; ?>
                  <?php if ((int)($row['subscriber_id']??0)>0): ?><a href="subscribers_history.php?id=<?= (int)$row['subscriber_id'] ?>"><i class="fa fa-user"></i><span>المشترك</span></a><?php endif; ?>
                  <form method="post"><?php if(function_exists('ua_csrf_field'))ua_csrf_field(); ?><input type="hidden" name="act" value="<?= $group['id']==='watch'?'close_watch':($group['id']==='admin'?'close_admin':'close_network') ?>"><input type="hidden" name="id" value="<?= $rid ?>"><button class="is-close" type="submit"><i class="fa fa-times"></i><span>إغلاق</span></button></form>
                </footer>
              <?php endif; ?>
            </article>
          <?php endforeach; ?>
        </div>
      </details>
    <?php endforeach; ?>

    <nav class="asm-links"><a href="security_alerts.php"><i class="fa fa-list"></i><span>سجل الأمان الكامل</span></a><a href="mtwatch_allowlist.php"><i class="fa fa-check-circle"></i><span>إدارة قائمة السماح</span></a></nav>
  </main>
</div>
<script>(function(){var el=document.querySelector('.asm-focus');if(el)setTimeout(function(){el.scrollIntoView({block:'center'});},250);})();</script>
