<?php
/** AURA FARMING — Arena: duelo 1x1 grátis e torneios pagos com Diamantes */
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';
require_once __DIR__.'/../includes/aura_ui.php';

requireLogin();
afRequireAgeFeature($pdo,'battle_hub');
$u=usuarioAtual();
$uid=(int)$u['id'];

if($_SERVER['REQUEST_METHOD']==='POST'){
    if(!validarCsrfToken($_POST[CSRF_TOKEN_NAME]??'')){
        setFlash('error','Sessão expirada. Atualize a página.');
    }else{
        try{
            $acao=(string)($_POST['acao']??'');

            if($acao==='desafiar'){
                // O duelo direto VS 1x1 continua totalmente gratuito.
                $b=afCriarDuelo($pdo,$uid,(string)($_POST['aura_id']??''));
                setFlash('success','Desafio 1x1 enviado gratuitamente!');
                header('Location: '.SITE_URL.'/pages/batalha.php?id='.(int)$b['id']);
                exit;
            }

            if($acao==='criar_competicao'){
                $requestToken=(string)($_POST['competition_request_token']??'');
                $sessionToken=(string)($_SESSION['competition_create_token']??'');
                if($requestToken===''||$sessionToken===''||!hash_equals($sessionToken,$requestToken)){
                    throw new RuntimeException('O formulário de criação expirou. Atualize a Arena e tente novamente.');
                }
                // Impede cobrança/criação duplicada por clique duplo ou reenvio do formulário.
                unset($_SESSION['competition_create_token']);

                $max=(int)($_POST['max_participantes']??0);
                $custo=afCompeticaoCustoDiamantes($max);
                $c=afCriarCompeticao(
                    $pdo,
                    $uid,
                    'torneio',
                    (string)($_POST['nome']??''),
                    (string)($_POST['descricao']??''),
                    $max,
                    (string)($_POST['visibilidade']??'publico'),
                    $requestToken
                );
                setFlash('success','Torneio criado! Foram utilizados '.$custo.' Diamantes. Compartilhe o código '.$c['codigo'].'.');
                header('Location: '.SITE_URL.'/pages/competicao.php?id='.(int)$c['id']);
                exit;
            }

            if($acao==='entrar_competicao'){
                $c=afEntrarCompeticao($pdo,$uid,(string)($_POST['codigo']??''));
                setFlash('success','Inscrição confirmada!');
                header('Location: '.SITE_URL.'/pages/competicao.php?id='.(int)$c['id']);
                exit;
            }
        }catch(Throwable $e){
            setFlash('error',$e->getMessage());
        }
    }
    header('Location: '.SITE_URL.'/pages/arena.php');
    exit;
}

if(empty($_SESSION['competition_create_token'])){
    $_SESSION['competition_create_token']=bin2hex(random_bytes(24));
}
$competitionRequestToken=(string)$_SESSION['competition_create_token'];
$competitionCosts=afCompeticaoCustosDiamantes();
try{$diamondBalance=afDiamondsGetBalance($pdo,$uid);}catch(Throwable $e){$diamondBalance=0;}

$batalhas=afListarBatalhasUsuario($pdo,$uid,20);
$competicoes=afListarCompeticoes($pdo,$uid,20);
$convites=array_values(array_filter($batalhas,static function($b)use($uid){
    foreach($b['jogadores'] as $j)if($j['usuario_id']===$uid&&$j['status']==='convidado')return true;
    return false;
}));
$ativas=array_values(array_filter($batalhas,static fn($b)=>in_array($b['status'],['aguardando_prontidao','preparando','em_andamento'],true)));

$pageTitle='Arena';
$activePage='arena';
$bodyClass='aura-home-v4-body aura-app-body aura-arena-body';
$showNav=false;
$hideLegalFooter=true;
$pageStyles=[SITE_URL.'/assets/css/home-fiel.css?v=4.1.0',SITE_URL.'/assets/css/aura-pages.css?v=1.1.0'];
require_once __DIR__.'/../includes/header.php';
?>
<?php afRenderAppHeader($pdo,$u); ?>
<main class="af-home-shell af-subpage-main page-content arena-page">
<?=renderFlash()?>
<section class="arena-hero fade-in">
    <div>
        <p class="eyebrow">ARENA AURA</p>
        <h1>AURA BATTLE</h1>
        <p>Desafie um jogador no VS 1x1 gratuitamente ou ative torneios eliminatórios usando Diamantes.</p>
    </div>
    <span class="arena-hero__orb">⚔️</span>
