<?php
// admin/security_monitor.php - مراقب الشبكة الذكي
$page_title = 'مراقب الشبكة';
$uaAndroidSecurityMonitor = ((string)($_GET['ua_android'] ?? '') === '1')
  || stripos((string)($_SERVER['HTTP_USER_AGENT'] ?? ''), 'NetworkCustomersAndroid/') !== false;
$UA_PAGE_CSS = ['assets/css/pages/security_monitor_admin.css'];
if ($uaAndroidSecurityMonitor) $UA_PAGE_CSS[] = 'assets/css/android_security_monitor.css';
if (session_status() === PHP_SESSION_NONE) session_start();
require_once __DIR__ . '/header.php';
require_once __DIR__ . '/sidebar.php';
require_once __DIR__ . '/subscriber_mikrotik_watch_lib.php';
require_once __DIR__ . '/security_alerts_lib.php';
require_once __DIR__ . '/security_monitor_lib.php';
require_once __DIR__ . '/mac_ownership_lib.php';

if (!($conn instanceof mysqli)) {
  echo '<div class="content-wrapper ua-manual-page"><section class="content"><div class="container-fluid p-4"><div class="alert alert-danger">فشل الاتصال بقاعدة البيانات.</div></div></section></div>';
  require_once __DIR__ . '/footer.php';
  exit;
}
mtwatch_ensure_schema($conn);
ua_security_alerts_ensure_schema($conn);
if (function_exists('uamac_ensure_schema')) uamac_ensure_schema($conn);
if (function_exists('mtwatch_auto_filter_internal_observations')) { @mtwatch_auto_filter_internal_observations($conn, []); }
if (function_exists('sm_ensure_event_log_schema')) sm_ensure_event_log_schema($conn);
if (function_exists('sm_sync_daily_event_log')) sm_sync_daily_event_log($conn);
$macAllowDisabled = function_exists('smp_disable_mac_allowances') ? smp_disable_mac_allowances($conn) : 0;
$securityCleanup = function_exists('sm_cleanup_stale_security_alerts') ? sm_cleanup_stale_security_alerts($conn, 3, 30) : [];

function smp_stage_label(string $stage): string {
  $m = ['observed'=>'رصد أولي','identifying'=>'قيد التعرف','suspect'=>'اشتباه','confirmed'=>'مؤكد','active'=>'مطابق PPPoE','allowlisted'=>'مسموح','resolved'=>'محلول','closed'=>'مغلق'];
  return $m[$stage] ?? $stage;
}
function smp_stage_class(string $stage): string {
  if ($stage === 'confirmed') return 'danger';
  if ($stage === 'suspect') return 'warn';
  if ($stage === 'identifying' || $stage === 'observed') return 'info';
  if ($stage === 'allowlisted' || $stage === 'active' || $stage === 'resolved') return 'ok';
  return 'muted';
}
function smp_review_label(string $status): string {
  $labels = ['pending'=>'بانتظار المعالجة','ignored'=>'متجاهل','allowed'=>'مسموح','resolved'=>'تمت المعالجة','deleted'=>'محذوف'];
  return $labels[$status] ?? $status;
}
function smp_category_label(string $category): string {
  $labels = [
    'identifying'=>'قيد التعرف','suspect'=>'اشتباه','pppoe'=>'تعارض PPPoE',
    'account_change'=>'تغيّر الحساب','router_change'=>'تغيّر الراوتر',
    'mac_conflict'=>'تعارض MAC','dangerous_login'=>'دخول خطر',
    'network'=>'حدث شبكة','admin'=>'حدث إدارة',
  ];
  return $labels[$category] ?? $category;
}
function smp_csrf_input(): string {
  return function_exists('ua_csrf_token')
    ? '<input type="hidden" name="ua_csrf" value="' . h(ua_csrf_token()) . '">'
    : '';
}
function smp_allow_buttons(string $mac, string $ip, string $username, string $prefix=''): string {
  // لا نستخدم سماح MAC هنا بعد الآن؛ تعارض ملكية MAC يجب أن يحسم من زر "اعتماد كمالك" لا أن يُخفى كتنبيه.
  $out = '';
  $mac = mtwatch_norm_mac($mac); $ip = trim($ip); $username = mtwatch_norm_user($username);
  $mk = function($kind,$v1,$v2,$txt) use ($prefix) {
    return '<form method="post" class="secmon-inline">'.smp_csrf_input().'<input type="hidden" name="act" value="allow"><input type="hidden" name="kind" value="'.h($kind).'"><input type="hidden" name="value1" value="'.h($v1).'"><input type="hidden" name="value2" value="'.h($v2).'"><input type="hidden" name="label" value="'.h($prefix.' '.$txt).'"><input type="hidden" name="note" value="إضافة من مراقب الشبكة"><button class="secmon-btn secmon-btn--soft" type="submit">'.h($txt).'</button></form>';
  };
  if ($ip !== '') $out .= $mk('ip',$ip,'','سماح IP');
  if ($username !== '') $out .= $mk('username',$username,'','سماح Username');
  return $out !== '' ? $out : '<span class="secmon-muted">لا توجد قيمة سماح واضحة</span>';
}

