<?php
require_once 'header.php';

$db = getDB();

/**
 * TEMP DEBUG LOG (safe while you’re sorting this)
 * Writes PHP errors to /RPG/php-calendar-error.log
 * Delete these 3 lines once fixed.
 */
ini_set('log_errors', '1');
ini_set('error_log', __DIR__ . '/php-calendar-error.log');
error_reporting(E_ALL);

$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'];

// Prev/Next links
$prevYear  = ($month == 1) ? $year - 1 : $year;
$prevMonth = ($month == 1) ? 12 : $month - 1;

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

?>
<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 htmlspecialchars(date('F Y', strtotime("$year-$month-1")), ENT_QUOTES, 'UTF-8'); ?>
  </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 htmlspecialchars($dayName, ENT_QUOTES, 'UTF-8'); ?></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 day
      $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 image for calendar (small icon)
      $avatarUrl = getChampionImage($champName, 'avatar');

      // Emoji fallback (data URI)
      $emojiSvg = "<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'>{$champEmoji}</text>"
                . "</svg>";
      $fallbackUri = "data:image/svg+xml;charset=utf-8," . rawurlencode($emojiSvg);
    ?>
      <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 htmlspecialchars($avatarUrl, ENT_QUOTES, 'UTF-8'); ?>"
          alt="<?php echo htmlspecialchars($champName, ENT_QUOTES, 'UTF-8'); ?>"
          onerror="this.onerror=null; this.src='<?php echo htmlspecialchars($fallbackUri, ENT_QUOTES, 'UTF-8'); ?>';"
        />
      </div>
    <?php endfor; ?>
  </div>
</div>

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