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

// Check & award achievements based on current stats
function checkAllAchievements($pdo, $uid) {
    // Get user stats
    $sessions = (int)$pdo->prepare("SELECT COUNT(*) FROM study_sessions WHERE user_id=?")->execute([$uid]) ? 0 : 0;
    $q = $pdo->prepare("SELECT COUNT(*) FROM study_sessions WHERE user_id=?"); $q->execute([$uid]); $sessions = (int)$q->fetchColumn();
    $q = $pdo->prepare("SELECT COALESCE(SUM(duration_minutes),0)/60 FROM study_sessions WHERE user_id=?"); $q->execute([$uid]); $hours = (float)$q->fetchColumn();
    $q = $pdo->prepare("SELECT COUNT(*) FROM study_streaks WHERE user_id=?"); $q->execute([$uid]); $streakDays = (int)$q->fetchColumn();
    $q = $pdo->prepare("SELECT COALESCE(AVG(marks_obtained/total_marks*100),0) FROM marks WHERE user_id=?"); $q->execute([$uid]); $avgMark = (float)$q->fetchColumn();
    $q = $pdo->prepare("SELECT COUNT(*) FROM goals WHERE user_id=?"); $q->execute([$uid]); $goalsCreated = (int)$q->fetchColumn();
    $q = $pdo->prepare("SELECT COUNT(*) FROM notes WHERE user_id=?"); $q->execute([$uid]); $notes = (int)$q->fetchColumn();
    $q = $pdo->prepare("SELECT COUNT(*) FROM flashcards WHERE user_id=?"); $q->execute([$uid]); $flashcards = (int)$q->fetchColumn();

    $checks = [
        'first_session'  => ['total_sessions', $sessions],
        'sessions_10'    => ['total_sessions', $sessions],
        'sessions_50'    => ['total_sessions', $sessions],
        'sessions_100'   => ['total_sessions', $sessions],
        'streak_3'       => ['streak_days',    $streakDays],
        'streak_7'       => ['streak_days',    $streakDays],
        'streak_30'      => ['streak_days',    $streakDays],
        'hours_10'       => ['total_hours',    $hours],
        'hours_100'      => ['total_hours',    $hours],
        'marks_75'       => ['marks_avg',      $avgMark],
        'marks_90'       => ['marks_avg',      $avgMark],
        'first_goal'     => ['goals_created',  $goalsCreated],
        'first_note'     => ['notes_created',  $notes],
        'flashcards_10'  => ['flashcards',     $flashcards],
    ];

    $defs = $pdo->query("SELECT * FROM achievement_defs")->fetchAll();
    foreach ($defs as $def) {
        if (!isset($checks[$def['key']])) continue;
        [, $val] = $checks[$def['key']];
        if ($val >= $def['condition_value']) {
            try {
                $ins = $pdo->prepare("INSERT IGNORE INTO user_achievements (user_id,achievement_id) VALUES (?,?)");
                $ins->execute([$uid, $def['id']]);
                if ($ins->rowCount() > 0) {
                    // XP
                    $pdo->prepare("UPDATE users SET xp_points=xp_points+? WHERE id=?")->execute([$def['xp_reward'],$uid]);                }
            } catch(Exception $e){}
        }
    }
}

checkAllAchievements($pdo, $uid);

// Load all achievements
$allAchs = $pdo->query("SELECT * FROM achievement_defs ORDER BY condition_value ASC")->fetchAll();
$earned  = $pdo->prepare("SELECT achievement_id, earned_at FROM user_achievements WHERE user_id=?");
$earned->execute([$uid]); $earned = $earned->fetchAll(PDO::FETCH_KEY_PAIR);

$q = $pdo->prepare("SELECT COALESCE(xp_points,0) FROM users WHERE id=?"); $q->execute([$uid]);
$xp = (int)$q->fetchColumn();

