<?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();
$from=preg_match('/^\d{4}-\d{2}-\d{2}$/',$_GET['from']??'')?$_GET['from']:date('Y-m-d',strtotime('-29 days'));$to=preg_match('/^\d{4}-\d{2}-\d{2}$/',$_GET['to']??'')?$_GET['to']:date('Y-m-d');if($from>$to)[$from,$to]=[$to,$from];
$st=$pdo->prepare("SELECT DATE(p.finalizada_em) dia,COUNT(*) partidas,COUNT(DISTINCT p.usuario_id) jogadores,COALESCE(SUM(p.pontuacao_validada),0) pontos,COALESCE(AVG(p.pontuacao_validada),0) media,SUM(p.antifraude_status='revisao') revisoes,SUM(p.admin_status='anulada') anuladas FROM af_partidas p WHERE DATE(p.finalizada_em) BETWEEN ? AND ? AND p.status='finalizada' GROUP BY DATE(p.finalizada_em) ORDER BY dia");$st->execute([$from,$to]);$daily=$st->fetchAll()?:[];
if(($_GET['export']??'')==='csv'){
 afAdminLog($pdo,'relatorio_exportado','relatorio',null,['from'=>$from,'to'=>$to]);header('Content-Type: text/csv; charset=UTF-8');header('Content-Disposition: attachment; filename="aura-relatorio-'.$from.'-a-'.$to.'.csv"');echo "\xEF\xBB\xBF";$out=fopen('php://output','w');fputcsv($out,['Data','Partidas','Jogadores','Pontos validados','Média','Revisões','Anuladas'],';');foreach($daily as $r)fputcsv($out,[$r['dia'],$r['partidas'],$r['jogadores'],$r['pontos'],$r['media'],$r['revisoes'],$r['anuladas']],';');fclose($out);exit;
}
$st=$pdo->prepare("SELECT COUNT(DISTINCT usuario_id) usuarios,COUNT(*) partidas,COALESCE(SUM(pontuacao_validada),0) pontos,COALESCE(AVG(pontuacao_validada),0) media,SUM(antifraude_status='revisao') revisoes,SUM(admin_status='anulada') anuladas FROM af_partidas WHERE DATE(finalizada_em) BETWEEN ? AND ? AND status='finalizada'");$st->execute([$from,$to]);$sum=$st->fetch()?:[];
$growth=$pdo->prepare('SELECT DATE(data_cadastro) dia,COUNT(*) total FROM af_usuarios WHERE DATE(data_cadastro) BETWEEN ? AND ? GROUP BY DATE(data_cadastro) ORDER BY dia');$growth->execute([$from,$to]);$usersDaily=$growth->fetchAll()?:[];
$top=$pdo->prepare("SELECT u.nome,u.aura_id,MAX(p.pontuacao_validada) pontos,COUNT(*) partidas FROM af_usuarios u JOIN af_partidas p ON p.usuario_id=u.id WHERE DATE(p.finalizada_em) BETWEEN ? AND ? AND p.status='finalizada' AND p.antifraude_status='aprovada' AND p.admin_status='normal' GROUP BY u.id ORDER BY pontos DESC LIMIT 10");$top->execute([$from,$to]);$top=$top->fetchAll()?:[];
$pageTitle='Admin • Relatórios';$showNav=false;$bodyClass='admin-body';$adminPage='relatorios';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>ANÁLISE DE DESEMPENHO</small><h1>Relatórios</h1></div><a class="admin-primary" href="?<?=esc(http_build_query(['from'=>$from,'to'=>$to,'export'=>'csv']))?>">↓ Exportar CSV</a></header>
<form class="admin-filters" method="get"><label>De <input type="date" name="from" value="<?=esc($from)?>"></label><label>Até <input type="date" name="to" value="<?=esc($to)?>"></label><button>Atualizar</button></form>
<section class="admin-kpi-grid report-kpis"><?php foreach([['👤','Jogadores',(int)($sum['usuarios']??0)],['🎮','Partidas',(int)($sum['partidas']??0)],['💎','Pontos',number_format((float)($sum['pontos']??0),0,',','.')],['📊','Média',number_format((float)($sum['media']??0),2,',','.')],['🛡️','Revisões',(int)($sum['revisoes']??0)],['✕','Anuladas',(int)($sum['anuladas']??0)]] as $k):?><article><span><?=$k[0]?></span><div><small><?=$k[1]?></small><strong><?=$k[2]?></strong></div></article><?php endforeach;?></section>
<div class="admin-grid-2"><section class="admin-panel"><header><div><small>PARTIDAS</small><h2>Evolução diária</h2></div></header><div class="admin-chart" data-admin-chart='<?=esc(json_encode($daily,JSON_UNESCAPED_UNICODE))?>'><canvas id="adminActivityChart" width="800" height="260"></canvas></div></section><section class="admin-panel"><header><div><small>CADASTROS</small><h2>Novos usuários</h2></div></header><div class="admin-chart" data-admin-users='<?=esc(json_encode($usersDaily,JSON_UNESCAPED_UNICODE))?>'><canvas id="adminUsersChart" width="800" height="260"></canvas></div></section></div>
<section class="admin-panel"><header><div><small>DESTAQUES</small><h2>Top 10 do período</h2></div></header><div class="admin-table-wrap"><table class="admin-table"><thead><tr><th>#</th><th>Jogador</th><th>Pontos</th><th>Partidas</th></tr></thead><tbody><?php foreach($top as $i=>$u):?><tr><td><?=($i+1)?>º</td><td><b><?=esc($u['nome'])?></b><small><?=esc($u['aura_id'])?></small></td><td><?=number_format((float)$u['pontos'],2,',','.')?></td><td><?=(int)$u['partidas']?></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';?>
