<?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();
$stats=afAdminDashboard($pdo);
$privacyOpen=afPrivacyTableExists($pdo,'af_privacy_requests')?(int)$pdo->query("SELECT COUNT(*) FROM af_privacy_requests WHERE status IN ('open','in_review','awaiting_identity')")->fetchColumn():0;
$series=$pdo->query("SELECT DATE(finalizada_em) dia,COUNT(*) partidas,COALESCE(SUM(pontuacao_validada),0) pontos FROM af_partidas WHERE finalizada_em>=DATE_SUB(CURDATE(),INTERVAL 13 DAY) AND status='finalizada' AND admin_status<>'anulada' GROUP BY DATE(finalizada_em) ORDER BY dia")->fetchAll()?:[];
$recentUsers=$pdo->query("SELECT id,nome,username,email,aura_id,papel,status,seguranca_status,data_cadastro FROM af_usuarios ORDER BY id DESC LIMIT 8")->fetchAll()?:[];
$alerts=$pdo->query("SELECT e.*,u.nome,u.aura_id FROM af_eventos_seguranca e LEFT JOIN af_usuarios u ON u.id=e.usuario_id WHERE e.status='aberto' ORDER BY FIELD(e.severidade,'critica','alta','media','baixa','info'),e.id DESC LIMIT 8")->fetchAll()?:[];
$pageTitle='Painel Administrativo';$showNav=false;$bodyClass='admin-body';$adminPage='dashboard';require __DIR__.'/../includes/header.php';?>
<div class="admin-shell"><?php require __DIR__.'/../includes/admin_nav.php';?><main class="admin-main">
<header class="admin-topbar"><div><small>CONTROLE DA PLATAFORMA</small><h1>Painel administrativo</h1></div><div class="admin-user-chip">👤 <?=esc(afAdminAtual()['nome']??'Admin')?></div></header><?=renderFlash()?>
<section class="admin-kpi-grid">
<?php foreach([
 ['👥','Usuários',(int)$stats['usuarios'],'+'.(int)$stats['novos_hoje'].' hoje'],['✅','Contas ativas',(int)$stats['usuarios_ativos'],'aptas para jogar'],['🎮','Partidas',(int)$stats['partidas_finalizadas'],(int)$stats['partidas_hoje'].' hoje'],['📡','Ao vivo',(int)$stats['ao_vivo'],'sessões agora'],['🛡️','Em revisão',(int)$stats['revisao'],'antifraude'],['🚩','Denúncias',(int)$stats['denuncias'],'pendentes'],['🛡️','Privacidade',$privacyOpen,'solicitações abertas'],['⚔️','Competições',(int)$stats['competicoes'],'ativas'],['💎','Pontos validados',number_format($stats['pontos_validados'],0,',','.'),'acumulados']
] as $k):?><article><span><?=$k[0]?></span><div><small><?=esc($k[1])?></small><strong><?=esc((string)$k[2])?></strong><em><?=esc($k[3])?></em></div></article><?php endforeach;?></section>
<div class="admin-grid-2">
<section class="admin-panel"><header><div><small>ÚLTIMOS 14 DIAS</small><h2>Atividade da plataforma</h2></div><a href="<?=SITE_URL?>/pages/admin-relatorios.php">Relatório →</a></header><div class="admin-chart" data-admin-chart='<?=esc(json_encode($series,JSON_UNESCAPED_UNICODE))?>'><canvas id="adminActivityChart" width="800" height="260"></canvas></div></section>
<section class="admin-panel"><header><div><small>SEGURANÇA</small><h2>Alertas recentes</h2></div><a href="<?=SITE_URL?>/pages/admin-seguranca.php">Abrir central →</a></header><div class="admin-list"><?php if(!$alerts):?><div class="admin-empty">Nenhum alerta aberto.</div><?php endif;foreach($alerts as $a):?><a href="<?=SITE_URL?>/pages/admin-seguranca.php" class="admin-list-row"><span class="admin-severity sev-<?=esc($a['severidade'])?>"></span><div><b><?=esc(str_replace('_',' ',$a['categoria']))?></b><small><?=esc($a['nome']??'Sistema')?> • <?=esc($a['aura_id']??'sem usuário')?></small></div><em><?=date('d/m H:i',strtotime($a['criado_em']))?></em></a><?php endforeach;?></div></section>
</div>
<section class="admin-panel"><header><div><small>CADASTROS</small><h2>Usuários mais recentes</h2></div><a href="<?=SITE_URL?>/pages/admin-usuarios.php">Gerenciar →</a></header><div class="admin-table-wrap"><table class="admin-table"><thead><tr><th>Usuário</th><th>ID</th><th>Papel</th><th>Status</th><th>Cadastro</th></tr></thead><tbody><?php foreach($recentUsers as $u):?><tr><td><b><?=esc($u['nome'])?></b><small>@<?=esc($u['username'])?> • <?=esc($u['email'])?></small></td><td><?=esc($u['aura_id'])?></td><td><span class="admin-pill"><?=esc($u['papel'])?></span></td><td><span class="admin-pill status-<?=esc($u['seguranca_status'])?>"><?=esc($u['seguranca_status'])?></span></td><td><?=date('d/m/Y H:i',strtotime($u['data_cadastro']))?></td></tr><?php endforeach;?></tbody></table></div></section>
</main></div><script src="<?=SITE_URL?>/assets/js/admin.js?v=14.1"></script><?php require __DIR__.'/../includes/footer.php';?>