function smp_disable_mac_allowances(mysqli $conn): int {
  if (!function_exists('mtwatch_table_exists') || !mtwatch_table_exists($conn, 'mtwatch_allowlist')) return 0;
  $sql = "UPDATE mtwatch_allowlist
          SET enabled=0,
              updated_at=NOW(),
              note=CONCAT(COALESCE(note,''), IF(COALESCE(note,'')='', '', ' | '), 'تم إلغاء سماح MAC لأن حسم الملكية أصبح من مراقب الشبكة.')
          WHERE enabled=1 AND kind IN ('mac','mac_ip')";
  @ $conn->query($sql);
  return max(0, (int)$conn->affected_rows);
}

function smp_mac_claim_buttons(mysqli $conn, array $alert): string {
  if (!function_exists('uamac_norm_mac') || !function_exists('uamac_claim_owner')) return '';
  $mac = uamac_norm_mac((string)($alert['mac_address'] ?? ''));
  if ($mac === '') return '';
  $meta = [];
  $raw = (string)($alert['meta_json'] ?? '');
  if ($raw !== '') {
    $tmp = json_decode($raw, true);
    if (is_array($tmp)) $meta = $tmp;
  }
  $cands = [];
  foreach ((array)($meta['candidates'] ?? []) as $c) {
    if (!is_array($c)) continue;
    $sid = (int)($c['id'] ?? $c['subscriber_id'] ?? 0);
    if ($sid > 0) $cands[$sid] = $c;
  }
  if (!$cands && function_exists('uamac_collect_candidates')) {
    $all = uamac_collect_candidates($conn, []);
    foreach ((array)($all[$mac] ?? []) as $sid => $c) {
      if ((int)$sid > 0 && is_array($c)) $cands[(int)$sid] = $c;
    }
  }
  if (!$cands) return '';
  $out = '<div class="secmon-owner-actions"><div class="secmon-muted ua-u-owner-label">حسم ملكية MAC:</div>';
  foreach ($cands as $sid => $c) {
    $name = trim((string)($c['full_name'] ?? '')) ?: (trim((string)($c['ppp_username'] ?? '')) ?: (trim((string)($c['username'] ?? '')) ?: ('#'.$sid)));
    $out .= '<form method="post" class="secmon-inline" onsubmit="return confirm(\'اعتماد هذا المشترك كمالك رسمي للـ MAC وتنظيفه من الحقول التشغيلية عند البقية؟\')">'
          . smp_csrf_input()
          . '<input type="hidden" name="act" value="claim_mac_owner">'
          . '<input type="hidden" name="mac" value="'.h($mac).'">'
          . '<input type="hidden" name="subscriber_id" value="'.(int)$sid.'">'
          . '<button class="secmon-btn secmon-btn--gold" type="submit">اعتماد #'.(int)$sid.' '.h($name).'</button>'
          . '</form>';
  }
  return $out . '</div>';
}

