<?php
require_once 'header.php';

$db = getDB();
$dayOfWeek = (int)date('w');

// Get habits for today
$stmt = $db->query("SELECT * FROM habits ORDER BY FIELD(time_of_day, 'morning', 'midday', 'evening')");
$habits = $stmt->fetchAll();

// Get bounties (active)
$stmt = $db->query("SELECT * FROM bounties WHERE completed = FALSE ORDER BY created_at DESC");
$bounties = $stmt->fetchAll();

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

// Stats
$stmt = $db->query("SELECT COUNT(*) as total FROM habits");
$totalQuests = (int)($stmt->fetch()['total'] ?? 0);

$stmt = $db->prepare("SELECT COUNT(*) as completed FROM completions WHERE completed_date = CURDATE()");
$stmt->execute();
$completedToday = (int)($stmt->fetch()['completed'] ?? 0);

$stmt = $db->query("SELECT COALESCE(SUM(quantity),0) as total FROM items");
$totalItems = (int)($stmt->fetch()['total'] ?? 0);

// Streak
$streak = 0;
for ($i = 0; $i < 365; $i++) {
  $date = date('Y-m-d', strtotime("-$i days"));
  $stmt = $db->prepare("SELECT COUNT(*) as count FROM completions WHERE completed_date = ?");
  $stmt->execute([$date]);
  $count = (int)($stmt->fetch()['count'] ?? 0);
  if ($count > 0) $streak++;
  else if ($i > 0) break;
}

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

// Safe emoji fallback data URI
$emoji = $currentChampion['emoji'] ?? '⭐';
$emojiSvg = "<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 120 120'>
<rect width='120' height='120' rx='12' ry='12' fill='%23111111'/>
<text x='50%' y='70%' text-anchor='middle' font-size='68'>{$emoji}</text>
</svg>";
$emojiDataUri = "data:image/svg+xml;charset=utf-8," . rawurlencode($emojiSvg);
?>

<div class="hero-section">
  <div class="champion-portrait">
    <?php echo esc(getChampionImage($currentChampion['name'], 'flyer')); ?>"
         alt="<?php echo esc($currentChampion['name']); ?>"
         onerror="this.onerror=null; this.src='<?php echo esc($emojiDataUri); ?>';">
  </div>

  <h1 class="champion-name"><?php echo esc($currentChampion['name']); ?></h1>
  <p class="champion-title"><?php echo esc($currentChampion['title']); ?> • <?php echo esc($currentChampion['role']); ?></p>
  <p class="champion-tagline">"<?php echo esc($currentChampion['tagline']); ?>"</p>

  <div class="xp-bar-container" style="margin-top: 20px;">
    <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>

<div class="stats-bar">
  <div class="stat-box">
    <div class="stat-label">Total Quests</div>
    <div class="stat-value"><?php echo (int)$totalQuests; ?></div>
  </div>
  <div class="stat-box">
    <div class="stat-label">Completed</div>
    <div class="stat-value"><?php echo (int)$completedToday; ?></div>
  </div>
  <div class="stat-box">
    <div class="stat-label">Streak</div>
    <div class="stat-value"><?php echo (int)$streak; ?></div>
  </div>
  <div class="stat-box">
    <div class="stat-label">Items</div>
    <div class="stat-value"><?php echo (int)$totalItems; ?></div>
  </div>
</div>

<div class="quest-grid">
  <?php foreach (['morning', 'midday', 'evening'] as $time): ?>
    <div class="quest-category">
      <div class="category-header">
        <span class="category-icon"><?php echo $time === 'morning' ? '🌅' : ($time === 'midday' ? '☀️' : '🌙'); ?></span>
        <span class="category-title"><?php echo esc(ucfirst($time)); ?> Quests</span>
      </div>

      <div class="quest-list">
        <?php
          $timeHabits = array_filter($habits, fn($h) => ($h['time_of_day'] ?? '') === $time);
          if (empty($timeHabits)):
        ?>
          <p style="color:#666; text-align:center; padding:20px;">No quests available</p>
        <?php else: ?>
          <?php foreach ($timeHabits as $habit):
            $stmt = $db->prepare("SELECT id FROM completions WHERE habit_id = ? AND completed_date = CURDATE()");
            $stmt->execute([$habit['id']]);
            $isCompleted = (bool)$stmt->fetch();
          ?>
            <div class="quest-item <?php echo $isCompleted ? 'quest-complete' : ''; ?>"
                 onclick="completeHabit(<?php echo (int)$habit['id']; ?>)">
              <div class="quest-info">
                <?php if (!empty($habit['image_path'])): ?>
                  <?php echo esc($habit['image_path']); ?>" alt="" class="quest-img">
                <?php endif; ?>
                <div>
                  <div class="quest-name"><?php echo esc($habit['name']); ?></div>
                  <div class="quest-desc"><?php echo esc($habit['description']); ?></div>
                </div>
              </div>
              <span class="quest-xp"><?php echo $isCompleted ? '✓' : ('+' . (int)$habit['xp_reward'] . ' XP'); ?></span>
            </div>
          <?php endforeach; ?>
        <?php endif; ?>
      </div>
    </div>
  <?php endforeach; ?>
</div>

<div class="quest-category mt-20">
  <div class="category-header">
    <span class="category-icon">💰</span>
    <span class="category-title">Active Bounties</span>
  </div>

  <div class="quest-list">
    <?php if (empty($bounties)): ?>
      <p style="color:#666; text-align:center;">No active bounties</p>
    <?php else: ?>
      <?php foreach ($bounties as $bounty): ?>
        <div class="quest-item" onclick="completeBounty(<?php echo (int)$bounty['id']; ?>)">
          <div class="quest-info">
            <?php if (!empty($bounty['image_path'])): ?>
              <?php echo esc($bounty['image_path']); ?>" alt="" class="quest-img">
            <?php endif; ?>
            <div>
              <div class="quest-name"><?php echo esc($bounty['name']); ?></div>
              <div class="quest-desc"><?php echo esc($bounty['description']); ?></div>
            </div>
          </div>
          <span class="quest-xp">+<?php echo (int)$bounty['xp_reward']; ?> XP</span>
        </div>
      <?php endforeach; ?>
    <?php endif; ?>
  </div>
</div>

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