<?php
require_once __DIR__ . '/header.php';
$db = getDB();

/**
 * Uses esc() from header.php.
 * Do NOT redeclare esc() here.
 */

// Today champion IDs
$todayChampionId = (int)($currentChampion['id'] ?? 0);
$todayDayIndex   = (int)($currentChampion['day_index'] ?? (int)date('w'));

// Progress
$level = 1; $xp = 0;
if ($todayChampionId > 0) {
  $stmt = $db->prepare("SELECT level, xp FROM champion_progress WHERE champion_id = ? LIMIT 1");
  $stmt->execute([$todayChampionId]);
  $p = $stmt->fetch();
  $level = (int)($p['level'] ?? 1);
  $xp    = (int)($p['xp'] ?? 0);
}
$level = max(1, $level);
$maxXP = $level * 100;
$xpPercent = $maxXP > 0 ? min(100, ($xp / $maxXP) * 100) : 0;

// Bounties collected by this champion
$bountiesCollected = 0;
try {
  $stmt = $db->prepare("SELECT COUNT(*) AS c FROM bounties WHERE completed = TRUE AND completed_by_champion_id = ?");
  $stmt->execute([$todayChampionId]);
  $bountiesCollected = (int)($stmt->fetch()['c'] ?? 0);
} catch (Throwable $e) { $bountiesCollected = 0; }

