<?php
require_once __DIR__ . '/header.php';

$db = getDB();

$year  = (int)($_GET['year'] ?? date('Y'));
$month = (int)($_GET['month'] ?? date('n'));
if ($month < 1) $month = 1;
if ($month > 12) $month = 12;

$firstDay    = (int)date('w', strtotime("$year-$month-1"));
$daysInMonth = cal_days_in_month(CAL_GREGORIAN, $month, $year);

$startDate = sprintf("%04d-%02d-01", $year, $month);
$endDate   = sprintf("%04d-%02d-%02d", $year, $month, $daysInMonth);

// Completions for month: date => count
$stmt = $db->prepare("
  SELECT completed_date, COUNT(*) as count
  FROM completions
  WHERE completed_date BETWEEN ? AND ?
  GROUP BY completed_date
");
$stmt->execute([$startDate, $endDate]);
$completions = $stmt->fetchAll(PDO::FETCH_KEY_PAIR);

$days = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];

$prevYear  = ($month == 1) ? $year - 1 : $year;
$prevMonth = ($month == 1) ? 12 : $month - 1;
$nextYear  = ($month == 12) ? $year + 1 : $year;
$nextMonth = ($month == 12) ? 1 : $month + 1;

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

function emojiDataUriLocal(string $emoji): string {
  $emoji = $emoji ?: '⭐';
  $svg = "<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 120 120'>
<rect width='120' height='120' rx='60' ry='60' fill='%23111111'/>
<text x='50%' y='70%' text-anchor='middle' font-size='68'>{$emoji}</text>
</svg>";
  return "data:image/svg+xml;charset=utf-8," . rawurlencode($svg);
}
?>
<h2 class="text-center mb-20" style="color: var(--gold);">📅 Quest Log</h2>

<div style="text-align:center; margin-bottom:20px;">
  <a href="?year=<?php echo (int)$prevYear; ?>&month=<?php echo (int)$prevMonth; ?>" class="nav-btn">&lt; Prev</a>

  <span style="margin:0 20px; font-size:1.3rem; color:var(--gold);">
    <?php echo _e(date('F Y', strtotime("$year-$month-1"))); ?>
  </span>

  <a href="?year=<?php echo (int)$nextYear; ?>&month=<?php echo (int)$nextMonth; ?>" class="nav-btn">Next &gt;</a>
</div>

<div style="background: rgba(0,0,0,0.8); padding: 20px; border-radius: 10px; border: 2px solid var(--gold);">
  <div class="calendar-grid">
    <?php foreach ($days as $dayName): ?>
      <div class="calendar-header"><?php echo _e($dayName); ?></div>
    <?php endforeach; ?>

    <?php for ($i = 0; $i < $firstDay; $i++): ?>
      <div class="calendar-day" style="opacity:0.3;"></div>
    <?php endfor; ?>

    <?php for ($d = 1; $d <= $daysInMonth; $d++):
      $date = sprintf("%04d-%02d-%02d", $year, $month, $d);
      $dayOfWeek = (int)date('w', strtotime($date));

      $isToday = ($date === date('Y-m-d'));
      $hasCompletion = isset($completions[$date]) && ((int)$completions[$date] > 0);

      // Champion for that weekday
      $stmt = $db->prepare("SELECT name, emoji FROM champions WHERE day_index = ? LIMIT 1");
      $stmt->execute([$dayOfWeek]);
      $dayChampion = $stmt->fetch() ?: [];

      $champName  = $dayChampion['name'] ?? 'Unknown';
      $champEmoji = $dayChampion['emoji'] ?? '⭐';

      // ✅ Use AVATAR icon in calendar
      $avatarUrl = getChampionImage($champName, 'avatar');

      // Fallback emoji circle if avatar missing
      $fallback = emojiDataUriLocal($champEmoji);
    ?>
      <div
        class="calendar-day <?php echo $isToday ? 'today' : ''; ?> <?php echo $hasCompletion ? 'completed' : ''; ?>"
        onclick="showDayDetails(<?php echo (int)$year; ?>, <?php echo (int)$month; ?>, <?php echo (int)$d; ?>)"
      >
        <div class="day-number"><?php echo (int)$d; ?></div>

        <img
          class="day-champion"
          src="<?php echo _e($avatarUrl); ?>"
          alt="<?php echo _e($champName); ?>"
          onerror="this.onerror=null; this.src='<?php echo _e($fallback); ?>';"
        />
      </div>
    <?php endfor; ?>
  </div>
</div>

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