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

$isPost = (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'POST');
$isSummaryMode = ((string)($_GET['summary'] ?? '') === '1');

require_once __DIR__ . '/../auth.php';
require_once __DIR__ . '/../db_bootstrap.php';
require_once __DIR__ . '/../security_monitor_lib.php';
if (!$isSummaryMode || $isPost) {
  require_once __DIR__ . '/../subscriber_mikrotik_watch_lib.php';
  require_once __DIR__ . '/../security_alerts_lib.php';
  require_once __DIR__ . '/../mac_ownership_lib.php';
}

header('Content-Type: application/json; charset=utf-8');
require_login('login.php');
if (function_exists('ensure_db')) ensure_db(true);
$conn = $GLOBALS['conn'] ?? null;
if (!($conn instanceof mysqli)) { echo json_encode(['ok'=>false,'message'=>'db'], JSON_UNESCAPED_UNICODE); exit; }

if (!$isSummaryMode || $isPost) {
  if (function_exists('mtwatch_ensure_schema')) mtwatch_ensure_schema($conn);
  if (function_exists('ua_security_alerts_ensure_schema')) 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);

function sm_json($arr){ echo json_encode($arr, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES); exit; }
$securityWarmup = ['ok'=>true,'status'=>'not_requested'];
$securityCleanup = function_exists('sm_cleanup_stale_security_alerts') ? sm_cleanup_stale_security_alerts($conn, 3, 30) : [];

if ($isPost) {
  if (function_exists('ua_csrf_verify') && !ua_csrf_verify()) {
    http_response_code(403);
    sm_json(['ok'=>false,'message'=>'csrf_expired']);
  }
  $act = sm_str($_POST['act'] ?? '', 60);
  if ($act === 'close_network') {
    $id = (int)($_POST['id'] ?? 0);
    sm_json(function_exists('sm_close_network_alert') ? sm_close_network_alert($conn, $id, 'closed', 'Closed from security monitor.') : ['ok'=>false,'message'=>'missing_close_helper']);
  }
  if ($act === 'close_admin') {
    $id = (int)($_POST['id'] ?? 0);
    sm_json(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) : false)]);
  }
  if ($act === 'allow') {
    $kind = (string)($_POST['kind'] ?? '');
    if (in_array($kind, ['mac','mac_ip'], true)) sm_json(['ok'=>false,'message'=>'mac_allow_disabled_use_claim_owner']);
    $ok = sm_insert_allow($conn, $kind, (string)($_POST['value1'] ?? ''), (string)($_POST['value2'] ?? ''), (string)($_POST['label'] ?? ''), (string)($_POST['note'] ?? ''));
    sm_json(['ok'=>$ok]);
  }
  if ($act === 'claim_mac_owner') {
    if (!function_exists('uamac_claim_owner')) sm_json(['ok'=>false,'message'=>'mac_ownership_not_loaded']);
    $res = uamac_claim_owner($conn, (string)($_POST['mac'] ?? ''), (int)($_POST['subscriber_id'] ?? 0), true, 'security_monitor_api');
    sm_json($res);
  }
  if ($act === 'review_event') {
    $actor = (string)($_SESSION['admin_username'] ?? $_SESSION['admin_user'] ?? 'admin');
    sm_json(function_exists('sm_event_log_review')
      ? sm_event_log_review(
          $conn,
          (int)($_POST['event_id'] ?? 0),
          sm_str($_POST['review_action'] ?? '', 30),
          sm_str($_POST['review_note'] ?? '', 2000),
          $actor
        )
      : ['ok'=>false,'message'=>'event_log_unavailable']);
  }
}

$allowWarmup = !$isSummaryMode && ((string)($_GET['warmup'] ?? '1') !== '0');
if (!$isPost && $allowWarmup && function_exists('sm_security_warmup_maybe')) {
  $securityWarmup = sm_security_warmup_maybe($conn, 300, 600);
}

$summary = sm_security_summary($conn);
$backgroundWorker = function_exists('sm_background_worker_health')
  ? sm_background_worker_health('monitor', 180)
  : ['configured'=>false,'ok'=>false,'stale'=>true,'message'=>'Background monitor health helper missing.'];
