<?php
// ladder.php (partial) — expects $db available OR will create it.
if (!isset($db)) {
  require_once __DIR__ . '/config.php';
  $db = getDB();
}

if (!function_exists('esc')) {
  function esc($v): string { return htmlspecialchars((string)$v, ENT_QUOTES, 'UTF-8'); }
}

/**
 * Next playable date for champion based on day_index (0=Sun..6=Sat)
 */
function nextPlayableLabel(int $champDayIndex): string {
  $todayIndex = (int)date('w');
  $delta = ($champDayIndex - $todayIndex + 7) % 7;
  if ($delta === 0) return 'Today';
  if ($delta === 1) return 'Tomorrow';
  return date('D d M', strtotime("+$delta days"));
}

/**
 * Load champions with progress + bounty count
 */
$stmt = $db->query("
  SELECT
    c.*,
    COALESCE(cp.level, 1) AS level,
    COALESCE(cp.xp, 0) AS xp,
    (
      SELECT COUNT(*)
      FROM bounties b
      WHERE b.completed = TRUE
        AND b.completed_by_champion_id = c.id
    ) AS bounty_count
  FROM champions c
  LEFT JOIN champion_progress cp ON c.id = cp.champion_id
  ORDER BY level DESC, xp DESC
");
$champions = $stmt->fetchAll();

/**
 * Load badges (completed bounties) for all champions and group them
 */
$badgeMap = [];
try {
  $stmt = $db->query("
    SELECT
      id, name, description, xp_reward, image_path, completed_date, completed_by_champion_id
    FROM bounties
    WHERE completed = TRUE
      AND completed_by_champion_id IS NOT NULL
    ORDER BY completed_date DESC, id DESC
  ");
  $badges = $stmt->fetchAll();
  foreach ($badges as $b) {
    $cid = (int)$b['completed_by_champion_id'];
    if (!isset($badgeMap[$cid])) $badgeMap[$cid] = [];
    $badgeMap[$cid][] = $b;
  }
} catch (Throwable $e) {
  $badgeMap = [];
}

function fmtDate(?string $ymd): string {
  if (!$ymd) return 'Unknown';
  $ts = strtotime($ymd);
  return $ts ? date('d M Y', $ts) : $ymd;
}
?>

<div class="ladder-container mb-20">
  <div class="ladder-header">
    <h2 style="color: var(--gold); font-size: 1.8rem;">🏆 Champion Ladder 🏆</h2>
    <p style="color: #888; margin-top: 5px;">All-Time Legend Rankings</p>
  </div>

  <!-- Column headers (like your mockup) -->
  <div class="ladder5 head">
    <div class="h">Name</div>
    <div class="h">Level</div>
    <div class="h">Bounties Collected</div>
    <div class="h">Overall XP</div>
    <div class="h">Next playable date</div>
  </div>

  <?php foreach ($champions as $i => $champ): ?>
    <?php
      $rank = $i + 1;
      $cid  = (int)$champ['id'];
      $badges = $badgeMap[$cid] ?? [];
      $badgeCount = count($badges);
      $badgeShow = array_slice($badges, 0, 7); // show 7 then +N
      $nextLabel = nextPlayableLabel((int)$champ['day_index']);
      $avatarUrl = getChampionImage($champ['name'], 'avatar');
    ?>

    <div class="ladder5 row">
      <!-- Name -->
      <div class="namecell">
        <div class="rk">#<?php echo (int)$rank; ?></div>
        <div class="who">
          <div class="ava">
            <img src="<?php echo esc($avatarUrl); ?>" alt="<?php echo esc($champ['name']); ?>"
                 onerror="this.style.display='none'; this.parentElement.querySelector('.emo').style.display='flex';">
            <div class="emo" style="display:none;"><?php echo esc($champ['emoji']); ?></div>
          </div>
          <div class="info">
            <div class="nm"><?php echo esc($champ['name']); ?></div>
            <div class="tt"><?php echo esc($champ['title']); ?></div>
          </div>
        </div>
      </div>

      <!-- Level -->
      <div class="cent">
        <div class="big"><?php echo (int)$champ['level']; ?></div>
        <div class="small">Level</div>
      </div>

      <!-- Badges -->
      <div class="badges">
        <?php if ($badgeCount === 0): ?>
          <div class="none">—</div>
        <?php else: ?>
          <div class="strip">
            <?php foreach ($badgeShow as $b): ?>
              <?php
                $img = $b['image_path'] ?? '';
                $ach = fmtDate($b['completed_date'] ?? null);
                $bxp = (int)($b['xp_reward'] ?? 0);
              ?>
              <div class="badge" tabindex="0">
                <?php if ($img): ?>
                  <img src="<?php echo esc($img); ?>" alt="<?php echo esc($b['name']); ?>"
                       onerror="this.style.display='none'; this.parentElement.querySelector('.fallback').style.display='flex';">
                <?php endif; ?>
                <div class="fallback" style="<?php echo $img ? 'display:none;' : 'display:flex;'; ?>">🏅</div>

                <div class="pop">
                  <div class="pt"><?php echo esc($b['name']); ?></div>
                  <?php if ($img): ?>
                    <img class="pimg" src="<?php echo esc($img); ?>" alt="<?php echo esc($b['name']); ?>">
                  <?php endif; ?>
                  <div class="meta">
                    <div><b>Achieved:</b> <?php echo esc($ach); ?></div>
                    <div><b>XP:</b> <?php echo (int)$bxp; ?></div>
                  </div>
                  <?php if (!empty($b['description'])): ?>
                    <div class="desc"><?php echo nl2br(esc($b['description'])); ?></div>
                  <?php endif; ?>
                </div>
              </div>
            <?php endforeach; ?>

            <?php if ($badgeCount > 7): ?>
              <div class="badge more">+<?php echo (int)($badgeCount - 7); ?></div>
            <?php endif; ?>
          </div>
        <?php endif; ?>

        <div class="countline">
          <span class="cnt"><?php echo (int)$badgeCount; ?></span>
          <span class="lbl">total</span>
        </div>
      </div>

      <!-- Overall XP -->
      <div class="cent">
        <div class="big"><?php echo (int)$champ['xp']; ?></div>
        <div class="small">XP</div>
      </div>

      <!-- Next playable -->
      <div class="cent">
        <div class="pill <?php echo $nextLabel === 'Today' ? 'today' : ($nextLabel === 'Tomorrow' ? 'tomorrow' : ''); ?>">
          <?php echo esc($nextLabel); ?>
        </div>
      </div>
    </div>
  <?php endforeach; ?>
</div>