<?php
require_once __DIR__.'/../config/config.php';
require_once __DIR__.'/../config/database.php';
require_once __DIR__.'/../includes/functions.php';
require_once __DIR__.'/../includes/admin_functions.php';
afAdminRequireAuth();

$adminId = afAdminId();
$tab = (string)($_GET['tab'] ?? 'dashboard');
if (!in_array($tab, ['dashboard','alertas','auditoria','usuarios','api'], true)) $tab = 'dashboard';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        if (!validarCsrfToken($_POST[CSRF_TOKEN_NAME] ?? '')) throw new RuntimeException('Sessão expirada.');
        $acao = (string)($_POST['acao'] ?? '');
        if ($acao === 'resolver_alerta') {
            afStage24ResolveAlert($pdo, (int)($_POST['alerta_id'] ?? 0), $adminId, (string)($_POST['status'] ?? 'resolved'), sanitize($_POST['nota'] ?? ''));
            setFlash('success', 'Alerta atualizado.');
            header('Location: '.SITE_URL.'/pages/admin-seguranca-auditoria.php?tab=alertas'); exit;
        }
        if ($acao === 'recalcular_usuario') {
            $uid = (int)($_POST['usuario_id'] ?? 0);
            if ($uid <= 0) throw new RuntimeException('Usuário inválido.');
            $risk = afStage24RefreshUserRisk($pdo, $uid);
            afStage24AnalyzeUserBehavior($pdo, $uid);
            setFlash('success', 'Risco recalculado: '.($risk['score'] ?? 0).' pontos.');
            header('Location: '.SITE_URL.'/pages/admin-seguranca-auditoria.php?tab=usuarios&usuario_id='.$uid); exit;
        }
        if ($acao === 'criar_alerta_manual') {
            $uid = (int)($_POST['usuario_id'] ?? 0);
            $sev = (string)($_POST['severity'] ?? 'medium');
            $titulo = sanitize($_POST['titulo'] ?? 'Alerta manual');
            $msg = sanitize($_POST['mensagem'] ?? '');
            if ($uid <= 0) throw new RuntimeException('Informe o usuário.');
            afStage24SecurityAlert($pdo, 'manual_admin_alert', $sev, $titulo ?: 'Alerta manual', $msg, $uid, $uid, 'admin_manual', 'usuario', $uid, ['admin_id'=>$adminId], $sev === 'critical' ? 25 : 8);
            setFlash('success', 'Alerta manual criado.');
            header('Location: '.SITE_URL.'/pages/admin-seguranca-auditoria.php?tab=usuarios&usuario_id='.$uid); exit;
        }
    } catch (Throwable $e) {
        setFlash('error', $e->getMessage());
        header('Location: '.SITE_URL.'/pages/admin-seguranca-auditoria.php?tab='.$tab); exit;
    }
}

$metricas = afStage24Dashboard($pdo);
$alertas = $tab === 'alertas' || $tab === 'dashboard' ? afStage24ListAlerts($pdo, (string)($_GET['status'] ?? 'open'), 100) : [];
$auditoria = $tab === 'auditoria' || $tab === 'dashboard' ? afStage24RecentAudit($pdo, $tab === 'dashboard' ? 20 : 120) : [];
$apiLogs = [];
if ($tab === 'api' && afStage24TableExists($pdo,'af_api_access_logs')) {
    $st = $pdo->prepare("SELECT l.*,u.nome,u.username,u.aura_id,a.nome admin_nome FROM af_api_access_logs l LEFT JOIN af_usuarios u ON u.id=l.user_id LEFT JOIN af_admin_users a ON a.id=l.admin_user_id ORDER BY l.created_at DESC LIMIT 150");
    $st->execute(); $apiLogs = $st->fetchAll() ?: [];
}
$userDossier = null;
$lookupUserId = (int)($_GET['usuario_id'] ?? 0);
$q = sanitize($_GET['q'] ?? '');
$userResults = [];
if ($tab === 'usuarios') {
    if ($lookupUserId > 0) $userDossier = afStage24UserDossier($pdo, $lookupUserId);
    elseif ($q !== '') {
        $like = '%'.$q.'%';
        $st = $pdo->prepare("SELECT u.id,u.nome,u.username,u.email,u.aura_id,u.status,u.seguranca_status,u.stage24_risk_score,u.stage24_risk_level,r.risk_score,r.risk_level FROM af_usuarios u LEFT JOIN af_user_risk_scores r ON r.user_id=u.id WHERE u.nome LIKE ? OR u.username LIKE ? OR u.email LIKE ? OR u.aura_id LIKE ? ORDER BY COALESCE(r.risk_score,u.stage24_risk_score,0) DESC,u.id DESC LIMIT 50");
        $st->execute([$like,$like,$like,$like]); $userResults = $st->fetchAll() ?: [];
    } else {
        $st = $pdo->prepare("SELECT u.id,u.nome,u.username,u.email,u.aura_id,u.status,u.seguranca_status,u.stage24_risk_score,u.stage24_risk_level,r.risk_score,r.risk_level,r.open_alerts,r.critical_alerts FROM af_usuarios u LEFT JOIN af_user_risk_scores r ON r.user_id=u.id ORDER BY COALESCE(r.risk_score,u.stage24_risk_score,0) DESC,u.id DESC LIMIT 50");
        $st->execute(); $userResults = $st->fetchAll() ?: [];
    }
}