</section>

<?php if($convites):?>
<section class="arena-section">
    <div class="section-title">🔥 Convites recebidos</div>
    <?php foreach($convites as $b):$op=array_values(array_filter($b['jogadores'],static fn($j)=>!$j['eu']))[0]??null;?>
    <a class="battle-list-card battle-list-card--invite" href="<?=SITE_URL?>/pages/batalha.php?id=<?=$b['id']?>">
        <span class="battle-list-card__icon">⚡</span>
        <div><strong><?=esc($op['nome']??'Jogador')?> desafiou você</strong><small><?=$b['codigo']?> • aceite para entrar na batalha</small></div>
        <b>RESPONDER →</b>
    </a>
    <?php endforeach;?>
</section>
<?php endif;?>

<section class="arena-grid fade-in">
    <article class="arena-panel arena-panel--free">
        <div class="arena-panel__topline">
            <div class="arena-panel__icon">⚔️</div>
            <span class="arena-free-badge">GRÁTIS</span>
        </div>
        <h2>VS 1x1</h2>
        <p>Desafie diretamente outro jogador. Esta modalidade não utiliza Diamantes.</p>
        <form method="post" class="arena-form">
            <input type="hidden" name="<?=CSRF_TOKEN_NAME?>" value="<?=esc(gerarCsrfToken())?>">
            <input type="hidden" name="acao" value="desafiar">
            <label>ID DO ADVERSÁRIO
                <input name="aura_id" placeholder="AURA-7291" maxlength="9" required>
            </label>
            <button class="btn btn-primary">ENVIAR DESAFIO GRÁTIS</button>
        </form>
    </article>

    <article class="arena-panel arena-panel--paid">
        <div class="arena-panel__topline">
            <div class="arena-panel__icon">🏆</div>
            <span class="arena-paid-badge">💎 TORNEIO PAGO</span>
        </div>
        <h2>CRIAR TORNEIO</h2>
        <p>Escolha a quantidade de participantes. A taxa é debitada uma única vez ao ativar o torneio.</p>

        <div class="arena-wallet-summary">
            <div><small>SEU SALDO</small><strong>💎 <?=number_format($diamondBalance,0,',','.')?></strong></div>
            <a href="<?=SITE_URL?>/pages/comprar-diamantes.php">COMPRAR DIAMANTES →</a>
        </div>

        <form method="post" class="arena-form" id="tournament-create-form" data-diamond-balance="<?=$diamondBalance?>">
            <input type="hidden" name="<?=CSRF_TOKEN_NAME?>" value="<?=esc(gerarCsrfToken())?>">
            <input type="hidden" name="acao" value="criar_competicao">
            <input type="hidden" name="tipo" value="torneio">
            <input type="hidden" name="competition_request_token" value="<?=esc($competitionRequestToken)?>">

            <label>MODO
                <div class="arena-mode-static">🏆 Torneio eliminatório</div>
            </label>
            <label>NOME
                <input name="nome" placeholder="Copa Aura Cascavel" maxlength="100" required>
            </label>
            <label>DESCRIÇÃO
                <textarea name="descricao" maxlength="500" placeholder="Explique as regras ou o objetivo"></textarea>
            </label>
            <div class="arena-form__row">
                <label>PARTICIPANTES
                    <select name="max_participantes" id="tournament-size" required>
                        <?php foreach($competitionCosts as $people=>$cost):?>
                        <option value="<?=$people?>" data-cost="<?=$cost?>" <?=$people===4?'selected':''?>><?=$people?> pessoas — <?=$cost?> Diamantes</option>
                        <?php endforeach;?>
                    </select>
                </label>
                <label>ACESSO
                    <select name="visibilidade">
                        <option value="publico">Público</option>
                        <option value="privado">Por código</option>
                    </select>
                </label>
            </div>

            <div class="arena-price-box">
                <span>VALOR PARA ATIVAR</span>
                <strong><i>💎</i> <b id="tournament-cost">20</b> DIAMANTES</strong>
                <small>O torneio inicia quando todas as vagas selecionadas estiverem preenchidas.</small>
            </div>
            <p class="arena-insufficient" id="tournament-insufficient" hidden>Saldo insuficiente. Adquira mais Diamantes para criar este torneio.</p>
            <button class="btn btn-outline-cyan" id="tournament-submit">CRIAR TORNEIO • 20 DIAMANTES</button>
        </form>
    </article>
