<?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.');$id=(int)($_POST['partida_id']??0);$acao=(string)($_POST['acao']??'');$obs=sanitize($_POST['observacao']??'');if(!in_array($acao,['normal','oculta','anulada'],true))throw new RuntimeException('Ação inválida.');$pdo->prepare('UPDATE af_partidas SET admin_status=?,admin_observacao=?,admin_revisor_id=NULL,admin_revisor_conta_id=?,admin_revisada_em=NOW() WHERE id=?')->execute([$acao,$obs,afAdminId(),$id]);if($acao==='anulada'){$pdo->prepare('DELETE FROM af_ranking WHERE partida_id=?')->execute([$id]);}$pdo->prepare('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) WHERE u.id=(SELECT usuario_id FROM af_partidas WHERE id=?)')->execute([$id]);afAdminLog($pdo,'partida_'.$acao,'partida',$id,['observacao'=>$obs]);setFlash('success','Partida atualizada.');}
 catch(Throwable $e){setFlash('error',$e->getMessage());}header('Location: '.SITE_URL.'/pages/admin-partidas.php');exit;
}
$q=sanitize($_GET['q']??'');$filter=(string)($_GET['filter']??'todas');$where=['1=1'];$params=[];if($q!==''){$where[]='(u.nome LIKE ? OR u.aura_id LIKE ? OR p.sessao_id LIKE ?)';$like='%'.$q.'%';array_push($params,$like,$like,$like);}if($filter==='revisao')$where[]="p.antifraude_status='revisao'";elseif($filter==='aprovadas')$where[]="p.antifraude_status='aprovada'";elseif($filter==='anuladas')$where[]="p.admin_status='anulada'";elseif($filter==='ao_vivo')$where[]="p.status='em_andamento'";$sqlWhere=implode(' AND ',$where);$st=$pdo->prepare("SELECT COUNT(*) FROM af_partidas p JOIN af_usuarios u ON u.id=p.usuario_id WHERE {$sqlWhere}");$st->execute($params);$pg=afAdminPagination((int)$st->fetchColumn(),25);$st=$pdo->prepare("SELECT p.*,u.nome,u.aura_id,u.username FROM af_partidas p JOIN af_usuarios u ON u.id=p.usuario_id WHERE {$sqlWhere} ORDER BY p.id DESC LIMIT {$pg['per_page']} OFFSET {$pg['offset']}");$st->execute($params);$items=$st->fetchAll()?:[];
$pageTitle='Admin • Partidas';$showNav=false;$bodyClass='admin-body';$adminPage='partidas';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>MODERAÇÃO</small><h1>Partidas</h1></div><span class="admin-count"><?=$pg['total']?> registros</span></header><?=renderFlash()?>
<form class="admin-filters" method="get"><input name="q" value="<?=esc($q)?>" placeholder="Jogador, AURA-ID ou sessão"><select name="filter"><option value="todas">Todas</option><?php foreach(['ao_vivo'=>'Ao vivo','aprovadas'=>'Aprovadas','revisao'=>'Em revisão','anuladas'=>'Anuladas'] as $k=>$v):?><option value="<?=$k?>" <?=$filter===$k?'selected':''?>><?=$v?></option><?php endforeach;?></select><button>Filtrar</button></form>
<section class="admin-panel"><div class="admin-table-wrap"><table class="admin-table"><thead><tr><th>Partida</th><th>Pontuação</th><th>Antifraude</th><th>Admin</th><th>Ações</th></tr></thead><tbody><?php foreach($items as $p):?><tr><td><b>#<?=(int)$p['id']?> • <?=esc($p['nome'])?></b><small><?=esc($p['aura_id'])?> • <?=esc($p['status'])?><br><?=esc($p['finalizada_em']??$p['criada_em'])?></small></td><td><b><?=number_format((float)$p['pontuacao_total'],2,',','.')?></b><small>Validada <?=number_format((float)$p['pontuacao_validada'],2,',','.')?> • Aura <?=number_format((float)$p['aura_gerada'],0,',','.')?></small></td><td><span class="admin-pill status-<?=esc($p['antifraude_status'])?>"><?=esc($p['antifraude_status'])?></span><small>Risco <?=(int)$p['antifraude_score']?></small></td><td><span class="admin-pill"><?=esc($p['admin_status'])?></span><small><?=esc($p['admin_observacao']??'Sem observação')?></small></td><td><form method="post" class="admin-inline-actions"><?=camposCsrf()?><input type="hidden" name="partida_id" value="<?=(int)$p['id']?>"><select name="acao"><option value="normal">Normal</option><option value="oculta">Ocultar pública</option><option value="anulada">Anular pontuação</option></select><input name="observacao" placeholder="Motivo"><button>Salvar</button></form></td></tr><?php endforeach;?></tbody></table></div></section><?php include __DIR__.'/../includes/admin_pagination.php';?></main></div><script src="<?=SITE_URL?>/assets/js/admin.js?v=14.1"></script><?php require __DIR__.'/../includes/footer.php';?>