$msg = ''; $err = '';
if (($_SERVER['REQUEST_METHOD'] ?? '') === 'POST') {
  $act = smp_s($_POST['act'] ?? '', 60);
  $csrfOk = !function_exists('ua_csrf_verify') || ua_csrf_verify();
  if (!$csrfOk) {
    $err = 'انتهت صلاحية الطلب. أعد تحميل الصفحة وحاول مجدداً.';
    $act = '';
  } elseif ($act === 'review_event') {
    $eventId = (int)($_POST['event_id'] ?? 0);
    $reviewAction = smp_s($_POST['review_action'] ?? '', 30);
    $reviewNote = smp_s($_POST['review_note'] ?? '', 2000);
    $actor = (string)($_SESSION['admin_username'] ?? $_SESSION['admin_user'] ?? 'admin');
    $review = function_exists('sm_event_log_review')
      ? sm_event_log_review($conn, $eventId, $reviewAction, $reviewNote, $actor)
      : ['ok'=>false, 'message'=>'سجل المعالجة غير متاح.'];
    if (!empty($review['ok'])) {
      $msg = 'تم حفظ قرار معالجة الحدث في السجل.';
    } else {
      $err = (string)($review['message'] ?? 'تعذر معالجة الحدث.');
    }
    $act = '';
  } elseif ($act === 'close_network') {
    $id = (int)($_POST['id'] ?? 0);
    $res = function_exists('sm_close_network_alert') ? sm_close_network_alert($conn, $id, 'closed', 'Closed from security monitor.') : ['ok'=>false];
    if (!empty($res['ok'])) $msg = 'تم إغلاق التنبيه.'; else $err = 'تعذر إغلاق التنبيه.';
    $act = '';
  } elseif ($act === 'close_admin') {
    $id = (int)($_POST['id'] ?? 0);
    $res = function_exists('sm_close_admin_alert') ? sm_close_admin_alert($conn, $id, 'closed', 'Closed from security monitor.') : ['ok'=>($id > 0 && ua_security_close_alert($conn, $id))];
    if (!empty($res['ok'])) $msg = 'تم إغلاق التنبيه الأمني.'; else $err = 'تعذر إغلاق التنبيه.';
    $act = '';
  }
  if ($act === 'close_watch') {
    $id = (int)($_POST['id'] ?? 0);
    if ($id > 0 && @$conn->query("UPDATE network_ip_watch SET stage='resolved', decision_note='تم إغلاق الملاحظة من مراقب الشبكة.' WHERE id={$id} LIMIT 1")) {
      $actor = $conn->real_escape_string((string)($_SESSION['admin_username'] ?? $_SESSION['admin_user'] ?? 'admin'));
      @ $conn->query("INSERT INTO security_monitor_event_actions(event_id,action_name,action_note,actor)
        SELECT id,'resolve','تم إغلاق الملاحظة من مراقب الشبكة.','{$actor}'
        FROM security_monitor_event_log
        WHERE source_type='watch' AND source_id={$id} AND event_date=CURDATE() AND review_status='pending'");
      @ $conn->query("UPDATE security_monitor_event_log
        SET review_status='resolved',review_action='resolve',review_note='تم إغلاق الملاحظة من مراقب الشبكة.',
            reviewed_by='{$actor}',reviewed_at=NOW(),updated_at=NOW()
        WHERE source_type='watch' AND source_id={$id} AND event_date=CURDATE() AND review_status='pending'");
      $msg = 'تم إغلاق ملاحظة المراقبة.';
    } else {
      $err = 'تعذر إغلاق الملاحظة.';
    }
  } elseif ($act === 'allow') {
    $kind = (string)($_POST['kind'] ?? '');
    if (in_array($kind, ['mac','mac_ip'], true)) {
      $err = 'تم إيقاف سماح MAC. استخدم زر اعتماد مالك MAC لحسم التعارض بدلاً من إخفائه.';
    } else {
      $ok = smp_allow($conn, $kind, (string)($_POST['value1'] ?? ''), (string)($_POST['value2'] ?? ''), (string)($_POST['label'] ?? ''), (string)($_POST['note'] ?? ''));
      if ($ok) $msg = 'تمت الإضافة إلى قائمة السماح وتصفية التنبيهات المطابقة.'; else $err = 'تعذر إضافة عنصر السماح.';
    }
  } elseif ($act === 'claim_mac_owner') {
    $mac = (string)($_POST['mac'] ?? '');
    $sid = (int)($_POST['subscriber_id'] ?? 0);
    if (function_exists('uamac_claim_owner')) {
      $res = uamac_claim_owner($conn, $mac, $sid, true, 'security_monitor_manual');
      if (!empty($res['ok'])) {
        $msg = 'تم اعتماد مالك MAC وتنظيف التعارضات التشغيلية القديمة.';
      } else {
        $err = 'تعذر اعتماد مالك MAC: ' . h((string)($res['message'] ?? 'خطأ غير معروف'));
      }
    } else {
      $err = 'مكتبة حسم ملكية MAC غير محملة.';
    }
  }
}

$focusType = smp_s($_GET['type'] ?? '', 30);
$focusId = (int)($_GET['id'] ?? 0);
$summary = sm_security_summary($conn);
$identifying = (int)$summary['identifying'];
$suspect = (int)$summary['suspect'];
$confirmed = (int)$summary['confirmed'];
$pppoeOpen = (int)$summary['pppoe_conflicts'];
$pppoeSuspect = smp_scalar($conn, "SELECT COUNT(*) FROM subscriber_network_alerts WHERE is_open=1 AND source IN ('pppoe_match','pppoe_secret','pppoe_duplicate_login') AND COALESCE(NULLIF(stage,''),'confirmed')<>'confirmed' AND last_seen_at>=CURDATE() AND last_seen_at<DATE_ADD(CURDATE(),INTERVAL 1 DAY)");
$adminOpen = (int)$summary['dangerous_logins'];
$allowCount = smp_scalar($conn, "SELECT COUNT(*) FROM mtwatch_allowlist WHERE enabled=1");
$watchRows = smp_rows($conn, "SELECT * FROM network_ip_watch WHERE is_pppoe_active=0 AND is_allowlisted=0 AND stage IN ('confirmed','suspect','identifying') AND last_seen_at>=CURDATE() AND last_seen_at<DATE_ADD(CURDATE(),INTERVAL 1 DAY) ORDER BY FIELD(stage,'confirmed','suspect','identifying'), last_seen_at DESC LIMIT 80");
$pppoeRows = smp_rows($conn, "SELECT * FROM subscriber_network_alerts WHERE is_open=1 AND source IN ('pppoe_duplicate_login','pppoe_match','pppoe_secret') AND last_seen_at>=CURDATE() AND last_seen_at<DATE_ADD(CURDATE(),INTERVAL 1 DAY) ORDER BY FIELD(source,'pppoe_duplicate_login','pppoe_match','pppoe_secret'), FIELD(COALESCE(NULLIF(stage,''),'confirmed'),'confirmed','suspect','identifying','observed'), last_seen_at DESC, id DESC LIMIT 80");
$networkRows = smp_rows($conn, "SELECT * FROM subscriber_network_alerts WHERE is_open=1 AND COALESCE(NULLIF(stage,''),'confirmed')='confirmed' AND (source IS NULL OR source NOT IN ('pppoe_duplicate_login','pppoe_match','pppoe_secret')) AND last_seen_at>=CURDATE() AND last_seen_at<DATE_ADD(CURDATE(),INTERVAL 1 DAY) ORDER BY last_seen_at DESC, id DESC LIMIT 80");
$adminRows = smp_rows($conn, "SELECT * FROM admin_security_alerts WHERE is_open=1
  AND alert_type IN (
    'login_failed','login_rate_limited','router_login_failed','router_security_warning',
    'router_account_change','router_config_change','router_user_added','router_user_changed',
    'router_user_removed','app_router_credentials_changed'
  )
  AND last_seen_at>=CURDATE() AND last_seen_at<DATE_ADD(CURDATE(),INTERVAL 1 DAY)
  ORDER BY last_seen_at DESC, id DESC LIMIT 60");
$allowRows = smp_rows($conn, "SELECT * FROM mtwatch_allowlist ORDER BY enabled DESC, id DESC LIMIT 80");
$eventLogStatus = smp_s($_GET['log_status'] ?? 'pending', 30);
if (!in_array($eventLogStatus, ['pending','ignored','allowed','resolved','deleted','all'], true)) $eventLogStatus = 'pending';
$eventLogDays = max(1, min(365, (int)($_GET['log_days'] ?? 30)));
$eventLogRows = function_exists('sm_event_log_rows') ? sm_event_log_rows($conn, $eventLogStatus, $eventLogDays, 300) : [];
$eventLogStats = ['pending'=>0,'ignored'=>0,'allowed'=>0,'resolved'=>0,'deleted'=>0];
$eventLogDaysBack = $eventLogDays - 1;
foreach (smp_rows($conn, "SELECT review_status,COUNT(*) total FROM security_monitor_event_log WHERE event_date>=DATE_SUB(CURDATE(),INTERVAL {$eventLogDaysBack} DAY) GROUP BY review_status") as $eventStat) {
  $key = (string)($eventStat['review_status'] ?? '');
  if (array_key_exists($key, $eventLogStats)) $eventLogStats[$key] = (int)($eventStat['total'] ?? 0);
}
$status = ($confirmed + $adminOpen > 0) ? 'danger' : (($suspect + $pppoeSuspect) > 0 ? 'warn' : ($identifying > 0 ? 'info' : 'ok'));
$statusLabel = ($status === 'danger') ? 'يوجد تنبيه مؤكد' : (($status === 'warn') ? 'يوجد اشتباه قيد التحقق' : (($status === 'info') ? 'قيد التعرف' : 'مستقر'));
if ($uaAndroidSecurityMonitor) {
  require __DIR__ . '/android_security_monitor.php';
  require_once __DIR__ . '/footer.php';
  exit;
}
?>
<div class="content-wrapper ua-manual-page">
  <section class="content">
    <div class="container-fluid">
<div class="secmon-page">
  <section class="secmon-hero">
    <div class="secmon-hero__row">
      <div>
        <h1 class="secmon-title">مراقب الشبكة</h1>
        <div class="secmon-sub">تعرض هذه الصفحة أحداث اليوم فقط، وتُحفظ كل واقعة في سجل معالجة مستقل للمراجعة أو التجاهل أو السماح لاحقاً.</div>
      </div>
      <div class="secmon-status <?= h($status) ?>"><span class="secmon-dot"></span><span><?= h($statusLabel) ?></span></div>
    </div>
    <div class="secmon-kpis">
      <div class="secmon-kpi info"><span>اشتباه اليوم</span><strong><?= (int)($identifying + $suspect) ?></strong></div>
      <div class="secmon-kpi warn"><span>تعارض PPPoE اليوم</span><strong><?= (int)$pppoeOpen ?></strong></div>
      <div class="secmon-kpi danger"><span>تغيّر الحساب اليوم</span><strong><?= (int)$summary['account_changes'] ?></strong></div>
      <div class="secmon-kpi danger"><span>تغيّر الراوتر اليوم</span><strong><?= (int)$summary['router_changes'] ?></strong></div>
      <div class="secmon-kpi warn"><span>تعارض MAC اليوم</span><strong><?= (int)$summary['mac_conflicts'] ?></strong></div>
      <div class="secmon-kpi danger"><span>دخول خطر اليوم</span><strong><?= (int)$summary['dangerous_logins'] ?></strong></div>
    </div>
  </section>

  <?php if (!empty($macAllowDisabled)): ?><div class="secmon-msg ok">تم إيقاف <?= (int)$macAllowDisabled ?> سماح MAC قديم حتى تتم مراجعة الملكية من مراقب الشبكة.</div><?php endif; ?>
  <?php if ($msg): ?><div class="secmon-msg ok"><?= h($msg) ?></div><?php endif; ?>
  <?php if ($err): ?><div class="secmon-msg err"><?= h($err) ?></div><?php endif; ?>

  <section class="secmon-card">
    <div class="secmon-card__head"><h2>مرحلة التعرف والاشتباه اليوم</h2><span class="secmon-muted">تُرحّل تلقائياً إلى سجل المعالجة، ولا تبقى في الملخص بعد انتهاء اليوم.</span></div>
    <div class="secmon-table-wrap"><table class="secmon-table"><thead><tr><th>الحالة</th><th>IP</th><th>MAC</th><th>Username</th><th>Interface</th><th>أول ظهور</th><th>آخر ظهور</th><th>التكرار</th><th>سبب التصنيف</th><th>قرار</th></tr></thead><tbody>
      <?php if (!$watchRows): ?><tr><td colspan="10" class="secmon-muted">لا توجد حالات قيد التعرف أو الاشتباه حالياً.</td></tr><?php else: foreach ($watchRows as $r): ?>
        <?php $st=(string)($r['stage']??'observed'); $cls=smp_stage_class($st); $rid=(int)($r['id']??0); ?>
        <tr id="watch-<?= $rid ?>" class="<?= ($focusType==='watch' && $focusId===$rid)?'secmon-focus':'' ?>">
          <td><span class="secmon-pill <?= h($cls) ?>"><?= h(smp_stage_label($st)) ?></span></td>
          <td class="secmon-ltr"><?= h($r['ip_address'] ?? '') ?></td>
          <td class="secmon-ltr"><?= h($r['mac_address'] ?? '') ?></td>
          <td><?= h($r['username'] ?? '') ?></td>
          <td><?= h($r['interface_name'] ?? '') ?></td>
          <td class="secmon-ltr"><?= h($r['first_seen_at'] ?? '') ?></td>
          <td class="secmon-ltr"><?= h($r['last_seen_at'] ?? '') ?></td>
          <td><?= (int)($r['seen_count'] ?? 1) ?></td>
          <td><?= h($r['decision_note'] ?? '') ?></td>
          <td><div class="secmon-actions">
            <?= smp_allow_buttons((string)($r['mac_address']??''), (string)($r['ip_address']??''), (string)($r['username']??''), 'مراقبة') ?>
            <form method="post" class="secmon-inline"><?= smp_csrf_input() ?><input type="hidden" name="act" value="close_watch"><input type="hidden" name="id" value="<?= $rid ?>"><button class="secmon-btn secmon-btn--red" type="submit">إغلاق</button></form>
          </div></td>
        </tr>
      <?php endforeach; endif; ?>
    </tbody></table></div>
  </section>

  <section class="secmon-card">
    <div class="secmon-card__head"><h2>تعارضات PPPoE ومحاولات الدخول المكررة اليوم</h2><span class="secmon-muted">تطابق حسابات PPPoE، الحالة بين البرنامج والمايكروتك، ومحاولة دخول نفس الحساب من جهاز آخر.</span></div>
    <div class="secmon-table-wrap"><table class="secmon-table"><thead><tr><th>#</th><th>الحالة</th><th>النوع</th><th>العنوان</th><th>التفاصيل</th><th>Username</th><th>IP</th><th>MAC</th><th>آخر ظهور</th><th>التكرار</th><th>قرار</th></tr></thead><tbody>
      <?php if (!$pppoeRows): ?><tr><td colspan="11" class="secmon-muted">لا توجد تعارضات PPPoE مفتوحة حالياً.</td></tr><?php else: foreach ($pppoeRows as $r): ?>
        <?php $sev=(string)($r['severity']??'warn'); $rid=(int)($r['id']??0); $st=(string)($r['stage']??'confirmed'); ?>
        <tr id="network-<?= $rid ?>" class="<?= ($focusType==='network' && $focusId===$rid)?'secmon-focus':'' ?>">
          <td><?= $rid ?></td>
          <td><span class="secmon-pill <?= h(smp_stage_class($st)) ?>"><?= h(smp_stage_label($st)) ?></span></td>
          <td><span class="secmon-pill <?= h($sev==='danger'?'danger':($sev==='warn'?'warn':'info')) ?>"><?= h($r['source'] ?? 'pppoe') ?></span></td>
          <td><?= h($r['title'] ?? '') ?></td>
          <td><?= h($r['message'] ?? '') ?></td>
          <td><?= h($r['username'] ?? '') ?></td>
          <td class="secmon-ltr"><?= h($r['ip_address'] ?? '') ?></td>
          <td class="secmon-ltr"><?= h($r['mac_address'] ?? '') ?></td>
          <td class="secmon-ltr"><?= h($r['last_seen_at'] ?? '') ?></td>
          <td><?= (int)($r['hit_count'] ?? 1) ?></td>
          <td><div class="secmon-actions">
            <?= smp_allow_buttons((string)($r['mac_address']??''), (string)($r['ip_address']??''), (string)($r['username']??''), 'تعارض PPPoE') ?>
            <?= smp_mac_claim_buttons($conn, $r) ?>
            <?php if ((int)($r['subscriber_id'] ?? 0) > 0): ?><a class="secmon-btn secmon-btn--gold" href="subscribers_history.php?id=<?= (int)$r['subscriber_id'] ?>">فتح المشترك</a><?php endif; ?>
            <form method="post" class="secmon-inline"><?= smp_csrf_input() ?><input type="hidden" name="act" value="close_network"><input type="hidden" name="id" value="<?= $rid ?>"><button class="secmon-btn secmon-btn--red" type="submit">إغلاق</button></form>
          </div></td>
        </tr>
      <?php endforeach; endif; ?>
    </tbody></table></div>
  </section>

  <section class="secmon-card">
    <div class="secmon-card__head"><h2>التنبيهات المؤكدة اليوم</h2><span class="secmon-muted">هذه فقط تظهر في زر التنبيهات، مع الاحتفاظ بنسخة منها في سجل المعالجة.</span></div>
    <div class="secmon-table-wrap"><table class="secmon-table"><thead><tr><th>#</th><th>الشدة</th><th>العنوان</th><th>التفاصيل</th><th>IP</th><th>MAC</th><th>Username</th><th>آخر ظهور</th><th>التكرار</th><th>قرار</th></tr></thead><tbody>
      <?php if (!$networkRows): ?><tr><td colspan="10" class="secmon-muted">لا توجد تنبيهات شبكة مؤكدة مفتوحة.</td></tr><?php else: foreach ($networkRows as $r): ?>
        <?php $sev=(string)($r['severity']??'warn'); $rid=(int)($r['id']??0); ?>
        <tr id="network-<?= $rid ?>" class="<?= ($focusType==='network' && $focusId===$rid)?'secmon-focus':'' ?>">
          <td><?= $rid ?></td><td><span class="secmon-pill <?= h($sev==='danger'?'danger':($sev==='warn'?'warn':'info')) ?>"><?= h($sev) ?></span></td>
          <td><?= h($r['title'] ?? '') ?></td><td><?= h($r['message'] ?? '') ?></td><td class="secmon-ltr"><?= h($r['ip_address'] ?? '') ?></td><td class="secmon-ltr"><?= h($r['mac_address'] ?? '') ?></td><td><?= h($r['username'] ?? '') ?></td><td class="secmon-ltr"><?= h($r['last_seen_at'] ?? '') ?></td><td><?= (int)($r['hit_count'] ?? 1) ?></td>
          <td><div class="secmon-actions">
            <?= smp_allow_buttons((string)($r['mac_address']??''), (string)($r['ip_address']??''), (string)($r['username']??''), 'تنبيه') ?>
            <?= smp_mac_claim_buttons($conn, $r) ?>
            <?php if ((int)($r['subscriber_id'] ?? 0) > 0): ?><a class="secmon-btn secmon-btn--gold" href="subscribers_history.php?id=<?= (int)$r['subscriber_id'] ?>">فتح المشترك</a><?php endif; ?>
            <form method="post" class="secmon-inline"><?= smp_csrf_input() ?><input type="hidden" name="act" value="close_network"><input type="hidden" name="id" value="<?= $rid ?>"><button class="secmon-btn secmon-btn--red" type="submit">إغلاق</button></form>
          </div></td>
        </tr>
      <?php endforeach; endif; ?>
    </tbody></table></div>
  </section>

  <section class="secmon-card">
    <div class="secmon-card__head"><h2>أحداث أمان لوحة الإدارة والراوتر اليوم</h2><a class="secmon-btn secmon-btn--soft" href="security_alerts.php">فتح سجل الدخول</a></div>
    <div class="secmon-table-wrap"><table class="secmon-table"><thead><tr><th>#</th><th>الشدة</th><th>النوع</th><th>العنوان</th><th>المستخدم</th><th>IP</th><th>التكرار</th><th>آخر ظهور</th><th>المصدر</th><th>قرار</th></tr></thead><tbody>
      <?php if (!$adminRows): ?><tr><td colspan="10" class="secmon-muted">لا توجد أحداث أمان مفتوحة للوحة أو الراوتر.</td></tr><?php else: foreach ($adminRows as $r): ?>
        <?php $sev=(string)($r['severity']??'warn'); $rid=(int)($r['id']??0); ?>
        <?php $sevCls = $sev === 'danger' ? 'danger' : ($sev === 'info' ? 'info' : 'warn'); ?>
          <tr id="admin-<?= $rid ?>" class="<?= ($focusType==='admin' && $focusId===$rid)?'secmon-focus':'' ?>"><td><?= $rid ?></td><td><span class="secmon-pill <?= h($sevCls) ?>"><?= h($sev) ?></span></td><td class="secmon-ltr"><?= h($r['alert_type'] ?? '') ?></td><td><?= h($r['title'] ?? '') ?></td><td><?= h($r['username'] ?? '') ?></td><td class="secmon-ltr"><?= h($r['ip_address'] ?? '') ?></td><td><?= (int)($r['hit_count'] ?? 1) ?></td><td class="secmon-ltr"><?= h($r['last_seen_at'] ?? '') ?></td><td class="secmon-ltr ua-u-one-line-260" title="<?= h($r['user_agent'] ?? '') ?>"><?= h($r['user_agent'] ?? '') ?></td><td><form method="post" class="secmon-inline"><?= smp_csrf_input() ?><input type="hidden" name="act" value="close_admin"><input type="hidden" name="id" value="<?= $rid ?>"><button class="secmon-btn secmon-btn--red" type="submit">إغلاق</button></form></td></tr>
      <?php endforeach; endif; ?>
    </tbody></table></div>
  </section>

  <section class="secmon-card secmon-event-log" id="event-log">
    <div class="secmon-card__head">
      <div>
        <h2>سجل معالجة أحداث مراقب الشبكة</h2>
        <span class="secmon-muted">سجل دائم مستقل عن ملخص اليوم. كل قرار يُحفظ مع المستخدم والتاريخ.</span>
      </div>
      <form method="get" class="secmon-log-filter">
        <label><span>الحالة</span><select name="log_status" onchange="this.form.submit()">
          <?php foreach (['pending'=>'بانتظار المعالجة','ignored'=>'متجاهلة','allowed'=>'مسموحة','resolved'=>'تمت معالجتها','deleted'=>'محذوفة','all'=>'كل الحالات'] as $logValue=>$logLabel): ?>
            <option value="<?= h($logValue) ?>" <?= $eventLogStatus===$logValue?'selected':'' ?>><?= h($logLabel) ?></option>
          <?php endforeach; ?>
        </select></label>
        <label><span>الفترة</span><select name="log_days" onchange="this.form.submit()">
          <?php foreach ([7=>'7 أيام',30=>'30 يوماً',90=>'90 يوماً',365=>'سنة'] as $daysValue=>$daysLabel): ?>
            <option value="<?= (int)$daysValue ?>" <?= $eventLogDays===$daysValue?'selected':'' ?>><?= h($daysLabel) ?></option>
          <?php endforeach; ?>
        </select></label>
      </form>
    </div>
    <div class="secmon-log-stats">
      <span class="warn"><b><?= (int)$eventLogStats['pending'] ?></b> بانتظار المعالجة</span>
      <span><b><?= (int)$eventLogStats['ignored'] ?></b> متجاهلة</span>
      <span class="ok"><b><?= (int)$eventLogStats['allowed'] ?></b> مسموحة</span>
      <span class="ok"><b><?= (int)$eventLogStats['resolved'] ?></b> معالجة</span>
      <span class="danger"><b><?= (int)$eventLogStats['deleted'] ?></b> محذوفة</span>
    </div>
    <div class="secmon-table-wrap"><table class="secmon-table secmon-log-table"><thead><tr><th>اليوم</th><th>الحالة</th><th>الفئة</th><th>الحدث</th><th>العنوان والتفاصيل</th><th>الحساب / IP / MAC</th><th>آخر ظهور</th><th>التكرار</th><th>المعالجة</th></tr></thead><tbody>
      <?php if (!$eventLogRows): ?><tr><td colspan="9" class="secmon-muted">لا توجد أحداث مطابقة لفلتر السجل.</td></tr><?php else: foreach ($eventLogRows as $event): ?>
        <?php
          $eventId=(int)$event['id'];
          $reviewStatus=(string)($event['review_status']??'pending');
          $reviewClass=$reviewStatus==='pending'?'warn':($reviewStatus==='deleted'?'danger':($reviewStatus==='ignored'?'muted':'ok'));
          $canAllow=trim((string)($event['username']??''))!=='' || trim((string)($event['ip_address']??''))!=='';
        ?>
        <tr>
          <td class="secmon-ltr"><?= h((string)$event['event_date']) ?></td>
          <td><span class="secmon-pill <?= h($reviewClass) ?>"><?= h(smp_review_label($reviewStatus)) ?></span></td>
          <td><?= h(smp_category_label((string)$event['category'])) ?></td>
          <td class="secmon-ltr"><?= h((string)$event['event_type']) ?></td>
          <td><b><?= h((string)$event['title']) ?></b><small><?= h((string)$event['message']) ?></small><?php if(trim((string)($event['review_note']??''))!==''): ?><em><?= h((string)$event['review_note']) ?></em><?php endif; ?></td>
          <td><div class="secmon-event-identities"><?php if(!empty($event['username'])):?><span><?= h((string)$event['username']) ?></span><?php endif; ?><?php if(!empty($event['ip_address'])):?><span class="secmon-ltr"><?= h((string)$event['ip_address']) ?></span><?php endif; ?><?php if(!empty($event['mac_address'])):?><span class="secmon-ltr"><?= h((string)$event['mac_address']) ?></span><?php endif; ?></div></td>
          <td class="secmon-ltr"><?= h((string)$event['last_seen_at']) ?></td>
          <td><?= (int)$event['hit_count'] ?></td>
          <td>
            <?php if($reviewStatus==='pending'): ?>
            <form method="post" class="secmon-review-form">
              <?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="<?= $eventId ?>">
              <input name="review_note" placeholder="ملاحظة القرار (اختياري)">
              <div>
                <button name="review_action" value="resolve" class="secmon-btn secmon-btn--gold" type="submit">معالجة</button>
                <button name="review_action" value="ignore" class="secmon-btn secmon-btn--soft" type="submit">تجاهل</button>
                <button name="review_action" value="allow" class="secmon-btn secmon-btn--soft" type="submit" <?= $canAllow?'':'disabled' ?>>سماح</button>
                <button name="review_action" value="delete" class="secmon-btn secmon-btn--red" type="submit" onclick="return confirm('حذف الحدث من قائمة العمل؟ سيبقى القرار موثقاً في السجل.')">حذف</button>
              </div>
            </form>
            <?php else: ?>
              <div class="secmon-reviewed"><b><?= h((string)($event['reviewed_by']?:'النظام')) ?></b><span class="secmon-ltr"><?= h((string)$event['reviewed_at']) ?></span></div>
            <?php endif; ?>
          </td>
        </tr>
      <?php endforeach; endif; ?>
    </tbody></table></div>
  </section>

  <section class="secmon-card">
    <div class="secmon-card__head"><h2>قائمة السماح الحالية</h2><a class="secmon-btn secmon-btn--soft" href="mtwatch_allowlist.php">إدارة متقدمة</a></div>
    <div class="secmon-table-wrap"><table class="secmon-table"><thead><tr><th>#</th><th>الحالة</th><th>النوع</th><th>القيمة</th><th>القيمة الثانية</th><th>الاسم</th><th>الملاحظة</th></tr></thead><tbody>
      <?php if (!$allowRows): ?><tr><td colspan="7" class="secmon-muted">لا توجد عناصر سماح.</td></tr><?php else: foreach ($allowRows as $r): ?>
        <tr><td><?= (int)$r['id'] ?></td><td><span class="secmon-pill <?= ((int)($r['enabled']??0)===1?'ok':'muted') ?>"><?= ((int)($r['enabled']??0)===1?'فعال':'متوقف') ?></span></td><td><?= h($r['kind']??'') ?></td><td class="secmon-ltr"><?= h($r['value1']??'') ?></td><td class="secmon-ltr"><?= h($r['value2']??'') ?></td><td><?= h($r['label']??'') ?></td><td><?= h($r['note']??'') ?></td></tr>
      <?php endforeach; endif; ?>
    </tbody></table></div>
  </section>
</div>
<script>
(function(){
  var el = document.querySelector('.secmon-focus');
  if (el) setTimeout(function(){ try { el.scrollIntoView({block:'center', behavior:'smooth'}); } catch(e) { el.scrollIntoView(); } }, 250);
})();
</script>
    </div>
  </section>
</div>
<?php require_once __DIR__ . '/footer.php'; ?>
