<?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();
if($_SERVER['REQUEST_METHOD']==='POST'){
 try{if(!validarCsrfToken($_POST[CSRF_TOKEN_NAME]??''))throw new RuntimeException('Sessão expirada.');$acao=(string)($_POST['acao']??'');if($acao==='recalcular'){$pdo->exec("UPDATE af_usuarios u SET melhor_pontuacao=COALESCE((SELECT MAX(p.pontuacao_validada) FROM af_partidas p WHERE p.usuario_id=u.id AND p.status='finalizada' AND p.antifraude_status='aprovada' AND p.admin_status='normal'),0),total_partidas=(SELECT COUNT(*) FROM af_partidas p WHERE p.usuario_id=u.id AND p.status='finalizada' AND p.admin_status<>'anulada')");afAdminLog($pdo,'ranking_recalculado','ranking',null);setFlash('success','Ranking e melhores pontuações recalculados.');}elseif($acao==='remover'){$uid=(int)($_POST['usuario_id']??0);$pdo->prepare("UPDATE af_partidas SET admin_status='anulada',admin_observacao='Anulada pelo painel de ranking',admin_revisor_id=NULL,admin_revisor_conta_id=?,admin_revisada_em=NOW() WHERE usuario_id=? AND pontuacao_validada=(SELECT mx FROM (SELECT MAX(pontuacao_validada) mx FROM af_partidas WHERE usuario_id=? AND status='finalizada' AND antifraude_status='aprovada' AND admin_status='normal') x) LIMIT 1")->execute([afAdminId(),$uid,$uid]);$pdo->prepare("UPDATE af_usuarios SET melhor_pontuacao=COALESCE((SELECT MAX(pontuacao_validada) FROM af_partidas WHERE usuario_id=? AND status='finalizada' AND antifraude_status='aprovada' AND admin_status='normal'),0) WHERE id=?")->execute([$uid,$uid]);afAdminLog($pdo,'ranking_pontuacao_removida','usuario',$uid);setFlash('success','Melhor pontuação removida do ranking.');}}
 catch(Throwable $e){setFlash('error',$e->getMessage());}header('Location: '.SITE_URL.'/pages/admin-ranking.php');exit;
}
$period=(string)($_GET['period']??'global');$periodSql=match($period){'diario'=>"AND p.finalizada_em>=CURDATE()",'semanal'=>"AND p.finalizada_em>=DATE_SUB(NOW(),INTERVAL 7 DAY)",'mensal'=>"AND p.finalizada_em>=DATE_SUB(NOW(),INTERVAL 30 DAY)",default=>''};
$st=$pdo->query("SELECT u.id,u.nome,u.username,u.aura_id,u.nivel,u.total_partidas,MAX(p.pontuacao_validada) pontuacao,MAX(p.finalizada_em) ultima FROM af_usuarios u JOIN af_partidas p ON p.usuario_id=u.id WHERE u.status=1 AND p.status='finalizada' AND p.antifraude_status='aprovada' AND p.admin_status='normal' {$periodSql} GROUP BY u.id ORDER BY pontuacao DESC LIMIT 100");$items=$st->fetchAll()?:[];
$pageTitle='Admin • Ranking';$showNav=false;$bodyClass='admin-body';$adminPage='ranking';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>CLASSIFICAÇÃO</small><h1>Ranking oficial</h1></div><form method="post"><?=camposCsrf()?><button class="admin-primary" name="acao" value="recalcular">↻ Recalcular</button></form></header><?=renderFlash()?>
<nav class="admin-tabs"><?php foreach(['global'=>'Todos os tempos','mensal'=>'30 dias','semanal'=>'7 dias','diario'=>'Hoje'] as $k=>$v):?><a class="<?=$period===$k?'active':''?>" href="?period=<?=$k?>"><?=$v?></a><?php endforeach;?></nav>
<section class="admin-panel"><div class="admin-table-wrap"><table class="admin-table"><thead><tr><th>#</th><th>Jogador</th><th>Melhor pontuação</th><th>Nível</th><th>Partidas</th><th>Ação</th></tr></thead><tbody><?php foreach($items as $i=>$u):?><tr><td><b><?=($i+1)?>º</b></td><td><b><?=esc($u['nome'])?></b><small>@<?=esc($u['username'])?> • <?=esc($u['aura_id'])?></small></td><td><b><?=number_format((float)$u['pontuacao'],2,',','.')?></b><small><?=date('d/m/Y H:i',strtotime($u['ultima']))?></small></td><td><?=(int)$u['nivel']?></td><td><?=(int)$u['total_partidas']?></td><td><form method="post" onsubmit="return confirm('Anular a melhor pontuação deste jogador?')"><?=camposCsrf()?><input type="hidden" name="usuario_id" value="<?=(int)$u['id']?>"><button class="admin-danger" name="acao" value="remover">Anular melhor</button></form></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';?>
