<?php
// تشغيل يدوي/مجدول لمراقبة MikroTik بدون فتح الواجهة.
// مثال Windows Task Scheduler كل دقيقة: php C:\Apache24\htdocs\mikrotik\admin\cron\mikrotik_watch_worker.php
@ini_set('display_errors','1');
error_reporting(E_ALL & ~E_WARNING & ~E_NOTICE);
@set_time_limit(180);

require_once dirname(__DIR__) . '/db_bootstrap.php';
require_once dirname(__DIR__) . '/subscriber_mikrotik_watch_lib.php';
require_once dirname(__DIR__) . '/security_alerts_lib.php';
require_once dirname(__DIR__) . '/security_monitor_lib.php';

$conn = ensure_db(true);
$out = [];
$out['cleanup'] = function_exists('sm_cleanup_stale_security_alerts') ? sm_cleanup_stale_security_alerts($conn, 3, 30) : ['ok'=>false,'message'=>'cleanup missing'];
$out['fast_active'] = function_exists('mtwatch_run_fast_active_sync') ? mtwatch_run_fast_active_sync($conn, false, 300) : ['ok'=>false,'message'=>'fast active sync missing'];
$out['deep'] = function_exists('mtwatch_run_hourly_deep_sync') ? mtwatch_run_hourly_deep_sync($conn, false) : ['ok'=>false,'message'=>'library missing'];
// فحص IP/MAC خفيف كل دقيقة، لكن خارج صفحة عرض المشتركين حتى لا يثقلها.
$out['ip_scan'] = function_exists('mtwatch_run_network_ip_scan') ? mtwatch_run_network_ip_scan($conn, false, 60) : ['ok'=>false,'message'=>'library missing'];
foreach (['fast_active','deep','ip_scan'] as $part) {
  if (empty($out[$part]['ok'])) {
    $msg = (string)($out[$part]['message'] ?? 'Security monitor worker failed.');
    if (function_exists('sm_record_monitor_issue')) sm_record_monitor_issue($conn, $part, $msg, 'warn');
  }
}
$out['daily_event_log'] = function_exists('sm_sync_daily_event_log')
  ? sm_sync_daily_event_log($conn)
  : ['ok'=>false,'message'=>'daily event log missing'];
if (function_exists('sm_sync_daily_event_log')) {
  $previousDayResult = @$conn->query("SELECT DATE_FORMAT(DATE_SUB(CURDATE(),INTERVAL 1 DAY),'%Y-%m-%d')");
  $previousDayRow = $previousDayResult ? $previousDayResult->fetch_row() : null;
  $previousDay = (string)($previousDayRow[0] ?? '');
  if ($previousDay !== '') $out['previous_day_event_log'] = sm_sync_daily_event_log($conn, $previousDay);
}
$dbTimeResult = @$conn->query("SELECT DATE_FORMAT(NOW(),'%Y-%m-%d %H:%i:%s')");
$dbTimeRow = $dbTimeResult ? $dbTimeResult->fetch_row() : null;
$out['time'] = (string)($dbTimeRow[0] ?? date('Y-m-d H:i:s'));

echo json_encode($out, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES|JSON_PRETTY_PRINT) . PHP_EOL;
