<?php
/** AURA FARMING — Etapa 9: central de progressão e recompensas */
require_once __DIR__.'/../config/config.php';
require_once __DIR__.'/../config/database.php';
require_once __DIR__.'/../includes/functions.php';
require_once __DIR__.'/../includes/progression_functions.php';
requireLogin();
$uid=(int)$_SESSION['usuario_id'];
recarregarSessaoUsuario($pdo,$uid);$u=usuarioAtual();
afGarantirProgressao($pdo,$uid);
$nivelAtual=calcularNivel((int)$u['xp_total']);
afSincronizarRecompensas($pdo,$uid,$nivelAtual);
verificarConquistas($pdo,$u);
recarregarSessaoUsuario($pdo,$uid);$u=usuarioAtual();

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==='resgatar_missao'){
                $r=afResgatarMissao($pdo,$uid,(int)($_POST['usuario_missao_id']??0));
                setFlash('success','Missão resgatada: +'.$r['xp'].' XP!');
            }elseif($acao==='equipar'){
                $r=afEquiparRecompensa($pdo,$uid,(int)($_POST['recompensa_id']??0));
                setFlash('success',$r['nome'].' foi equipada.');
            }else throw new RuntimeException('Ação inválida.');
        }catch(Throwable $e){setFlash('error',$e->getMessage());}
    }
    header('Location: '.SITE_URL.'/pages/recompensas.php');exit;
}

$resumo=afResumoProgressao($pdo,$uid);$recompensas=afListarRecompensas($pdo,$uid);$historicoXp=afHistoricoXp($pdo,$uid,12);
$porTipo=['titulo'=>[],'moldura'=>[],'cor_aura'=>[],'efeito_aura'=>[]];foreach($recompensas as $r)$porTipo[$r['tipo']][]=$r;
$labels=['titulo'=>['Títulos','🏷️'],'moldura'=>['Molduras','⭕'],'cor_aura'=>['Cores de Aura','🌈'],'efeito_aura'=>['Efeitos de Aura','✨']];
$equip=$resumo['equipamentos'];$auraColor=$equip['cor_aura_valor']??'#00d4ff';
$agora=new DateTimeImmutable('now');$fimDia=$agora->setTime(23,59,59);$fimSemana=$agora->modify('sunday this week')->setTime(23,59,59);
$pageTitle='Progressão';$activePage='perfil';$bodyClass='rewards-body';require_once __DIR__.'/../includes/header.php';
?>
<header class="app-header"><a class="btn-back" href="<?=SITE_URL?>/pages/home.php">← Início</a><div class="logo-inline"><span class="logo-main">PROGRESSÃO</span><span class="logo-sub">ETAPA 8</span></div><a href="<?=SITE_URL?>/pages/perfil.php" class="btn-notif" aria-label="Perfil">👤</a></header>
<main class="page-content rewards-page" style="--equipped-aura-color:<?=esc($auraColor)?>">
<?=renderFlash()?>
<section class="progression-hero card card--glow">
  <div class="progression-orbit" aria-hidden="true"></div>
  <div class="progression-level"><small>NÍVEL ATUAL</small><strong><?= (int)$resumo['nivel']['nivel']?></strong></div>
  <div class="progression-main"><span class="badge-titulo">⭐ <?=esc($equip['titulo_valor']??$resumo['nivel']['titulo'])?></span><h1><?=esc($u['nome'])?></h1><p><?=formatarNumero((float)$resumo['nivel']['xp_total'])?> XP acumulado</p>
    <div class="progress-bar-wrap"><div class="progress-bar-fill" style="width:<?=$resumo['nivel']['percentual']?>%"></div></div>
    <div class="level-nums"><span><?=formatarNumero((float)$resumo['nivel']['xp_atual'])?> XP</span><span>Nv <?= (int)$resumo['nivel']['nivel']+1?> • <?=formatarNumero((float)$resumo['nivel']['xp_necessario'])?> XP</span></div>
  </div>
</section>

<section class="progression-summary">
  <article><span>🔥</span><small>SEQUÊNCIA</small><strong><?= (int)$resumo['sequencia_atual']?> dias</strong><em>Recorde: <?= (int)$resumo['melhor_sequencia']?></em></article>
  <article><span>🎁</span><small>RECOMPENSAS</small><strong><?= (int)$resumo['recompensas_desbloqueadas']?></strong><em>desbloqueadas</em></article>
  <article><span>🎯</span><small>PRONTAS</small><strong><?= (int)$resumo['missoes_prontas']?></strong><em>para resgatar</em></article>
</section>

