<?php
require_once __DIR__.'/../config/config.php';
require_once __DIR__.'/../config/database.php';
require_once __DIR__.'/../includes/functions.php';

$limit = max(10, min(500, (int)($_GET['limit'] ?? 150)));
$processed = 0;
$alerts = 0;
try {
    if (afStage24TableExists($pdo,'af_usuarios')) {
        $st = $pdo->prepare("SELECT id FROM af_usuarios WHERE status IN (1,2) ORDER BY COALESCE(stage24_last_audit_at,'1970-01-01') ASC,id DESC LIMIT {$limit}");
        $st->execute();
        foreach ($st->fetchAll(PDO::FETCH_COLUMN) ?: [] as $uid) {
            $processed++;
            $risk = afStage24RefreshUserRisk($pdo, (int)$uid);
            $analysis = afStage24AnalyzeUserBehavior($pdo, (int)$uid);
            if (!empty($analysis['signals'])) $alerts++;
        }
    }
    afStage24AuditLog($pdo,'stage24_cron_completed','cron','etapa24-auditoria-rotina',[],['processed'=>$processed,'behavior_alerts'=>$alerts],['actor_type'=>'cron','severity'=>'info','source'=>'cron_stage24']);
    echo "OK Etapa 24: {$processed} usuários analisados, {$alerts} sinais.\n";
} catch (Throwable $e) {
    if (function_exists('afStage24AuditLog')) afStage24AuditLog($pdo,'stage24_cron_failed','cron','etapa24-auditoria-rotina',[],['error'=>$e->getMessage()],['actor_type'=>'cron','severity'=>'high','source'=>'cron_stage24']);
    http_response_code(500);
    echo "ERRO Etapa 24: ".$e->getMessage()."\n";
}