$ownershipConflict = (int)$summary['mac_conflicts'];
$ownershipRows = $isSummaryMode ? [] : sm_rows($conn, "SELECT mac_address, subscriber_id, username, status, confidence, resolution_source, reason, candidates_json, last_seen_at FROM mtwatch_mac_ownership WHERE status='conflict' ORDER BY last_seen_at DESC LIMIT 30");

$identifying = (int)$summary['identifying'];
$suspect = (int)$summary['suspect'];
$confirmedNetwork = (int)$summary['confirmed'];
$pppoeOpen = (int)$summary['pppoe_conflicts'];
$pppoeSuspect = 0;
$pppoeDuplicate = sm_scalar($conn, "SELECT COUNT(*) FROM subscriber_network_alerts WHERE is_open=1 AND source='pppoe_duplicate_login' AND last_seen_at>=CURDATE() AND last_seen_at<DATE_ADD(CURDATE(),INTERVAL 1 DAY)");
$adminOpen = (int)$summary['dangerous_logins'];
$allowCount = sm_scalar($conn, "SELECT COUNT(*) FROM mtwatch_allowlist WHERE enabled=1");
$latestWatch = sm_rows($conn, "SELECT ip_address, mac_address, username, stage, decision_note, last_seen_at FROM network_ip_watch WHERE stage IN ('confirmed','suspect','identifying','active') AND last_seen_at>=CURDATE() AND last_seen_at<DATE_ADD(CURDATE(),INTERVAL 1 DAY) ORDER BY last_seen_at DESC, id DESC LIMIT 1");
$latestNetwork = sm_rows($conn, "SELECT title, message, severity, last_seen_at FROM subscriber_network_alerts WHERE is_open=1 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 1");
$latestAdmin = sm_rows($conn, "SELECT title, message, severity, last_seen_at 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 1");

$watchRows = [];
$pppoeAlerts = [];
$networkAlerts = [];
$adminAlerts = [];
if (!$isSummaryMode) {
  $watchRows = sm_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 40");
  $pppoeAlerts = sm_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 40");
  $networkAlerts = sm_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 40");
  $adminAlerts = sm_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 30");
}

$lastText = 'لا توجد أحداث أمنية حديثة';
$lastAt = '';
if (!empty($latestNetwork[0])) { $lastText = (string)($latestNetwork[0]['title'] ?? 'تنبيه شبكة مؤكد'); $lastAt = (string)($latestNetwork[0]['last_seen_at'] ?? ''); }
elseif (!empty($latestAdmin[0])) { $lastText = (string)($latestAdmin[0]['title'] ?? 'تنبيه أمان'); $lastAt = (string)($latestAdmin[0]['last_seen_at'] ?? ''); }
elseif (!empty($latestWatch[0])) { $lw = $latestWatch[0]; $lastText = 'قيد المطابقة: ' . ((string)($lw['mac_address'] ?? '')) . ((string)($lw['ip_address'] ?? '') !== '' ? ' / ' . (string)$lw['ip_address'] : ''); $lastAt = (string)($lw['last_seen_at'] ?? ''); }

$payload = [
  'ok'=>true,
  'summary'=>array_merge($summary, [
    'allowlist'=>$allowCount,
    'pppoe_duplicate_login'=>$pppoeDuplicate,
    'warmup'=>$securityWarmup,
    'cleanup'=>$securityCleanup,
    'worker'=>$backgroundWorker,
    'last_text'=>$lastText,
    'last_seen_at'=>$lastAt,
  ]),
  'warmup'=>$securityWarmup,
  'watch_rows'=>$watchRows,
  'pppoe_alerts'=>$pppoeAlerts,
  'network_alerts'=>$networkAlerts,
  'admin_alerts'=>$adminAlerts,
  'ownership_conflicts'=>$ownershipRows,
];

if ($isSummaryMode) {
  unset($payload['watch_rows'], $payload['pppoe_alerts'], $payload['network_alerts'], $payload['admin_alerts'], $payload['ownership_conflicts']);
}

sm_json($payload);
