<?php
/** AURA FARMING — Etapa 10: torneio ou evento */
require_once __DIR__.'/../config/config.php';require_once __DIR__.'/../config/database.php';require_once __DIR__.'/../includes/functions.php';require_once __DIR__.'/../includes/match_functions.php';requireLogin();
afRequireAgeFeature($pdo,'competition');$u=usuarioAtual();$uid=(int)$u['id'];$id=max(0,(int)($_GET['id']??0));$c=afBuscarCompeticao($pdo,$id);
if(!$c){setFlash('error','Competição não encontrada.');header('Location: '.SITE_URL.'/pages/arena.php');exit;}
if($_SERVER['REQUEST_METHOD']==='POST'){
 if(!validarCsrfToken($_POST[CSRF_TOKEN_NAME]??''))setFlash('error','Sessão expirada.');else try{$acao=(string)($_POST['acao']??'');if($acao==='entrar')afEntrarCompeticao($pdo,$uid,$id);elseif($acao==='iniciar')afIniciarCompeticao($pdo,$id,$uid);elseif($acao==='finalizar_evento')afFinalizarEvento($pdo,$id,$uid);}catch(Throwable $e){setFlash('error',$e->getMessage());}
 header('Location: '.SITE_URL.'/pages/competicao.php?id='.$id);exit;
}
$c=afBuscarCompeticao($pdo,$id);$pub=afCompeticaoPublica($pdo,$c,$uid);$minhaBatalha=null;foreach($pub['batalhas'] as $b)if(in_array($b['status'],['convite','aguardando_prontidao','preparando','em_andamento'],true)&&$b['sou_participante']){$minhaBatalha=$b;break;}
$pageTitle=$pub['nome'];$showNav=false;require_once __DIR__.'/../includes/header.php';
?>
<main class="competition-page"><header class="competition-header"><a href="<?=SITE_URL?>/pages/arena.php">← ARENA</a><span><?=$pub['tipo']==='torneio'?'🏆 TORNEIO ELIMINATÓRIO':'🌐 EVENTO DE RANKING'?></span><b><?=$pub['codigo']?></b></header><?=renderFlash()?>
<section class="competition-hero"><div><p class="eyebrow"><?=strtoupper(esc(str_replace('_',' ',$pub['status'])))?></p><h1><?=esc($pub['nome'])?></h1><p><?=esc($pub['descricao']?:'Competição oficial de Aura Farming.')?></p><div class="competition-meta"><span>👥 <?=$pub['total_participantes']?>/<?=$pub['max_participantes']?></span><span>👑 <?=esc($pub['criador_nome'])?></span><span>🔐 <?=$pub['visibilidade']==='privado'?'POR CÓDIGO':'PÚBLICO'?></span></div></div><div class="competition-trophy"><?=$pub['tipo']==='torneio'?'🏆':'🌌'?></div></section>
<section class="competition-actions">
<?php if(!$pub['inscrito']&&$pub['status']==='inscricoes'):?><form method="post"><input type="hidden" name="<?=CSRF_TOKEN_NAME?>" value="<?=esc(gerarCsrfToken())?>"><button class="btn btn-primary" name="acao" value="entrar">ENTRAR NA COMPETIÇÃO</button></form><?php endif;?>
<?php if($pub['sou_criador']&&$pub['status']==='inscricoes'):?><form method="post"><input type="hidden" name="<?=CSRF_TOKEN_NAME?>" value="<?=esc(gerarCsrfToken())?>"><button class="btn btn-primary" name="acao" value="iniciar">▶ INICIAR <?= $pub['tipo']==='torneio'?'TORNEIO':'EVENTO' ?></button></form><?php endif;?>
<?php if($minhaBatalha):?><a class="btn btn-primary" href="<?=SITE_URL?>/pages/batalha.php?id=<?=$minhaBatalha['id']?>">⚔️ ABRIR MINHA BATALHA</a><?php endif;?>
<?php if($pub['tipo']==='evento'&&$pub['status']==='em_andamento'&&$pub['inscrito']):$me=array_values(array_filter($pub['participantes'],static fn($p)=>$p['eu']))[0]??null;if((int)($me['partidas']??0)===0):?><a class="btn btn-primary" href="<?=SITE_URL?>/pages/farmar.php?competition=<?=$id?>">🔥 REALIZAR FARMADA DO EVENTO</a><?php else:?><div class="event-score-done">✓ SUA PONTUAÇÃO FOI REGISTRADA: <b><?=number_format((float)($me['melhor_pontuacao']??0),2,',','.')?></b></div><?php endif;?><?php endif;?>
<?php if($pub['tipo']==='evento'&&$pub['sou_criador']&&$pub['status']==='em_andamento'):?><form method="post"><input type="hidden" name="<?=CSRF_TOKEN_NAME?>" value="<?=esc(gerarCsrfToken())?>"><button class="btn btn-secondary" name="acao" value="finalizar_evento">ENCERRAR E CALCULAR VENCEDOR</button></form><?php endif;?>
<?php if($pub['status']==='finalizada'):?><div class="competition-champion"><span>👑</span><div><small>CAMPEÃO</small><strong><?=esc($pub['campeao_nome']??'Resultado final')?></strong></div></div><?php endif;?>
</section>

<section class="competition-section"><div class="section-title">👥 Participantes</div><div class="competition-ranking"><?php foreach($pub['participantes'] as $i=>$p):?><a href="<?=SITE_URL?>/pages/jogador.php?aura=<?=urlencode($p['aura_id'])?>" class="competition-player <?=!empty($p['eu'])?'is-me':''?>"><b><?=($p['posicao']?:$i+1)?>º</b><img src="<?=esc($p['avatar'])?>"><div><strong><?=esc($p['nome'])?></strong><small><?=esc($p['aura_id'])?> • <?=esc($p['status'])?></small></div><span><strong><?=number_format((float)$p['melhor_pontuacao'],2,',','.')?></strong><small>melhor</small></span></a><?php endforeach;?></div></section>

<?php if($pub['tipo']==='torneio'&&$pub['batalhas']):?><section class="competition-section"><div class="section-title">⚔️ Chaveamento</div><div class="bracket-board"><?php $rounds=[];foreach($pub['batalhas'] as $b)$rounds[$b['rodada']][]=$b;foreach($rounds as $round=>$matches):?><div class="bracket-round"><h3>RODADA <?=$round?></h3><?php foreach($matches as $b):?><a href="<?=SITE_URL?>/pages/batalha.php?id=<?=$b['id']?>" class="bracket-match"><small>CHAVE <?=$b['chave_ordem']?> • <?=esc(str_replace('_',' ',$b['status']))?></small><?php foreach($b['jogadores'] as $j):?><div class="<?=($b['vencedor_id']===$j['usuario_id'])?'is-winner':''?>"><img src="<?=esc($j['avatar'])?>"><span><?=esc($j['nome'])?></span><b><?=number_format((float)$j['pontuacao'],0,',','.')?></b></div><?php endforeach;?></a><?php endforeach;?></div><?php endforeach;?></div></section><?php endif;?>
<section class="competition-code"><span>🔑</span><div><small>CÓDIGO PARA CONVIDAR</small><strong><?=$pub['codigo']?></strong></div><button type="button" onclick="navigator.clipboard?.writeText('<?=$pub['codigo']?>');this.textContent='COPIADO!'">COPIAR</button></section>
</main>
<?php require_once __DIR__.'/../includes/footer.php';?>
