<?php
require_once 'includes/config.php';
requireLogin();
$uid = $_SESSION['user_id'];

// ── Safe self-migration: add SM-2 columns to flashcards ────────────────
foreach ([
    "ALTER TABLE flashcards ADD COLUMN ease_factor DECIMAL(3,2) DEFAULT 2.5",
    "ALTER TABLE flashcards ADD COLUMN interval_days INT DEFAULT 0",
    "ALTER TABLE flashcards ADD COLUMN repetitions INT DEFAULT 0",
    "ALTER TABLE flashcards ADD COLUMN next_review_date DATE DEFAULT NULL",
] as $sql) {
    try { $pdo->exec($sql); } catch (PDOException $e) {}
}
// Backfill any cards that have never been scheduled → due today
try { $pdo->exec("UPDATE flashcards SET next_review_date = CURDATE() WHERE next_review_date IS NULL"); } catch (PDOException $e) {}

// ── SM-2 algorithm ──────────────────────────────────────────────────────
function sm2Update($ef, $reps, $interval, $quality) {
    $quality = max(0, min(5, (int)$quality));
    if ($quality < 3) {
        $reps = 0;
        $interval = 1;
    } else {
        if ($reps == 0) $interval = 1;
        elseif ($reps == 1) $interval = 6;
        else $interval = (int)round($interval * $ef);
        $reps++;
    }
    $ef = $ef + (0.1 - (5 - $quality) * (0.08 + (5 - $quality) * 0.02));
    if ($ef < 1.3) $ef = 1.3;
    return [round($ef, 2), $reps, $interval];
}

// ── AJAX handler ────────────────────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_SERVER['HTTP_X_REQUESTED_WITH'])) {
    $action = $_POST['action'] ?? '';

    if ($action === 'submit_review') {
        $id      = (int)($_POST['id'] ?? 0);
        $quality = (int)($_POST['quality'] ?? 0);

        $row = $pdo->prepare("SELECT ease_factor,repetitions,interval_days FROM flashcards WHERE id=? AND user_id=?");
        $row->execute([$id, $uid]); $row = $row->fetch();
        if (!$row) jsonResponse(['success'=>false,'message'=>'Card not found.']);

        $ef = $row['ease_factor'] ?: 2.5;
        [$newEf, $newReps, $newInterval] = sm2Update($ef, (int)$row['repetitions'], (int)$row['interval_days'], $quality);
        $nextDate = date('Y-m-d', strtotime("+{$newInterval} days"));

        $pdo->prepare("UPDATE flashcards SET ease_factor=?, repetitions=?, interval_days=?, next_review_date=?, times_reviewed=times_reviewed+1, last_reviewed=NOW() WHERE id=? AND user_id=?")
            ->execute([$newEf, $newReps, $newInterval, $nextDate, $id, $uid]);

        jsonResponse(['success'=>true, 'next_review_date'=>$nextDate, 'interval_days'=>$newInterval]);
    }
}

// ── Data for page render ───────────────────────────────────────────────
$subjects = $pdo->prepare("SELECT id,name,color FROM subjects WHERE user_id=? ORDER BY name");
$subjects->execute([$uid]); $subjects = $subjects->fetchAll();

$dueStmt = $pdo->prepare("SELECT f.*, s.name as subject_name, s.color as subject_color FROM flashcards f LEFT JOIN subjects s ON f.subject_id=s.id WHERE f.user_id=? AND f.next_review_date <= CURDATE() ORDER BY RAND()");
$dueStmt->execute([$uid]); $dueCards = $dueStmt->fetchAll();

$totalStmt = $pdo->prepare("SELECT COUNT(*) FROM flashcards WHERE user_id=?");
$totalStmt->execute([$uid]); $totalCards = (int)$totalStmt->fetchColumn();

$upcomingStmt = $pdo->prepare("SELECT COUNT(*) FROM flashcards WHERE user_id=? AND next_review_date = CURDATE() + INTERVAL 1 DAY");
$upcomingStmt->execute([$uid]); $upcomingTomorrow = (int)$upcomingStmt->fetchColumn();

require_once 'includes/header.php';
renderHeader('Flashcard Review', 'flashcards-review');
?>