<div class="section-title">🎯 Missões atuais</div>
<section class="mission-section card">
  <div class="mission-heading"><div><strong>DIÁRIAS</strong><small>Reiniciam à meia-noite</small></div><span>⏱ <?=$agora->diff($fimDia)->format('%hh %Im')?></span></div>
  <?php foreach($resumo['missoes']['diaria'] as $m): $pct=min(100,round(((int)$m['progresso']/max(1,(int)$m['meta']))*100)); ?>
    <article class="mission-card <?=!empty($m['concluida_em'])?'is-complete':''?> <?=!empty($m['resgatada_em'])?'is-claimed':''?>">
      <div class="mission-icon"><?=esc($m['icone'])?></div><div class="mission-content"><strong><?=esc($m['nome'])?></strong><p><?=esc($m['descricao'])?></p><div class="mission-progress"><div style="width:<?=$pct?>%"></div></div><small><?=min((int)$m['progresso'],(int)$m['meta'])?> / <?= (int)$m['meta']?></small></div>
      <div class="mission-reward"><b>+<?= (int)$m['xp_recompensa']?> XP</b><?php if(!empty($m['resgatada_em'])):?><span>✓ RESGATADO</span><?php elseif(!empty($m['concluida_em'])):?><form method="post"><?=camposCsrf()?><input type="hidden" name="acao" value="resgatar_missao"><input type="hidden" name="usuario_missao_id" value="<?= (int)$m['usuario_missao_id']?>"><button>RESGATAR</button></form><?php else:?><span>EM PROGRESSO</span><?php endif;?></div>
    </article>
  <?php endforeach;?>
</section>
<section class="mission-section card">
  <div class="mission-heading"><div><strong>SEMANAIS</strong><small>Metas maiores, prêmios maiores</small></div><span>⏱ <?=$agora->diff($fimSemana)->format('%d d %h h')?></span></div>
  <?php foreach($resumo['missoes']['semanal'] as $m): $pct=min(100,round(((int)$m['progresso']/max(1,(int)$m['meta']))*100)); ?>
    <article class="mission-card <?=!empty($m['concluida_em'])?'is-complete':''?> <?=!empty($m['resgatada_em'])?'is-claimed':''?>">
      <div class="mission-icon"><?=esc($m['icone'])?></div><div class="mission-content"><strong><?=esc($m['nome'])?></strong><p><?=esc($m['descricao'])?></p><div class="mission-progress"><div style="width:<?=$pct?>%"></div></div><small><?=min((int)$m['progresso'],(int)$m['meta'])?> / <?= (int)$m['meta']?></small></div>
      <div class="mission-reward"><b>+<?= (int)$m['xp_recompensa']?> XP</b><?php if(!empty($m['resgatada_em'])):?><span>✓ RESGATADO</span><?php elseif(!empty($m['concluida_em'])):?><form method="post"><?=camposCsrf()?><input type="hidden" name="acao" value="resgatar_missao"><input type="hidden" name="usuario_missao_id" value="<?= (int)$m['usuario_missao_id']?>"><button>RESGATAR</button></form><?php else:?><span>EM PROGRESSO</span><?php endif;?></div>
    </article>
  <?php endforeach;?>
</section>

<div class="section-title">🎁 Coleção de recompensas</div>
<?php foreach($porTipo as $tipo=>$itens):?>
<section class="reward-group"><div class="reward-group-title"><span><?=$labels[$tipo][1]?></span><strong><?=$labels[$tipo][0]?></strong><small><?=count(array_filter($itens,fn($r)=>!empty($r['desbloqueada_em'])))?> / <?=count($itens)?></small></div><div class="reward-grid">
<?php foreach($itens as $r): $unlocked=!empty($r['desbloqueada_em']); ?>
<article class="reward-card rarity-<?=esc($r['raridade'])?> <?=$unlocked?'is-unlocked':'is-locked'?> <?=!empty($r['equipada'])?'is-equipped':''?>">
  <div class="reward-preview reward-preview--<?=esc($r['tipo'])?>" <?php if($r['tipo']==='cor_aura'):?>style="--reward-color:<?=esc($r['valor_visual'])?>"<?php endif;?>><?=esc($r['icone'])?></div>
  <span class="reward-rarity"><?=strtoupper(esc($r['raridade']))?></span><strong><?=esc($r['nome'])?></strong><p><?=esc($r['descricao'])?></p><small>DESBLOQUEIA NO NÍVEL <?= (int)$r['nivel_min']?></small>
  <?php if(!empty($r['equipada'])):?><button class="reward-equipped" disabled>✓ EQUIPADA</button><?php elseif($unlocked):?><form method="post"><?=camposCsrf()?><input type="hidden" name="acao" value="equipar"><input type="hidden" name="recompensa_id" value="<?= (int)$r['id']?>"><button class="reward-equip">EQUIPAR</button></form><?php else:?><button class="reward-locked" disabled>🔒 BLOQUEADA</button><?php endif;?>
</article>
<?php endforeach;?></div></section>
<?php endforeach;?>

<div class="section-title">⭐ XP recente</div>
<section class="card xp-history"><?php if(!$historicoXp):?><p class="empty-inline">Seu histórico de XP aparecerá aqui.</p><?php else:foreach($historicoXp as $x):?><article><span><?=match($x['tipo']){'partida'=>'🔥','missao'=>'🎯','conquista'=>'🏅',default=>'⭐'}?></span><div><strong><?=esc($x['descricao']?:ucfirst($x['tipo']))?></strong><small><?=date('d/m/Y H:i',strtotime($x['criado_em']))?></small></div><b>+<?= (int)$x['xp']?> XP</b></article><?php endforeach;endif;?></section>
</main>
<?php require_once __DIR__.'/../includes/navbar.php';require_once __DIR__.'/../includes/footer.php';?>
