<?php
@ini_set('display_errors','0');
error_reporting(E_ALL & ~E_WARNING & ~E_NOTICE);
if (session_status() === PHP_SESSION_NONE) session_start();

require_once __DIR__ . '/../auth.php';
if (function_exists('require_login')) require_login('login.php');
require_once __DIR__ . '/../db_bootstrap.php';
require_once __DIR__ . '/../subscriber_mikrotik_watch_lib.php';
require_once __DIR__ . '/../security_monitor_lib.php';

header('Content-Type: application/json; charset=utf-8');
if (session_status() === PHP_SESSION_ACTIVE) { @session_write_close(); }

if (function_exists('ensure_db')) ensure_db(true);
$conn = $GLOBALS['conn'] ?? null;
if (!($conn instanceof mysqli)) { echo json_encode(['ok'=>false,'message'=>'db']); exit; }

try {
  if (function_exists('sm_cleanup_stale_security_alerts')) sm_cleanup_stale_security_alerts($conn, 3, 30);
  // مهم للأداء: هذا الملف يُطلب من الشريط العلوي كل دقيقة.
  // لا نفتح اتصال MikroTik من هنا نهائياً، نقرأ التنبيهات المسجلة فقط.
  // تشغيل الفحص يتم عبر admin/cron/mikrotik_watch_worker.php.
  $alerts = function_exists('mtwatch_recent_alerts') ? mtwatch_recent_alerts($conn, 12) : [];
  $out = [];
  foreach ($alerts as $a) {
    $out[] = [
      'id' => (int)($a['id'] ?? 0),
      'alert_key' => (string)($a['alert_key'] ?? ''),
      'severity' => (string)($a['severity'] ?? 'warn'),
      'title' => (string)($a['title'] ?? 'تنبيه'),
      'message' => (string)($a['message'] ?? ''),
      'subscriber_id' => (int)($a['subscriber_id'] ?? 0),
      'username' => (string)($a['username'] ?? ''),
      'mac_address' => (string)($a['mac_address'] ?? ''),
      'ip_address' => (string)($a['ip_address'] ?? ''),
      'last_seen_at' => (string)($a['last_seen_at'] ?? ''),
      'hit_count' => (int)($a['hit_count'] ?? 1),
      'href' => (string)($a['href'] ?? ''),
    ];
  }
  echo json_encode(['ok'=>true, 'count'=>count($out), 'alerts'=>$out], JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);
} catch (Throwable $e) {
  echo json_encode(['ok'=>false, 'message'=>$e->getMessage()], JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);
}