<style>
.cs-overlay { position:fixed; inset:0; background:radial-gradient(ellipse at center, rgba(30,24,10,.55) 0%, rgba(0,0,0,.88) 100%); backdrop-filter:blur(14px) saturate(140%); -webkit-backdrop-filter:blur(14px) saturate(140%); display:flex; align-items:center; justify-content:center; z-index:9999; padding:20px; animation:csFade .35s ease; }
@keyframes csFade { from{opacity:0;} to{opacity:1;} }
.cs-modal { position:relative; background:linear-gradient(160deg, rgba(40,32,14,.55) 0%, rgba(18,16,12,.65) 100%); border:1px solid rgba(212,175,55,.35); border-radius:24px; padding:46px 36px; max-width:400px; width:100%; text-align:center; backdrop-filter:blur(20px); -webkit-backdrop-filter:blur(20px); box-shadow:0 25px 70px rgba(0,0,0,.55), 0 0 0 1px rgba(255,215,120,.06) inset, 0 1px 0 rgba(255,235,180,.15) inset; animation:csPop .45s cubic-bezier(.2,.9,.25,1.1); overflow:hidden; }
.cs-modal::before { content:''; position:absolute; top:-40%; left:-20%; width:140%; height:140%; background:conic-gradient(from 0deg, transparent, rgba(212,175,55,.18), transparent 30%); animation:csSheen 6s linear infinite; pointer-events:none; }
.cs-modal::after { content:''; position:absolute; inset:0; border-radius:24px; padding:1px; background:linear-gradient(135deg, rgba(255,223,140,.6), rgba(212,175,55,0) 40%, rgba(212,175,55,0) 60%, rgba(255,223,140,.4)); -webkit-mask:linear-gradient(#fff 0 0) content-box, linear-gradient(#fff 0 0); -webkit-mask-composite:xor; mask-composite:exclude; pointer-events:none; }
@keyframes csSheen { to { transform:rotate(360deg); } }
@keyframes csPop { from{opacity:0; transform:scale(.9) translateY(16px);} to{opacity:1; transform:scale(1) translateY(0);} }
.cs-emoji { position:relative; font-size:50px; margin-bottom:16px; filter:drop-shadow(0 0 18px rgba(255,205,90,.55)); animation:csFloat 3s ease-in-out infinite; }
@keyframes csFloat { 0%,100%{transform:translateY(0);} 50%{transform:translateY(-6px);} }
.cs-title { position:relative; font-size:24px; font-weight:800; font-family:'Sora',sans-serif; margin-bottom:12px; letter-spacing:.3px; background:linear-gradient(135deg,#fff3cf,#d4af37 45%,#f6e27a 65%,#b8860b); -webkit-background-clip:text; background-clip:text; -webkit-text-fill-color:transparent; }
.cs-desc { position:relative; font-size:14px; color:rgba(240,225,190,.75); line-height:1.7; margin-bottom:28px; }
.cs-btn { position:relative; display:inline-flex; align-items:center; justify-content:center; gap:8px; width:100%; padding:14px 20px; border:1px solid rgba(255,223,140,.5); border-radius:14px; background:linear-gradient(135deg,#f6e27a,#d4af37 50%,#b8860b); color:#241a05; font-size:14px; font-weight:700; font-family:'Sora',sans-serif; letter-spacing:.2px; cursor:pointer; box-shadow:0 10px 30px rgba(212,175,55,.35), 0 1px 0 rgba(255,245,210,.6) inset; transition:transform .18s ease, box-shadow .18s ease; }
.cs-btn:hover { transform:translateY(-2px); box-shadow:0 14px 36px rgba(212,175,55,.45), 0 1px 0 rgba(255,245,210,.7) inset; }
.cs-btn:active { transform:translateY(0); }

.fr-page-header { display:flex; align-items:center; justify-content:space-between; gap:16px; margin-bottom:20px; flex-wrap:wrap; }
.fr-page-title { font-size:22px; font-weight:800; color:var(--text-primary); font-family:'Sora',sans-serif; letter-spacing:-.3px; }
.fr-page-sub { font-size:13px; color:var(--text-muted); margin-top:4px; }

.fr-stat-row { display:grid; grid-template-columns:repeat(3,1fr); gap:12px; margin-bottom:22px; }
.fr-stat-card { background:var(--bg-card); border:1px solid var(--border); border-radius:14px; padding:16px; text-align:center; }
.fr-stat-num { font-size:26px; font-weight:800; font-family:'Sora',sans-serif; color:var(--text-primary); }
.fr-stat-label { font-size:11px; color:var(--text-muted); text-transform:uppercase; letter-spacing:.5px; margin-top:4px; }

.fr-card-wrap { perspective:1200px; max-width:560px; margin:0 auto 20px; }
.fr-flip-card { min-height:220px; background:var(--bg-card); border:1px solid var(--border); border-radius:18px; padding:36px 28px; display:flex; align-items:center; justify-content:center; text-align:center; position:relative; }
.fr-card-label { position:absolute; top:16px; left:20px; font-size:11px; font-weight:700; color:var(--text-muted); text-transform:uppercase; letter-spacing:.6px; }
.fr-card-text { font-size:17px; font-weight:600; color:var(--text-primary); line-height:1.6; }
.fr-answer-text { font-size:15px; color:var(--text-secondary); line-height:1.7; }

.fr-progress-label { display:flex; justify-content:space-between; font-size:12px; color:var(--text-secondary); margin-bottom:8px; max-width:560px; margin-left:auto; margin-right:auto; }

.fr-btn-row { display:grid; grid-template-columns:repeat(2,1fr); gap:10px; max-width:560px; margin:16px auto 0; }
@media (min-width:600px) { .fr-btn-row.rating { grid-template-columns:repeat(4,1fr); } }
.fr-rate-btn { padding:14px 8px; border-radius:12px; border:none; font-size:13px; font-weight:700; cursor:pointer; transition:transform .15s, opacity .15s; color:#fff; }
.fr-rate-btn:hover { transform:translateY(-2px); }
.fr-rate-again { background:linear-gradient(135deg,#ef4444,#dc2626); }
.fr-rate-hard  { background:linear-gradient(135deg,#f59e0b,#d97706); }
.fr-rate-good  { background:linear-gradient(135deg,#6366f1,#4f46e5); }
.fr-rate-easy  { background:linear-gradient(135deg,#10b981,#059669); }
.fr-rate-sub { display:block; font-size:10px; font-weight:500; opacity:.85; margin-top:2px; }

.fr-summary { text-align:center; padding:40px 20px; }
.fr-summary-emoji { font-size:56px; margin-bottom:14px; }
</style>

<div class="cs-overlay" id="csOverlay">
  <div class="cs-modal">
    <div class="cs-emoji">✨</div>
    <div class="cs-title">Coming Soon</div>
    <p class="cs-desc">Flashcard Review is being polished behind the scenes. It'll be ready before you know it.</p>
    <button class="cs-btn" onclick="csGoBack()">← Go Back</button>
  </div>
</div>
<script>
function csGoBack() {
  if (document.referrer && document.referrer.indexOf(location.host) !== -1) {
    window.location.href = document.referrer;
  } else if (window.history.length > 1) {
    window.history.back();
  } else {
    window.location.href = '<?= SITE_URL ?>/dashboard';
  }
}
</script>

<div class="fr-page-header">
  <div>
    <div class="fr-page-title">🔁 Flashcard Review</div>
    <div class="fr-page-sub">Spaced repetition — review cards right when you're about to forget them</div>
  </div>
  <a href="<?= SITE_URL ?>/notes" class="btn btn-secondary">📝 Manage Flashcards</a>
</div>

<div class="fr-stat-row">
  <div class="fr-stat-card"><div class="fr-stat-num"><?= count($dueCards) ?></div><div class="fr-stat-label">Due Today</div></div>
  <div class="fr-stat-card"><div class="fr-stat-num"><?= $upcomingTomorrow ?></div><div class="fr-stat-label">Due Tomorrow</div></div>
  <div class="fr-stat-card"><div class="fr-stat-num"><?= $totalCards ?></div><div class="fr-stat-label">Total Cards</div></div>
</div>

<?php if (empty($dueCards)): ?>
  <div class="card">
    <div class="empty-state">
      <div class="empty-icon">🎉</div>
      <h3>All caught up!</h3>
      <p><?= $totalCards ? 'No flashcards due for review right now. Check back later.' : "You don't have any flashcards yet — create some in Notes & Flashcards first." ?></p>
      <a href="<?= SITE_URL ?>/notes" class="btn btn-primary" style="margin-top:14px;display:inline-flex">Go to Notes &amp; Flashcards</a>
    </div>
  </div>
<?php else: ?>

<div class="fr-progress-label"><span id="frProgressText">Card 1 of <?= count($dueCards) ?></span><span id="frDeckText"></span></div>
<div class="progress-bar" style="max-width:560px;margin:0 auto 20px"><div class="progress-fill" id="frProgressBar" style="width:0%"></div></div>

<div class="fr-card-wrap">
  <div class="fr-flip-card" id="frCard">
    <div class="fr-card-label" id="frCardLabel">QUESTION</div>
    <div class="fr-card-text" id="frCardText"></div>
  </div>
</div>

<div class="fr-btn-row" id="frShowBtnRow">
  <button class="btn btn-primary btn-full" style="grid-column:1/-1" onclick="frShowAnswer()">👁️ Show Answer</button>
</div>

<div class="fr-btn-row rating" id="frRatingRow" style="display:none">
  <button class="fr-rate-btn fr-rate-again" onclick="frRate(0)">Again<span class="fr-rate-sub">&lt;1 day</span></button>
  <button class="fr-rate-btn fr-rate-hard"  onclick="frRate(3)">Hard<span class="fr-rate-sub">1 day</span></button>
  <button class="fr-rate-btn fr-rate-good"  onclick="frRate(4)">Good<span class="fr-rate-sub">a few days</span></button>
  <button class="fr-rate-btn fr-rate-easy"  onclick="frRate(5)">Easy<span class="fr-rate-sub">longer</span></button>
</div>

<div id="frSummary" style="display:none"></div>

<script>
const frCards = <?= json_encode(array_map(fn($c) => [
    'id' => (int)$c['id'],
    'question' => $c['question'],
    'answer' => $c['answer'],
    'deck' => $c['deck_name'],
], $dueCards)) ?>;
let frIndex = 0;
let frShowingAnswer = false;
const frTally = { again:0, hard:0, good:0, easy:0 };

function frRenderCard() {
  if (frIndex >= frCards.length) { frShowSummary(); return; }
  const c = frCards[frIndex];
  frShowingAnswer = false;
  document.getElementById('frCardLabel').textContent = 'QUESTION';
  document.getElementById('frCardText').textContent = c.question;
  document.getElementById('frCardText').className = 'fr-card-text';
  document.getElementById('frDeckText').textContent = c.deck || '';
  document.getElementById('frProgressText').textContent = `Card ${frIndex+1} of ${frCards.length}`;
  document.getElementById('frProgressBar').style.width = (frIndex/frCards.length*100) + '%';
  document.getElementById('frShowBtnRow').style.display = 'grid';
  document.getElementById('frRatingRow').style.display = 'none';
}

function frShowAnswer() {
  const c = frCards[frIndex];
  frShowingAnswer = true;
  document.getElementById('frCardLabel').textContent = 'ANSWER';
  document.getElementById('frCardText').textContent = c.answer;
  document.getElementById('frCardText').className = 'fr-answer-text';
  document.getElementById('frShowBtnRow').style.display = 'none';
  document.getElementById('frRatingRow').style.display = 'grid';
}

async function frRate(quality) {
  const c = frCards[frIndex];
  const fd = new FormData();
  fd.append('action', 'submit_review');
  fd.append('id', c.id);
  fd.append('quality', quality);
  fetch(location.href, { method:'POST', body:fd, headers:{'X-Requested-With':'XMLHttpRequest'} }).catch(()=>{});

  if (quality === 0) frTally.again++;
  else if (quality === 3) frTally.hard++;
  else if (quality === 4) frTally.good++;
  else frTally.easy++;

  frIndex++;
  frRenderCard();
}

function frShowSummary() {
  document.getElementById('frCard').closest('.fr-card-wrap').style.display = 'none';
  document.getElementById('frShowBtnRow').style.display = 'none';
  document.getElementById('frRatingRow').style.display = 'none';
  document.querySelector('.fr-progress-label').style.display = 'none';
  document.querySelector('.progress-bar').style.display = 'none';
  const s = document.getElementById('frSummary');
  s.style.display = 'block';
  s.innerHTML = `
    <div class="card">
      <div class="fr-summary">
        <div class="fr-summary-emoji">🎉</div>
        <h3 style="font-size:20px;font-weight:800;color:var(--text-primary);margin-bottom:8px">Review Complete!</h3>
        <p style="color:var(--text-muted);margin-bottom:20px">You reviewed ${frCards.length} card${frCards.length===1?'':'s'} today.</p>
        <div style="display:flex;gap:10px;justify-content:center;flex-wrap:wrap;margin-bottom:22px">
          <span class="badge badge-red">Again: ${frTally.again}</span>
          <span class="badge badge-yellow">Hard: ${frTally.hard}</span>
          <span class="badge badge-purple">Good: ${frTally.good}</span>
          <span class="badge badge-green">Easy: ${frTally.easy}</span>
        </div>
        <a href="<?= SITE_URL ?>/notes" class="btn btn-secondary" style="margin-right:8px">📝 Manage Flashcards</a>
        <a href="<?= SITE_URL ?>/dashboard" class="btn btn-primary">🏠 Back to Dashboard</a>
      </div>
    </div>
  `;
}

frRenderCard();
</script>

<?php endif; ?>

<?php require_once 'includes/footer.php'; renderFooter(); ?>