// Last 5 completed quests for this champion's day (Option A)
$last5 = [];
try {
  $stmt = $db->prepare("
    SELECT c.completed_date, h.name, h.xp_reward
    FROM completions c
    JOIN habits h ON h.id = c.habit_id
    WHERE c.champion_day = ?
    ORDER BY c.completed_date DESC, c.id DESC
    LIMIT 5
  ");
  $stmt->execute([$todayDayIndex]);
  $last5 = $stmt->fetchAll();
} catch (Throwable $e) { $last5 = []; }

// Bottom champions tiles
$stmt = $db->query("
  SELECT c.*, COALESCE(cp.level,1) AS level, COALESCE(cp.xp,0) AS xp
  FROM champions c
  LEFT JOIN champion_progress cp ON c.id = cp.champion_id
  ORDER BY c.day_index ASC
");
$allChampions = $stmt->fetchAll();

// Flyer + emoji fallback poster (never blank)
$flyerUrl = getChampionImage($currentChampion['name'], 'flyer');
$emoji = $currentChampion['emoji'] ?? '⭐';
$emojiSvg = "<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 240 340'>
<rect width='240' height='340' fill='%23111111'/>
<text x='50%' y='55%' text-anchor='middle' font-size='120'>{$emoji}</text>
</svg>";
$flyerFallback = "data:image/svg+xml;charset=utf-8," . rawurlencode($emojiSvg);
?>

<style>
  /* Champions page layout */
  .today-wrap{ display:grid; grid-template-columns: 260px 1fr; gap:24px; align-items:start; margin-bottom:20px; }
  .today-card{ background:rgba(0,0,0,0.75); border:2px solid var(--gold); border-radius:12px; padding:18px; }
  .today-img{ width:240px; height:340px; border-radius:12px; border:3px solid var(--primary); overflow:hidden; margin:0 auto; background:#111; }
  .today-img img{ width:100%; height:100%; object-fit:cover; display:block; }

  .today-meta h1{ margin:0; font-size:2.2rem; color:var(--primary); }
  .today-meta .sub{ color:#aaa; margin-top:6px; }
  .today-meta .tag{ color:var(--accent); font-family:'MedievalSharp', cursive; margin-top:10px; }

  .mini-stats{ display:grid; grid-template-columns: repeat(auto-fit, minmax(140px,1fr)); gap:12px; margin-top:14px; }
  .mini{ background:rgba(0,0,0,0.6); border:1px solid rgba(255,215,0,0.25); border-radius:10px; padding:12px; text-align:center; }
  .mini .lab{ color:#888; font-size:0.72rem; text-transform:uppercase; letter-spacing:1px; font-weight:900; }
  .mini .val{ color:var(--gold); font-size:1.3rem; font-weight:900; margin-top:6px; }

  .last5{ margin-top:16px; }
  .last5 h3{ color:var(--gold); margin:0 0 10px; }
  .last5 .row{ display:flex; gap:10px; align-items:center; background:rgba(255,255,255,0.05); border:1px solid #333; padding:10px; border-radius:10px; margin-bottom:8px; }
  .q-fallback{ width:42px;height:42px;border-radius:8px;background:#111;border:1px solid rgba(255,215,0,0.25);display:flex;align-items:center;justify-content:center;color:var(--gold);font-weight:900; }
  .last5 .row .nm{ color:#fff; font-weight:800; }
  .last5 .row .dt{ color:#888; font-size:0.82rem; margin-top:2px; }

  /* Bottom champion tiles (emoji circles) */
  .champ-grid{ display:grid; grid-template-columns: repeat(auto-fit, minmax(260px,1fr)); gap:18px; margin-top:20px; }
  .champ-mini{ background:rgba(0,0,0,0.75); border:2px solid var(--dark-gold); border-radius:12px; padding:16px; }
  .champ-mini .top{ display:flex; gap:12px; align-items:center; }
  .champ-mini .ava{
    width:50px; height:50px; border-radius:50%;
    border:2px solid var(--primary);
    background:#111;
    display:flex; align-items:center; justify-content:center;
    flex:0 0 auto;
    font-size:22px; color:var(--gold);
  }
  .champ-mini .n{ font-weight:900; color:#fff; margin:0; }
  .champ-mini .t{ color:#888; margin:4px 0 0; font-size:0.85rem; }
  .champ-mini .xpbar{ margin-top:12px; }

  @media (max-width: 900px){
    .today-wrap{ grid-template-columns: 1fr; }
    .today-img{ width:200px; height:280px; }
    .champ-mini .ava{ width:46px; height:46px; }
  }
</style>

<div class="today-wrap">
  <div class="today-card">
    <div class="today-img">
      <img
        src="<?php echo esc($flyerUrl); ?>"
        alt="<?php echo esc($currentChampion['name']); ?>"
        onerror="this.onerror=null; this.src='<?php echo esc($flyerFallback); ?>';"
      />
    </div>
  </div>

  <div class="today-card today-meta">
    <h1><?php echo esc($currentChampion['name']); ?></h1>
    <div class="sub"><?php echo esc($currentChampion['title']); ?> • <?php echo esc($currentChampion['role']); ?></div>
    <div class="tag">"<?php echo esc($currentChampion['tagline']); ?>"</div>

    <div class="xp-bar-container" style="margin-top:16px;">
      <div class="xp-bar-fill" style="width: <?php echo (float)$xpPercent; ?>%;">
        Level <?php echo (int)$level; ?> — <?php echo (int)$xp; ?> / <?php echo (int)$maxXP; ?> XP
      </div>
    </div>

    <div class="mini-stats">
      <div class="mini"><div class="lab">Bounties</div><div class="val"><?php echo (int)$bountiesCollected; ?></div></div>
      <div class="mini"><div class="lab">Level</div><div class="val"><?php echo (int)$level; ?></div></div>
      <div class="mini"><div class="lab">XP</div><div class="val"><?php echo (int)$xp; ?></div></div>
    </div>

    <div class="last5">
      <h3>Last 5 completed quests (<?php echo esc($currentChampion['name']); ?> days)</h3>
      <?php if (empty($last5)): ?>
        <div style="color:#666;">No completions recorded yet.</div>
      <?php else: ?>
        <?php foreach ($last5 as $r): ?>
          <div class="row">
            <div class="q-fallback">✓</div>
            <div>
              <div class="nm"><?php echo esc($r['name']); ?></div>
              <div class="dt"><?php echo esc($r['completed_date']); ?> • +<?php echo (int)$r['xp_reward']; ?> XP</div>
            </div>
          </div>
        <?php endforeach; ?>
      <?php endif; ?>
    </div>
  </div>
</div>

<!-- Ladder (unchanged file) -->
<?php require __DIR__ . '/ladder.php'; ?>

<div class="champ-grid">
  <?php foreach ($allChampions as $c): ?>
    <?php
      $lvl = max(1, (int)$c['level']);
      $cxp = (int)$c['xp'];
      $pct = min(100, ($cxp / ($lvl * 100)) * 100);
    ?>
    <div class="champ-mini" style="border-color: <?php echo esc($c['color']); ?>;">
      <div class="top">
        <div class="ava" style="border-color: <?php echo esc($c['color']); ?>;">
          <?php echo esc($c['emoji'] ?? '⭐'); ?>
        </div>
        <div>
          <div class="n"><?php echo esc($c['name']); ?></div>
          <div class="t"><?php echo esc($c['title']); ?></div>
        </div>
      </div>

      <div class="xpbar xp-bar-container" style="height:18px; margin-top:12px;">
        <div class="xp-bar-fill" style="width: <?php echo (float)$pct; ?>%; font-size:0.7rem;">
          Lvl <?php echo (int)$lvl; ?>
        </div>
      </div>

      <div style="margin-top:10px; color:#888; font-size:0.85rem;">
        XP: <span style="color:var(--gold); font-weight:900;"><?php echo (int)$cxp; ?></span>
      </div>
    </div>
  <?php endforeach; ?>
</div>

<?php require_once __DIR__ . '/footer.php'; ?>