<?php
$pageTitle  = 'Significant Events';
$activePage = 'events';
require_once __DIR__ . '/../src/includes/layout.php';

$db = Database::getInstance();

// Which event are we viewing?
$eventId = isset($_GET['id']) ? (int)$_GET['id'] : 0;
$view    = $_GET['view'] ?? 'list';   // list | read | quiz

// Load all events for the list
$allEvents = $db->query('SELECT id, title, category, book_ref, chapter_ref, summary FROM events ORDER BY sort_order')->fetchAll(PDO::FETCH_ASSOC);

// Load single event if needed
$event = null;
$questions = [];
if ($eventId > 0 && in_array($view, ['read','quiz'])) {
    $stmt = $db->prepare('SELECT * FROM events WHERE id = ?');
    $stmt->execute([$eventId]);
    $event = $stmt->fetch(PDO::FETCH_ASSOC);
    if (!$event) { $eventId = 0; $view = 'list'; }

    if ($view === 'quiz') {
        $stmt = $db->prepare('SELECT * FROM quiz_questions WHERE entity_type = ? AND entity_id = ? ORDER BY sort_order');
        $stmt->execute(['event', $eventId]);
        $questions = $stmt->fetchAll(PDO::FETCH_ASSOC);
    }
}

// Best quiz result for this event
$bestScore = null;
if ($eventId > 0) {
    $stmt = $db->prepare('SELECT score, total FROM quiz_results WHERE user_id = ? AND entity_type = ? AND entity_id = ? ORDER BY score DESC LIMIT 1');
    $stmt->execute([$userId, 'event', $eventId]);
    $bestScore = $stmt->fetch(PDO::FETCH_ASSOC);
}

// Best scores for list view
$myBest = [];
$stmt = $db->prepare('SELECT entity_id, MAX(score) as best_score, MAX(total) as total FROM quiz_results WHERE user_id = ? AND entity_type = ? GROUP BY entity_id');
$stmt->execute([$userId, 'event']);
foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
    $myBest[$row['entity_id']] = $row;
}
?>

<?php if ($view === 'list'): ?>
<!-- ═══════════════════════════════════════ LIST VIEW ═══════════════════════ -->
<div class="ep-header">
  <div class="ep-header-icon">⚡</div>
  <div>
    <h2 class="ep-header-title">Significant Events</h2>
    <p class="ep-header-sub">Explore the defining moments of the New Testament — read each account in depth, then test your knowledge with a quiz.</p>
  </div>
</div>

<div class="ep-grid">
  <?php foreach ($allEvents as $ev): ?>
  <?php
    $best   = $myBest[$ev['id']] ?? null;
    $pct    = $best ? round($best['best_score'] / $best['total'] * 100) : null;
    $badgeClass = '';
    if ($pct !== null) {
      if ($pct >= 80) $badgeClass = 'badge-gold';
      elseif ($pct >= 60) $badgeClass = 'badge-silver';
      else $badgeClass = 'badge-bronze';
    }
  ?>
  <div class="ep-card" onclick="location.href='/events.php?id=<?= $ev['id'] ?>&view=read'">
    <div class="ep-card-top">
      <div class="ep-card-ref"><?= htmlspecialchars($ev['chapter_ref']) ?></div>
      <?php if ($pct !== null): ?>
        <div class="ep-badge <?= $badgeClass ?>" title="Best quiz score"><?= $pct ?>%</div>
      <?php else: ?>
        <div class="ep-badge badge-new">New</div>
      <?php endif; ?>
    </div>
    <h3 class="ep-card-title"><?= htmlspecialchars($ev['title']) ?></h3>
    <p class="ep-card-summary"><?= htmlspecialchars($ev['summary']) ?></p>
    <div class="ep-card-footer">
      <span class="ep-card-action">Read & Study →</span>
      <?php if ($pct !== null): ?>
        <span class="ep-card-retake">Retake quiz</span>
      <?php endif; ?>
    </div>
  </div>
  <?php endforeach; ?>
</div>

<?php elseif ($view === 'read'): ?>
<!-- ═══════════════════════════════════════ READ VIEW ══════════════════════ -->
<div class="ep-read-wrap">
  <div class="ep-breadcrumb">
    <a href="/events.php">← All Events</a>
    <span class="ep-crumb-sep">/</span>
    <span><?= htmlspecialchars($event['title']) ?></span>
  </div>

  <article class="ep-article">
