<?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['competicao_id']??0);$acao=(string)($_POST['acao']??'');if(!in_array($acao,['publico','privado','cancelar','finalizar'],true))throw new RuntimeException('Ação inválida.');if(in_array($acao,['publico','privado'],true)){$pdo->prepare('UPDATE af_competicoes SET visibilidade=?,atualizada_em=NOW() WHERE id=?')->execute([$acao,$id]);}elseif($acao==='cancelar'){$pdo->prepare("UPDATE af_competicoes SET status='cancelada',finalizada_em=NOW(),atualizada_em=NOW() WHERE id=? AND status<>'finalizada'")->execute([$id]);$pdo->prepare("UPDATE af_batalhas SET status='cancelada',finalizada_em=NOW() WHERE competicao_id=? AND status NOT IN ('finalizada','cancelada')")->execute([$id]);}else{$pdo->prepare("UPDATE af_competicoes SET status='finalizada',finalizada_em=NOW(),atualizada_em=NOW() WHERE id=?")->execute([$id]);}afAdminLog($pdo,'competicao_'.$acao,'competicao',$id);setFlash('success','Competição atualizada.');}
 catch(Throwable $e){setFlash('error',$e->getMessage());}header('Location: '.SITE_URL.'/pages/admin-competicoes.php');exit;
}
$status=(string)($_GET['status']??'ativas');$where=match($status){'finalizadas'=>"c.status='finalizada'",'canceladas'=>"c.status='cancelada'",'todas'=>'1=1',default=>"c.status IN ('inscricoes','em_andamento')"};$items=$pdo->query("SELECT c.*,u.nome criador_nome,u.aura_id criador_aura,(SELECT COUNT(*) FROM af_competicao_participantes cp WHERE cp.competicao_id=c.id) participantes,(SELECT COUNT(*) FROM af_batalhas b WHERE b.competicao_id=c.id) batalhas FROM af_competicoes c JOIN af_usuarios u ON u.id=c.criador_id WHERE {$where} ORDER BY c.id DESC LIMIT 150")->fetchAll()?:[];
$pageTitle='Admin • Competições';$showNav=false;$bodyClass='admin-body';$adminPage='competicoes';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>ARENA</small><h1>Competições</h1></div><span class="admin-count"><?=count($items)?> registros</span></header><?=renderFlash()?>
<nav class="admin-tabs"><?php foreach(['ativas'=>'Ativas','finalizadas'=>'Finalizadas','canceladas'=>'Canceladas','todas'=>'Todas'] as $k=>$v):?><a class="<?=$status===$k?'active':''?>" href="?status=<?=$k?>"><?=$v?></a><?php endforeach;?></nav>
<section class="admin-panel"><div class="admin-table-wrap"><table class="admin-table"><thead><tr><th>Competição</th><th>Criador</th><th>Estrutura</th><th>Status</th><th>Ações</th></tr></thead><tbody><?php foreach($items as $c):?><tr><td><b><?=esc($c['nome'])?></b><small><?=esc($c['codigo'])?> • <?=esc($c['tipo'])?> • <?=esc($c['formato'])?></small></td><td><b><?=esc($c['criador_nome'])?></b><small><?=esc($c['criador_aura'])?></small></td><td><?=(int)$c['participantes']?> participantes<small><?=(int)$c['batalhas']?> batalhas • limite <?=(int)$c['max_participantes']?></small></td><td><span class="admin-pill"><?=esc($c['status'])?></span><small><?=esc($c['visibilidade'])?></small></td><td><form method="post" class="admin-inline-actions"><?=camposCsrf()?><input type="hidden" name="competicao_id" value="<?=(int)$c['id']?>"><select name="acao"><option value="publico">Tornar pública</option><option value="privado">Tornar privada</option><option value="finalizar">Finalizar</option><option value="cancelar">Cancelar</option></select><button>Aplicar</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';?>