$pageTitle = 'Admin • Segurança e Auditoria';
$showNav = false;
$bodyClass = 'admin-body';
$adminPage = 'auditoria';
require __DIR__.'/../includes/header.php';
?>
<div class="admin-shell">
<?php require __DIR__.'/../includes/admin_nav.php'; ?>
<main class="admin-main stage24-admin">
  <header class="admin-topbar">
    <div><small>ETAPA 24</small><h1>Segurança e Auditoria</h1></div>
    <span class="admin-count">v<?=esc(STAGE24_AUDIT_VERSION)?> • <?=date('d/m/Y H:i')?></span>
  </header>
  <?=renderFlash()?>

  <section class="admin-kpi-grid report-kpis">
    <article><span>🚨</span><div><small>Alertas abertos</small><strong><?=(int)$metricas['alerts_open']?></strong></div></article>
    <article><span>🔥</span><div><small>Críticos</small><strong><?=(int)$metricas['alerts_critical']?></strong></div></article>
    <article><span>🧾</span><div><small>Auditoria 24h</small><strong><?=(int)$metricas['audit_24h']?></strong></div></article>
    <article><span>⛔</span><div><small>APIs bloqueadas 24h</small><strong><?=(int)$metricas['api_denied_24h']?></strong></div></article>
    <article><span>👶</span><div><small>Menores</small><strong><?=(int)$metricas['minors_active']?></strong></div></article>
    <article><span>🎟️</span><div><small>Eventos ativos</small><strong><?=(int)$metricas['events_active']?></strong></div></article>
  </section>

  <nav class="admin-tabs">
    <?php foreach(['dashboard'=>'Resumo','alertas'=>'Alertas','auditoria'=>'Auditoria','usuarios'=>'Dossiê de usuário','api'=>'Logs de API'] as $k=>$v): ?>
      <a class="<?=$tab===$k?'active':''?>" href="?tab=<?=$k?>"><?=$v?></a>
    <?php endforeach; ?>
  </nav>

  <?php if($tab==='dashboard'): ?>
    <section class="admin-grid-two">
      <article class="admin-card"><h2>Alertas prioritários</h2>
        <?php if(!$alertas): ?><p class="admin-empty">Nenhum alerta aberto.</p><?php endif; ?>
        <?php foreach(array_slice($alertas,0,8) as $a): ?>
          <div class="stage24-alert severity-<?=esc($a['severity'])?>"><b><?=esc($a['title'])?></b><small><?=esc($a['severity'])?> • <?=esc($a['alert_type'])?> • <?=date('d/m H:i',strtotime($a['last_seen_at']))?></small><p><?=esc($a['message'])?></p></div>
        <?php endforeach; ?>
      </article>
      <article class="admin-card"><h2>Últimos registros de auditoria</h2>
        <?php foreach($auditoria as $l): ?>
          <div class="stage24-log"><b><?=esc($l['action_key'])?></b><small><?=esc($l['actor_type'])?> • <?=date('d/m H:i',strtotime($l['created_at']))?> • <?=esc($l['entity_type'] ?? '')?> <?=esc($l['entity_id'] ?? '')?></small></div>
        <?php endforeach; ?>
      </article>
    </section>
  <?php endif; ?>

  <?php if($tab==='alertas'): ?>
    <form method="get" class="admin-filter-bar"><input type="hidden" name="tab" value="alertas"><select name="status"><option value="open">Abertos</option><option value="resolved" <?=(($_GET['status']??'')==='resolved')?'selected':''?>>Resolvidos</option><option value="dismissed" <?=(($_GET['status']??'')==='dismissed')?'selected':''?>>Descartados</option><option value="all" <?=(($_GET['status']??'')==='all')?'selected':''?>>Todos</option></select><button>Filtrar</button></form>
    <div class="admin-cards-list">
      <?php if(!$alertas): ?><div class="admin-empty">Nenhum alerta neste filtro.</div><?php endif; ?>
      <?php foreach($alertas as $a): ?>
        <article class="admin-report-card stage24-alert-card"><header><div><span class="admin-pill status-<?=esc($a['severity'])?>"><?=esc($a['severity'])?></span><b><?=esc($a['title'])?></b></div><strong><?=esc($a['status'])?></strong></header>
          <p><?=esc($a['message'])?></p>
          <div class="admin-report-grid"><p><small>Tipo</small><b><?=esc($a['alert_type'])?></b></p><p><small>Usuário</small><b><?=esc($a['subject_nome'] ?: $a['nome'] ?: '—')?></b><span><?=esc($a['subject_aura'] ?: $a['aura_id'] ?: '')?></span></p><p><small>Ocorrências</small><b><?=(int)$a['occurrence_count']?></b><span><?=date('d/m/Y H:i',strtotime($a['last_seen_at']))?></span></p></div>
          <?php if(in_array($a['status'],['open','triage','in_review'],true)): ?>
          <form method="post" class="admin-review-form"><?=camposCsrf()?><input type="hidden" name="acao" value="resolver_alerta"><input type="hidden" name="alerta_id" value="<?=(int)$a['id']?>"><input name="nota" placeholder="Observação"><button name="status" value="in_review">Em análise</button><button class="admin-primary" name="status" value="resolved">Resolver</button><button name="status" value="dismissed">Descartar</button></form>
          <?php endif; ?>
        </article>
      <?php endforeach; ?>
    </div>
  <?php endif; ?>

  <?php if($tab==='auditoria'): ?>
    <section class="admin-card"><h2>Exportar auditoria</h2><form method="get" action="<?=SITE_URL?>/pages/admin-auditoria-exportar.php" class="admin-filter-bar"><select name="format"><option value="csv">CSV</option><option value="json">JSON</option></select><input name="usuario_id" placeholder="ID do usuário"><input name="action" placeholder="Ação contém"><input type="date" name="from"><input type="date" name="to"><button class="admin-primary">Exportar</button></form></section>
    <div class="admin-table-wrap"><table class="admin-table"><thead><tr><th>Data</th><th>Ação</th><th>Ator</th><th>Alvo</th><th>Entidade</th><th>Sev.</th></tr></thead><tbody><?php foreach($auditoria as $l): ?><tr><td><?=date('d/m/Y H:i',strtotime($l['created_at']))?></td><td><?=esc($l['action_key'])?></td><td><?=esc($l['admin_nome'] ?: $l['actor_nome'] ?: $l['actor_type'])?></td><td><?=esc($l['subject_nome'] ?: $l['subject_aura'] ?: '')?></td><td><?=esc(($l['entity_type']??'').' '.($l['entity_id']??''))?></td><td><?=esc($l['severity'])?></td></tr><?php endforeach; ?></tbody></table></div>
  <?php endif; ?>

  <?php if($tab==='usuarios'): ?>
    <section class="admin-card"><h2>Buscar usuário</h2><form method="get" class="admin-filter-bar"><input type="hidden" name="tab" value="usuarios"><input name="q" value="<?=esc($q)?>" placeholder="Nome, e-mail, username ou AURA ID"><button>Buscar</button></form></section>
    <?php if($userDossier && $userDossier['usuario']): $u=$userDossier['usuario']; $risk=$userDossier['risk'] ?: []; ?>
      <article class="admin-report-card"><header><div><span class="admin-pill status-<?=esc($risk['risk_level'] ?? $u['stage24_risk_level'] ?? 'safe')?>"><?=esc($risk['risk_level'] ?? $u['stage24_risk_level'] ?? 'safe')?></span><b><?=esc($u['nome'])?> • <?=esc($u['aura_id'])?></b></div><strong><?=(int)($risk['risk_score'] ?? $u['stage24_risk_score'] ?? 0)?> pts</strong></header>
      <div class="admin-report-grid"><p><small>Status</small><b><?=esc($u['seguranca_status'])?></b><span>Conta <?=esc((string)$u['status'])?></span></p><p><small>Idade</small><b><?=esc($userDossier['age']['tipo_conta'] ?? '—')?></b><span><?=esc($userDossier['age']['status_idade'] ?? '')?></span></p><p><small>Alertas</small><b><?=count($userDossier['alerts'])?></b><span>abertos/histórico</span></p></div>
      <form method="post" class="admin-review-form"><?=camposCsrf()?><input type="hidden" name="acao" value="recalcular_usuario"><input type="hidden" name="usuario_id" value="<?=(int)$u['id']?>"><button class="admin-primary">Recalcular risco</button></form>
      <form method="post" class="admin-review-form"><?=camposCsrf()?><input type="hidden" name="acao" value="criar_alerta_manual"><input type="hidden" name="usuario_id" value="<?=(int)$u['id']?>"><select name="severity"><option value="medium">Médio</option><option value="high">Alto</option><option value="critical">Crítico</option></select><input name="titulo" placeholder="Título do alerta"><input name="mensagem" placeholder="Mensagem"><button>Criar alerta</button></form></article>
      <section class="admin-grid-two"><article class="admin-card"><h2>Alertas</h2><?php foreach($userDossier['alerts'] as $a): ?><div class="stage24-alert severity-<?=esc($a['severity'])?>"><b><?=esc($a['title'])?></b><small><?=esc($a['status'])?> • <?=date('d/m H:i',strtotime($a['last_seen_at']))?></small><p><?=esc($a['message'])?></p></div><?php endforeach; ?></article><article class="admin-card"><h2>Auditoria do usuário</h2><?php foreach($userDossier['audit'] as $l): ?><div class="stage24-log"><b><?=esc($l['action_key'])?></b><small><?=date('d/m/Y H:i',strtotime($l['created_at']))?> • <?=esc($l['severity'])?></small></div><?php endforeach; ?></article></section>
    <?php else: ?>
      <div class="admin-table-wrap"><table class="admin-table"><thead><tr><th>Usuário</th><th>Aura ID</th><th>Status</th><th>Risco</th><th>Ações</th></tr></thead><tbody><?php foreach($userResults as $u): ?><tr><td><?=esc($u['nome'])?><br><small><?=esc($u['email'])?></small></td><td><?=esc($u['aura_id'])?></td><td><?=esc($u['seguranca_status'])?></td><td><?=esc($u['risk_level'] ?? $u['stage24_risk_level'])?> • <?=(int)($u['risk_score'] ?? $u['stage24_risk_score'])?></td><td><a class="admin-primary" href="?tab=usuarios&usuario_id=<?=(int)$u['id']?>">Abrir dossiê</a></td></tr><?php endforeach; ?></tbody></table></div>
    <?php endif; ?>
  <?php endif; ?>

  <?php if($tab==='api'): ?>
    <div class="admin-table-wrap"><table class="admin-table"><thead><tr><th>Data</th><th>Endpoint</th><th>Usuário</th><th>Status</th><th>Perm.</th><th>Duração</th></tr></thead><tbody><?php foreach($apiLogs as $l): ?><tr><td><?=date('d/m/Y H:i:s',strtotime($l['created_at']))?></td><td><small><?=esc($l['method'])?></small> <?=esc($l['endpoint'])?></td><td><?=esc($l['nome'] ?: $l['admin_nome'] ?: '—')?></td><td><?=(int)$l['http_status']?></td><td><?=((int)$l['allowed'])?'sim':'não'?></td><td><?=(int)$l['duration_ms']?> ms</td></tr><?php endforeach; ?></tbody></table></div>
  <?php endif; ?>
</main>
</div>
<link rel="stylesheet" href="<?=SITE_URL?>/assets/css/admin-auditoria.css?v=24.0">
<script src="<?=SITE_URL?>/assets/js/admin.js?v=14.1"></script>
<?php require __DIR__.'/../includes/footer.php'; ?>
