<?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';
require_once __DIR__ . '/../db_bootstrap.php';
require_once __DIR__ . '/../security_alerts_lib.php';
require_once __DIR__ . '/../security_monitor_lib.php';

header('Content-Type: application/json; charset=utf-8');
require_login('login.php');
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','count'=>0,'alerts'=>[]], JSON_UNESCAPED_UNICODE); exit; }

try {
  if (function_exists('sm_cleanup_stale_security_alerts')) sm_cleanup_stale_security_alerts($conn, 3, 30);
  $alerts = ua_security_recent_alerts($conn, 10);
  $out = [];
  foreach ($alerts as $a) {
    $out[] = [
      'id' => (int)($a['id'] ?? 0),
      'alert_key' => (string)($a['alert_key'] ?? ''),
      'alert_type' => (string)($a['alert_type'] ?? ''),
      'severity' => (string)($a['severity'] ?? 'warn'),
      'title' => (string)($a['title'] ?? 'تنبيه أمان'),
      'message' => (string)($a['message'] ?? ''),
      'username' => (string)($a['username'] ?? ''),
      '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'] ?? 'security_alerts.php'),
    ];
  }
  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(), 'count'=>0, 'alerts'=>[]], JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);
}