</section>

<section class="arena-pricing-guide">
    <strong>💎 TABELA DE ATIVAÇÃO</strong>
    <?php foreach($competitionCosts as $people=>$cost):?>
    <span><b><?=$people?> pessoas</b><em><?=$cost?> Diamantes</em></span>
    <?php endforeach;?>
</section>

<section class="arena-join">
    <div><span>🎟️</span><strong>ENTRAR COM CÓDIGO</strong><small>Use o código enviado pelo organizador.</small></div>
    <form method="post">
        <input type="hidden" name="<?=CSRF_TOKEN_NAME?>" value="<?=esc(gerarCsrfToken())?>">
        <input type="hidden" name="acao" value="entrar_competicao">
        <input name="codigo" placeholder="AB12CD34" maxlength="8" required>
        <button class="btn btn-secondary">ENTRAR</button>
    </form>
</section>

<?php if($ativas):?>
<section class="arena-section">
    <div class="section-title">⚡ Suas batalhas ativas</div>
    <div class="battle-list">
    <?php foreach($ativas as $b):$eu=array_values(array_filter($b['jogadores'],static fn($j)=>$j['eu']))[0]??null;$op=array_values(array_filter($b['jogadores'],static fn($j)=>!$j['eu']))[0]??null;?>
        <a class="battle-list-card" href="<?=SITE_URL?>/pages/batalha.php?id=<?=$b['id']?>">
            <div class="battle-mini-avatars"><img src="<?=esc($eu['avatar']??'')?>"><b>VS</b><img src="<?=esc($op['avatar']??'')?>"></div>
            <div><strong><?=esc($eu['nome']??'Você')?> vs <?=esc($op['nome']??'Adversário')?></strong><small><?=esc(str_replace('_',' ',$b['status']))?> • <?=$b['codigo']?></small></div>
            <span>→</span>
        </a>
    <?php endforeach;?>
    </div>
</section>
<?php endif;?>

<section class="arena-section">
    <div class="section-title">🏟️ Torneios e eventos</div>
    <div class="competition-list">
    <?php foreach($competicoes as $c):?>
        <a class="competition-card" href="<?=SITE_URL?>/pages/competicao.php?id=<?=$c['id']?>">
            <span class="competition-card__type"><?=$c['tipo']==='torneio'?'🏆 TORNEIO':'🌐 EVENTO'?></span>
            <h3><?=esc($c['nome'])?></h3>
            <p><?=esc($c['descricao']?:'Competição oficial de Aura Farming.')?></p>
            <div><span>👥 <?=$c['total_participantes']?>/<?=$c['max_participantes']?></span><span>🔑 <?=$c['codigo']?></span><span class="competition-status"><?=esc(str_replace('_',' ',$c['status']))?></span></div>
        </a>
    <?php endforeach;?>
    <?php if(!$competicoes):?><div class="empty-state"><span>🏟️</span><strong>Nenhum torneio disponível</strong><p>Crie o primeiro torneio da Arena.</p></div><?php endif;?>
    </div>
</section>
</main>

<script>
(() => {
    const form = document.getElementById('tournament-create-form');
    const size = document.getElementById('tournament-size');
    const costText = document.getElementById('tournament-cost');
    const button = document.getElementById('tournament-submit');
    const warning = document.getElementById('tournament-insufficient');
    if (!form || !size || !costText || !button || !warning) return;

    const balance = Number(form.dataset.diamondBalance || 0);
    const updatePrice = () => {
        const option = size.options[size.selectedIndex];
        const cost = Number(option?.dataset.cost || 0);
        costText.textContent = String(cost);
        button.textContent = `CRIAR TORNEIO • ${cost} DIAMANTES`;
        const insufficient = balance < cost;
        button.disabled = insufficient;
        warning.hidden = !insufficient;
        button.setAttribute('aria-disabled', insufficient ? 'true' : 'false');
    };

    size.addEventListener('change', updatePrice);
    updatePrice();
})();
</script>

<?php afRenderBottomNav($activePage);require_once __DIR__.'/../includes/footer.php';?>