// XP level calculation
$level  = max(1, (int)floor($xp / 100) + 1);
$nextXP = $level * 100;
$xpPct  = min(100, round(($xp % 100)));

require_once 'includes/header.php';
renderHeader('Achievements', 'achievements');
?>

<div style="display:flex;align-items:center;justify-content:space-between;gap:12px;margin-bottom:22px">
  <div>
    <div style="font-size:22px;font-weight:800;font-family:'Sora',sans-serif">🏆 Achievements</div>
    <div style="font-size:13px;color:var(--text-muted);margin-top:3px"><?= count($earned) ?> / <?= count($allAchs) ?> unlocked</div>
  </div>
</div>

<!-- XP Card -->
<div class="card" style="margin-bottom:20px;background:linear-gradient(135deg,rgba(56,189,248,0.1),rgba(129,140,248,0.08));border-color:rgba(56,189,248,0.2)">
  <div style="display:flex;align-items:center;gap:20px;flex-wrap:wrap">
    <div style="width:64px;height:64px;border-radius:50%;background:var(--grad-primary,linear-gradient(135deg,#38bdf8,#818cf8));display:flex;align-items:center;justify-content:center;font-size:26px;font-weight:900;color:#fff;font-family:'Sora',sans-serif;flex-shrink:0;box-shadow:0 0 30px rgba(56,189,248,0.3)">
      <?= $level ?>
    </div>
    <div style="flex:1;min-width:160px">
      <div style="font-family:'Sora',sans-serif;font-size:18px;font-weight:700;color:var(--text-primary)">Level <?= $level ?></div>
      <div style="font-size:13px;color:var(--text-muted);margin-bottom:10px"><?= $xp ?> XP · <?= $nextXP - ($xp % 100 == 0 && $xp > 0 ? 0 : $xp % 100) ?> XP to next level</div>
      <div class="progress-bar" style="height:10px"><div class="progress-fill" style="width:<?= $xpPct ?>%;background:var(--grad-primary,linear-gradient(135deg,#38bdf8,#818cf8))"></div></div>
    </div>
    <div style="text-align:center;flex-shrink:0">
      <div style="font-size:32px;font-weight:800;font-family:'Sora',sans-serif;color:var(--teal,#38bdf8)"><?= $xp ?></div>
      <div style="font-size:12px;color:var(--text-muted)">Total XP</div>
    </div>
  </div>
</div>

<!-- Achievements Grid -->
<div class="stats-grid">
  <?php foreach ($allAchs as $a):
    $isEarned = isset($earned[$a['id']]);
    $earnedAt = $isEarned ? date('M j, Y', strtotime($earned[$a['id']])) : null;
  ?>
  <div class="card" style="<?= $isEarned ? 'border-color:rgba(56,189,248,0.3);background:linear-gradient(135deg,rgba(56,189,248,0.06),rgba(129,140,248,0.04))' : 'opacity:0.55;filter:grayscale(0.3)' ?>">
    <div style="font-size:36px;margin-bottom:10px"><?= $a['icon'] ?></div>
    <div style="font-size:15px;font-weight:700;color:var(--text-primary);margin-bottom:5px"><?= htmlspecialchars($a['title']) ?></div>
    <div style="font-size:13px;color:var(--text-secondary);margin-bottom:10px;line-height:1.4"><?= htmlspecialchars($a['description']) ?></div>
    <div style="display:flex;justify-content:space-between;align-items:center">
      <?php if ($isEarned): ?>
        <span class="badge badge-cyan">✓ Earned</span>
        <span style="font-size:11px;color:var(--text-muted)"><?= $earnedAt ?></span>
      <?php else: ?>
        <span class="badge badge-yellow">🔒 Locked</span>
        <span style="font-size:12px;color:var(--teal,#38bdf8);font-weight:700">+<?= $a['xp_reward'] ?> XP</span>
      <?php endif; ?>
    </div>
  </div>
  <?php endforeach; ?>
</div>

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