<?php
/**
 * StudyTrack Admin — Student View
 * File: admin/student-view.php
 * Usage: admin/student-view.php?id=USER_ID
 *
 * Add to admin/includes/header.php nav:
 *   <a href="<?= $siteUrl ?>/admin/users.php" class="nav-item ...">👥 Users</a>
 *
 * Add "View Student" button in users.php table row:
 *   <a href="student-view.php?id=<?= $u['id'] ?>" class="btn btn-sm btn-secondary">👁 View</a>
 *
 * Add "View Student" button in user-detail.php quick-actions:
 *   <a href="student-view.php?id=<?= $userId ?>" class="btn btn-sm btn-secondary" target="_blank">👁 Student View</a>
 */

require_once '../includes/config.php';
requireAdmin();

$userId = (int)($_GET['id'] ?? 0);
if ($userId <= 0) { header('Location: users.php'); exit; }

// ── Fetch user ────────────────────────────────────────────────────────────────
$stmt = $pdo->prepare("SELECT * FROM users WHERE id=?");
$stmt->execute([$userId]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$user) { header('Location: users.php'); exit; }

// ── Stats ─────────────────────────────────────────────────────────────────────
$q = $pdo->prepare("SELECT COALESCE(SUM(duration_minutes),0) FROM study_sessions WHERE user_id=?");
$q->execute([$userId]); $totalMins = (int)$q->fetchColumn();

$q = $pdo->prepare("SELECT COUNT(*) FROM study_sessions WHERE user_id=?");
$q->execute([$userId]); $sessionCount = (int)$q->fetchColumn();

$q = $pdo->prepare("SELECT COUNT(*) FROM tasks WHERE user_id=?");
$q->execute([$userId]); $taskTotal = (int)$q->fetchColumn();

$q = $pdo->prepare("SELECT COUNT(*) FROM tasks WHERE user_id=? AND status='completed'");
$q->execute([$userId]); $taskDone = (int)$q->fetchColumn();

$avgMark = 0;
try {
    $q = $pdo->prepare("SELECT AVG(marks_obtained/total_marks*100) FROM marks WHERE user_id=?");
    $q->execute([$userId]); $avgMark = round((float)$q->fetchColumn(), 1);
} catch (Exception $e) {}

$achieveCount = 0;
try {
    $q = $pdo->prepare("SELECT COUNT(*) FROM user_achievements WHERE user_id=?");
    $q->execute([$userId]); $achieveCount = (int)$q->fetchColumn();
} catch (Exception $e) {}

$xpPoints = (int)($user['xp_points'] ?? 0);

// Study streak
$streak = 0;
try {
    $days = $pdo->prepare("SELECT DISTINCT date FROM study_sessions WHERE user_id=? ORDER BY date DESC LIMIT 60");
    $days->execute([$userId]);
    $dates = array_column($days->fetchAll(PDO::FETCH_ASSOC), 'date');
    if ($dates) {
        $streak = 1; $prev = $dates[0];
        for ($i = 1; $i < count($dates); $i++) {
            $diff = (strtotime($prev) - strtotime($dates[$i])) / 86400;
            if ($diff == 1) { $streak++; $prev = $dates[$i]; } else break;
        }
    }
} catch (Exception $e) {}

// ── Detail data ───────────────────────────────────────────────────────────────
// Subjects with study time
$q = $pdo->prepare("
    SELECT s.*, COALESCE(SUM(ss.duration_minutes),0) as mins, COUNT(ss.id) as session_cnt
    FROM subjects s
    LEFT JOIN study_sessions ss ON ss.subject_id=s.id AND ss.user_id=?
    WHERE s.user_id=?
    GROUP BY s.id ORDER BY mins DESC
");
$q->execute([$userId, $userId]); $subjects = $q->fetchAll(PDO::FETCH_ASSOC);

// Recent sessions (last 20)
$q = $pdo->prepare("
    SELECT ss.*, sub.name as subject_name, sub.color
    FROM study_sessions ss
    LEFT JOIN subjects sub ON ss.subject_id=sub.id
    WHERE ss.user_id=? ORDER BY ss.date DESC, ss.created_at DESC LIMIT 20
");
$q->execute([$userId]); $sessions = $q->fetchAll(PDO::FETCH_ASSOC);

// Tasks
$q = $pdo->prepare("
    SELECT t.*, sub.name as subject_name, sub.color as subject_color
    FROM tasks t
    LEFT JOIN subjects sub ON t.subject_id=sub.id
    WHERE t.user_id=? ORDER BY
        CASE t.status WHEN 'pending' THEN 0 WHEN 'in_progress' THEN 1 ELSE 2 END,
        CASE t.priority WHEN 'high' THEN 0 WHEN 'medium' THEN 1 ELSE 2 END,
        t.due_date ASC LIMIT 20
");
$q->execute([$userId]); $tasks = $q->fetchAll(PDO::FETCH_ASSOC);

// Marks
$q = $pdo->prepare("
    SELECT m.*, sub.name as subject_name, sub.color
    FROM marks m
    LEFT JOIN subjects sub ON m.subject_id=sub.id
    WHERE m.user_id=? ORDER BY m.exam_date DESC LIMIT 20
");
$q->execute([$userId]); $marks = $q->fetchAll(PDO::FETCH_ASSOC);

// Achievements
$achievements = [];
try {
    $q = $pdo->prepare("
        SELECT ua.earned_at, ad.title, ad.icon, ad.description, ad.xp_reward
        FROM user_achievements ua
        JOIN achievement_defs ad ON ua.achievement_id=ad.id
        WHERE ua.user_id=? ORDER BY ua.earned_at DESC
    ");
    $q->execute([$userId]); $achievements = $q->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {}

// Goals
$goals = [];
try {
    $q = $pdo->prepare("
        SELECT g.*, sub.name as subject_name
        FROM goals g LEFT JOIN subjects sub ON g.subject_id=sub.id
        WHERE g.user_id=? ORDER BY g.status ASC, g.deadline ASC LIMIT 10
    ");
    $q->execute([$userId]); $goals = $q->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {}

// Activity — last 30 days
$activityDays = [];
for ($i = 29; $i >= 0; $i--) {
    $d = date('Y-m-d', strtotime("-$i days"));
    $q = $pdo->prepare("SELECT COALESCE(SUM(duration_minutes),0) FROM study_sessions WHERE user_id=? AND date=?");
    $q->execute([$userId, $d]);
    $activityDays[] = ['date' => date('M j', strtotime($d)), 'mins' => (int)$q->fetchColumn()];
}

// Subject chart data (JSON)
$subjectLabels = json_encode(array_column($subjects, 'name'));
$subjectMins   = json_encode(array_map(fn($s) => (int)$s['mins'], $subjects));
$subjectColors = json_encode(array_map(fn($s) => $s['color'] ?? '#6366f1', $subjects));

// Activity chart data (JSON)
$actLabels = json_encode(array_column($activityDays, 'date'));
$actMins   = json_encode(array_column($activityDays, 'mins'));

// Marks chart data
$markLabels = json_encode(array_reverse(array_map(fn($m) => $m['subject_name'].' ('.date('M j',strtotime($m['exam_date'])).')', $marks)));
$markPcts   = json_encode(array_reverse(array_map(fn($m) => $m['total_marks'] > 0 ? round($m['marks_obtained']/$m['total_marks']*100,1) : 0, $marks)));

// Avatar
$siteUrl   = defined('SITE_URL') ? SITE_URL : '';
$avatarSrc = !empty($user['avatar']) ? '../' . $user['avatar'] : (!empty($user['google_avatar']) ? $user['google_avatar'] : null);
$initials  = strtoupper(substr($user['name'], 0, 1)) . (strpos($user['name'],' ')!==false ? strtoupper(substr(strrchr($user['name'],' '),1,1)) : '');
$taskPct   = $taskTotal > 0 ? round($taskDone / $taskTotal * 100) : 0;
$totalHours = floor($totalMins / 60);

require_once 'includes/header.php';
renderAdminHeader('Student View — ' . $user['name'], 'users');
?>

<style>
/* ── Admin notice banner ───────────────────────────────────────── */
.admin-notice {
    background: rgba(99,102,241,0.08);
    border: 1px solid rgba(99,102,241,0.25);
    border-radius: 10px;
    padding: 10px 16px;
    margin-bottom: 20px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 12px;
    flex-wrap: wrap;
}
.admin-notice-text { font-size: 13px; color: var(--text-secondary); }
.admin-notice-text strong { color: var(--text-primary); }

/* ── Student profile card ──────────────────────────────────────── */
.sv-hero {
    background: var(--surface);
    border: 1px solid var(--border);
    border-radius: 16px;
    padding: 24px;
    margin-bottom: 20px;
    display: flex;
    align-items: center;
    gap: 20px;
    flex-wrap: wrap;
}
.sv-avatar {
    width: 80px; height: 80px;
    border-radius: 50%;
    background: linear-gradient(135deg, #6366f1, #a855f7);
    display: flex; align-items: center; justify-content: center;
    font-size: 28px; font-weight: 700; color: #fff;
    flex-shrink: 0;
    overflow: hidden;
}
.sv-avatar img { width: 80px; height: 80px; object-fit: cover; }
.sv-name { font-size: 22px; font-weight: 700; color: var(--text-primary); margin: 0 0 3px; }
.sv-email { font-size: 13px; color: var(--text-muted); margin: 0 0 10px; }
.sv-meta { display: flex; gap: 8px; flex-wrap: wrap; align-items: center; }
.sv-meta span { font-size: 12px; color: var(--text-muted); }

/* XP bar */
.xp-bar-wrap { display: flex; align-items: center; gap: 10px; margin-top: 10px; }
.xp-label { font-size: 12px; color: var(--text-muted); white-space: nowrap; }
.xp-track { flex: 1; height: 6px; background: rgba(99,102,241,0.12); border-radius: 3px; overflow: hidden; max-width: 160px; }
.xp-fill { height: 100%; background: linear-gradient(90deg,#6366f1,#a855f7); border-radius: 3px; }

/* ── Stats grid ────────────────────────────────────────────────── */
.sv-stats { display: grid; grid-template-columns: repeat(auto-fit, minmax(130px,1fr)); gap: 12px; margin-bottom: 20px; }
.sv-stat {
    background: var(--surface); border: 1px solid var(--border);
    border-radius: 12px; padding: 16px 14px; text-align: center;
}
.sv-stat-val { font-size: 24px; font-weight: 700; color: var(--text-primary); }
.sv-stat-label { font-size: 12px; color: var(--text-muted); margin-top: 3px; }
.sv-stat-icon { font-size: 20px; margin-bottom: 6px; }

/* ── Tabs ──────────────────────────────────────────────────────── */
.sv-tabs { background: var(--surface); border: 1px solid var(--border); border-radius: 16px; overflow: hidden; margin-bottom: 20px; }
.sv-tab-bar { display: flex; border-bottom: 1px solid var(--border); overflow-x: auto; }
.sv-tab-btn {
    padding: 12px 18px; font-size: 13px; font-weight: 500;
    color: var(--text-muted); border: none; background: transparent;
    cursor: pointer; border-bottom: 2px solid transparent;
    transition: all .15s; white-space: nowrap; flex-shrink: 0;
}
.sv-tab-btn.active { color: #818cf8; border-bottom-color: #6366f1; }
.sv-tab-body { padding: 20px; }
.sv-tab-pane { display: none; }
.sv-tab-pane.active { display: block; }

/* ── Charts container ──────────────────────────────────────────── */
.sv-chart-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 20px; }
@media(max-width:720px) { .sv-chart-grid { grid-template-columns: 1fr; } }
.sv-chart-box { }
.sv-chart-title { font-size: 13px; font-weight: 600; color: var(--text-primary); margin-bottom: 12px; }
.sv-chart-wrap { position: relative; height: 200px; }

/* ── Subject list ──────────────────────────────────────────────── */
.sv-subject-row { display: flex; align-items: center; gap: 10px; margin-bottom: 10px; }
.sv-subject-dot { width: 12px; height: 12px; border-radius: 50%; flex-shrink: 0; }
.sv-subject-name { font-size: 13px; color: var(--text-primary); flex: 1; }
.sv-subject-bar-track { flex: 2; height: 7px; background: rgba(99,102,241,0.1); border-radius: 4px; overflow: hidden; }
.sv-subject-bar-fill { height: 100%; border-radius: 4px; }
.sv-subject-time { font-size: 12px; color: var(--text-muted); min-width: 45px; text-align: right; }

/* ── Tables ────────────────────────────────────────────────────── */
.sv-table { width: 100%; border-collapse: collapse; font-size: 13px; }
.sv-table th { text-align: left; padding: 8px 10px; font-size: 11px; font-weight: 600; color: var(--text-muted); text-transform: uppercase; letter-spacing: .04em; border-bottom: 1px solid var(--border); }
.sv-table td { padding: 10px; border-bottom: 1px solid rgba(var(--border),0.5); vertical-align: middle; }
.sv-table tr:last-child td { border-bottom: none; }
.sv-table tr:hover td { background: rgba(99,102,241,0.03); }

/* ── Badges ────────────────────────────────────────────────────── */
.sv-badge { display: inline-flex; align-items: center; gap: 4px; padding: 3px 9px; border-radius: 20px; font-size: 11px; font-weight: 600; }
.sv-badge-green  { background: rgba(16,185,129,0.12); color: #10b981; }
.sv-badge-red    { background: rgba(239,68,68,0.12);  color: #ef4444; }
.sv-badge-yellow { background: rgba(245,158,11,0.12); color: #f59e0b; }
.sv-badge-cyan   { background: rgba(6,182,212,0.12);  color: #22d3ee; }
.sv-badge-purple { background: rgba(139,92,246,0.12); color: #a78bfa; }

/* ── Achievement cards ─────────────────────────────────────────── */
.sv-achieve-grid { display: grid; grid-template-columns: repeat(auto-fill,minmax(200px,1fr)); gap: 12px; }
.sv-achieve-card {
    background: var(--bg-secondary,rgba(99,102,241,0.05));
    border: 1px solid var(--border);
    border-radius: 12px; padding: 14px 16px;
    display: flex; align-items: flex-start; gap: 12px;
}
.sv-achieve-icon { font-size: 26px; }
.sv-achieve-title { font-size: 13px; font-weight: 600; color: var(--text-primary); margin: 0 0 2px; }
.sv-achieve-desc { font-size: 12px; color: var(--text-muted); margin: 0; }
.sv-achieve-xp { font-size: 11px; color: #818cf8; margin-top: 4px; font-weight: 600; }

/* ── Goal row ──────────────────────────────────────────────────── */
.sv-goal-row { padding: 12px 0; border-bottom: 1px solid var(--border); }
.sv-goal-row:last-child { border-bottom: none; }
.sv-goal-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 6px; }
.sv-goal-title { font-size: 13px; font-weight: 500; color: var(--text-primary); }
.sv-goal-progress { font-size: 12px; color: var(--text-muted); }
.sv-goal-bar-track { height: 6px; background: rgba(99,102,241,0.1); border-radius: 3px; overflow: hidden; }
.sv-goal-bar-fill { height: 100%; border-radius: 3px; background: linear-gradient(90deg,#6366f1,#a855f7); transition: width .6s; }

/* ── Empty ─────────────────────────────────────────────────────── */
.sv-empty { text-align: center; padding: 40px 20px; color: var(--text-muted); font-size: 14px; }
.sv-empty-icon { font-size: 36px; margin-bottom: 10px; }
</style>

<!-- Back / breadcrumb -->
<div style="display:flex; align-items:center; justify-content:space-between; margin-bottom:16px; flex-wrap:wrap; gap:8px;">
    <div style="display:flex;align-items:center;gap:8px">
        <a href="users.php" class="btn btn-secondary btn-sm">← Users</a>
        <a href="user-detail.php?id=<?= $userId ?>" class="btn btn-secondary btn-sm">⚙️ Admin Detail</a>
    </div>
    <a href="student-view.php?id=<?= $userId ?>" class="btn btn-secondary btn-sm" target="_blank">↗ New tab</a>
</div>

<!-- Admin notice -->
<div class="admin-notice">
    <div class="admin-notice-text">
        👁 <strong>Admin Preview Mode</strong> — ඔබ දකිනවා
        <strong><?= htmlspecialchars($user['name']) ?></strong> ගේ student dashboard එක.
        මෙය read-only view — student data වෙනස් නොවේ.
    </div>
    <div style="display:flex;gap:6px;flex-wrap:wrap">
        <?php if (!empty($user['is_disabled'])): ?>
            <span class="sv-badge sv-badge-red">🚫 Disabled</span>
        <?php endif; ?>
        <?php if (!($user['is_verified'] ?? 0)): ?>
            <span class="sv-badge sv-badge-yellow">⚠️ Unverified</span>
        <?php endif; ?>
        <span class="sv-badge sv-badge-purple">ID #<?= $userId ?></span>
    </div>
</div>

<!-- Student profile hero -->
<div class="sv-hero">
    <div class="sv-avatar">
        <?php if ($avatarSrc): ?>
            <img src="<?= htmlspecialchars($avatarSrc) ?>" alt="<?= htmlspecialchars($user['name']) ?>">
        <?php else: ?>
            <?= htmlspecialchars($initials) ?>
        <?php endif; ?>
    </div>
    <div style="flex:1;min-width:0">
        <div class="sv-name"><?= htmlspecialchars($user['name']) ?></div>
        <div class="sv-email"><?= htmlspecialchars($user['email']) ?></div>
        <div class="sv-meta">
            <span>📅 Joined <?= date('F j, Y', strtotime($user['created_at'])) ?></span>
            <?php if (!empty($user['last_login'])): ?>
            <span>• 🕐 Last seen <?= date('M j, Y', strtotime($user['last_login'])) ?></span>
            <?php endif; ?>
            <?php if ($xpPoints > 0): ?>
            <span>• ✨ <?= number_format($xpPoints) ?> XP</span>
            <?php endif; ?>
        </div>
        <?php if ($xpPoints > 0): ?>
        <div class="xp-bar-wrap">
            <span class="xp-label">XP</span>
            <div class="xp-track">
                <div class="xp-fill" style="width:<?= min(100, round($xpPoints/1000*100)) ?>%"></div>
            </div>
            <span class="xp-label"><?= number_format($xpPoints) ?> / 1000</span>
        </div>
        <?php endif; ?>
    </div>
    <div style="text-align:right">
        <div style="font-size:13px;color:var(--text-muted)">Daily Study Goal</div>
        <div style="font-size:18px;font-weight:700;color:var(--text-primary)">
            <?= floor(($user['study_goal_minutes'] ?? 120) / 60) ?>h
            <?= ($user['study_goal_minutes'] ?? 120) % 60 > 0 ? (($user['study_goal_minutes'] ?? 120) % 60).'m' : '' ?>
        </div>
    </div>
</div>

<!-- Stats row -->
<div class="sv-stats">
    <div class="sv-stat">
        <div class="sv-stat-icon">⏱️</div>
        <div class="sv-stat-val"><?= $totalHours ?>h</div>
        <div class="sv-stat-label">Total Study Time</div>
    </div>
    <div class="sv-stat">
        <div class="sv-stat-icon">📚</div>
        <div class="sv-stat-val"><?= $sessionCount ?></div>
        <div class="sv-stat-label">Study Sessions</div>
    </div>
    <div class="sv-stat">
        <div class="sv-stat-icon">🔥</div>
        <div class="sv-stat-val"><?= $streak ?></div>
        <div class="sv-stat-label">Day Streak</div>
    </div>
    <div class="sv-stat">
        <div class="sv-stat-icon">📊</div>
        <div class="sv-stat-val"><?= $avgMark ?>%</div>
        <div class="sv-stat-label">Average Mark</div>
    </div>
    <div class="sv-stat">
        <div class="sv-stat-icon">✅</div>
        <div class="sv-stat-val"><?= $taskDone ?>/<?= $taskTotal ?></div>
        <div class="sv-stat-label">Tasks Done</div>
    </div>
    <div class="sv-stat">
        <div class="sv-stat-icon">🏆</div>
        <div class="sv-stat-val"><?= $achieveCount ?></div>
        <div class="sv-stat-label">Achievements</div>
    </div>
</div>

<!-- Tabs -->
<div class="sv-tabs">
    <div class="sv-tab-bar">
        <button class="sv-tab-btn active" onclick="svTab('overview',this)">📊 Overview</button>
        <button class="sv-tab-btn" onclick="svTab('sessions',this)">⏱️ Sessions</button>
        <button class="sv-tab-btn" onclick="svTab('marks',this)">📝 Marks</button>
        <button class="sv-tab-btn" onclick="svTab('tasks',this)">✅ Tasks</button>
        <button class="sv-tab-btn" onclick="svTab('goals',this)">🎯 Goals</button>
        <button class="sv-tab-btn" onclick="svTab('subjects',this)">📚 Subjects</button>
        <button class="sv-tab-btn" onclick="svTab('achievements',this)">🏆 Achievements</button>
    </div>

    <div class="sv-tab-body">

        <!-- ── OVERVIEW ── -->
        <div class="sv-tab-pane active" id="svtab-overview">
            <div class="sv-chart-grid">
                <!-- Activity chart -->
                <div class="sv-chart-box">
                    <div class="sv-chart-title">📅 Study Activity — Last 30 Days</div>
                    <div class="sv-chart-wrap"><canvas id="actChart"></canvas></div>
                </div>
                <!-- Subject doughnut -->
                <div class="sv-chart-box">
                    <div class="sv-chart-title">📚 Time by Subject</div>
                    <div class="sv-chart-wrap"><canvas id="subChart"></canvas></div>
                </div>
            </div>

            <!-- Task progress -->
            <div style="margin-top:24px">
                <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:8px">
                    <span style="font-size:13px;font-weight:600;color:var(--text-primary)">Task Completion</span>
                    <span style="font-size:13px;color:var(--text-muted)"><?= $taskDone ?> / <?= $taskTotal ?> (<?= $taskPct ?>%)</span>
                </div>
                <div style="height:10px;background:rgba(99,102,241,0.1);border-radius:5px;overflow:hidden">
                    <div style="height:100%;width:<?= $taskPct ?>%;background:linear-gradient(90deg,#10b981,#6366f1);border-radius:5px;transition:width .6s"></div>
                </div>
            </div>

            <!-- Quick subject list -->
            <?php if ($subjects): ?>
            <div style="margin-top:24px">
                <div class="sv-chart-title">⏱️ Subject Study Time</div>
                <?php $maxMins = max(array_column($subjects,'mins') ?: [1]); ?>
                <?php foreach ($subjects as $s): $pct = $maxMins > 0 ? ($s['mins']/$maxMins*100) : 0; ?>
                <div class="sv-subject-row">
                    <div class="sv-subject-dot" style="background:<?= htmlspecialchars($s['color'] ?? '#6366f1') ?>"></div>
                    <span class="sv-subject-name"><?= htmlspecialchars($s['name']) ?></span>
                    <div class="sv-subject-bar-track">
                        <div class="sv-subject-bar-fill" style="width:<?= round($pct) ?>%;background:<?= htmlspecialchars($s['color'] ?? '#6366f1') ?>"></div>
                    </div>
                    <span class="sv-subject-time"><?= floor($s['mins']/60) ?>h <?= $s['mins']%60 ?>m</span>
                </div>
                <?php endforeach; ?>
            </div>
            <?php endif; ?>
        </div>

        <!-- ── SESSIONS ── -->
        <div class="sv-tab-pane" id="svtab-sessions">
            <?php if ($sessions): ?>
            <table class="sv-table">
                <thead>
                    <tr>
                        <th>Date</th>
                        <th>Subject</th>
                        <th>Duration</th>
                        <th>Notes</th>
                    </tr>
                </thead>
                <tbody>
                <?php foreach ($sessions as $s): ?>
                <tr>
                    <td><?= date('M j, Y', strtotime($s['date'])) ?></td>
                    <td>
                        <div style="display:flex;align-items:center;gap:7px">
                            <div style="width:10px;height:10px;border-radius:50%;background:<?= htmlspecialchars($s['color'] ?? '#6366f1') ?>;flex-shrink:0"></div>
                            <?= htmlspecialchars($s['subject_name'] ?? '—') ?>
                        </div>
                    </td>
                    <td><span class="sv-badge sv-badge-cyan"><?= floor($s['duration_minutes']/60) ?>h <?= $s['duration_minutes']%60 ?>m</span></td>
                    <td style="color:var(--text-muted);max-width:220px">
                        <?= htmlspecialchars(mb_substr($s['notes'] ?? '', 0, 70)) ?><?= mb_strlen($s['notes'] ?? '') > 70 ? '…' : '' ?>
                    </td>
                </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
            <?php else: ?>
            <div class="sv-empty"><div class="sv-empty-icon">⏱️</div>Study sessions නැත.</div>
            <?php endif; ?>
        </div>

        <!-- ── MARKS ── -->
        <div class="sv-tab-pane" id="svtab-marks">
            <?php if ($marks): ?>
            <div style="margin-bottom:20px">
                <div class="sv-chart-title">📈 Exam Scores</div>
                <div class="sv-chart-wrap" style="height:180px"><canvas id="marksChart"></canvas></div>
            </div>
            <table class="sv-table">
                <thead>
                    <tr>
                        <th>Date</th>
                        <th>Exam</th>
                        <th>Subject</th>
                        <th>Score</th>
                        <th>%</th>
                    </tr>
                </thead>
                <tbody>
                <?php foreach ($marks as $m):
                    $pct = $m['total_marks'] > 0 ? round($m['marks_obtained']/$m['total_marks']*100,1) : 0;
                    $badgeClass = $pct >= 75 ? 'sv-badge-green' : ($pct >= 50 ? 'sv-badge-yellow' : 'sv-badge-red');
                ?>
                <tr>
                    <td><?= date('M j, Y', strtotime($m['exam_date'])) ?></td>
                    <td style="font-weight:500"><?= htmlspecialchars($m['exam_name']) ?></td>
                    <td>
                        <div style="display:flex;align-items:center;gap:7px">
                            <div style="width:10px;height:10px;border-radius:50%;background:<?= htmlspecialchars($m['color'] ?? '#6366f1') ?>;flex-shrink:0"></div>
                            <?= htmlspecialchars($m['subject_name'] ?? '—') ?>
                        </div>
                    </td>
                    <td><?= $m['marks_obtained'] ?> / <?= $m['total_marks'] ?></td>
                    <td><span class="sv-badge <?= $badgeClass ?>"><?= $pct ?>%</span></td>
                </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
            <?php else: ?>
            <div class="sv-empty"><div class="sv-empty-icon">📝</div>Exam marks නැත.</div>
            <?php endif; ?>
        </div>

        <!-- ── TASKS ── -->
        <div class="sv-tab-pane" id="svtab-tasks">
            <?php if ($tasks): ?>
            <table class="sv-table">
                <thead>
                    <tr>
                        <th>Task</th>
                        <th>Subject</th>
                        <th>Priority</th>
                        <th>Status</th>
                        <th>Due</th>
                    </tr>
                </thead>
                <tbody>
                <?php foreach ($tasks as $t):
                    $priClass = ['high'=>'sv-badge-red','medium'=>'sv-badge-yellow','low'=>'sv-badge-green'][$t['priority']] ?? 'sv-badge-yellow';
                    $stClass  = ['completed'=>'sv-badge-green','in_progress'=>'sv-badge-cyan','pending'=>'sv-badge-yellow'][$t['status']] ?? 'sv-badge-yellow';
                    $overdue  = $t['due_date'] && $t['status'] !== 'completed' && strtotime($t['due_date']) < time();
                ?>
                <tr>
                    <td>
                        <div style="font-weight:500;color:var(--text-primary)"><?= htmlspecialchars($t['title']) ?></div>
                        <?php if (!empty($t['description'])): ?>
                        <div style="font-size:12px;color:var(--text-muted)"><?= htmlspecialchars(mb_substr($t['description'],0,60)) ?></div>
                        <?php endif; ?>
                    </td>
                    <td>
                        <?php if ($t['subject_name']): ?>
                        <div style="display:flex;align-items:center;gap:6px">
                            <div style="width:8px;height:8px;border-radius:50%;background:<?= htmlspecialchars($t['subject_color'] ?? '#6366f1') ?>"></div>
                            <?= htmlspecialchars($t['subject_name']) ?>
                        </div>
                        <?php else: ?>—<?php endif; ?>
                    </td>
                    <td><span class="sv-badge <?= $priClass ?>"><?= ucfirst($t['priority']) ?></span></td>
                    <td><span class="sv-badge <?= $stClass ?>"><?= str_replace('_',' ',ucfirst($t['status'])) ?></span></td>
                    <td>
                        <?php if ($t['due_date']): ?>
                        <span style="color:<?= $overdue ? '#ef4444' : 'var(--text-secondary)' ?>;font-size:13px">
                            <?= $overdue ? '⚠️ ' : '' ?><?= date('M j', strtotime($t['due_date'])) ?>
                        </span>
                        <?php else: ?>—<?php endif; ?>
                    </td>
                </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
            <?php else: ?>
            <div class="sv-empty"><div class="sv-empty-icon">✅</div>Tasks නැත.</div>
            <?php endif; ?>
        </div>

        <!-- ── GOALS ── -->
        <div class="sv-tab-pane" id="svtab-goals">
            <?php if ($goals): ?>
            <?php foreach ($goals as $g):
                $gpct = $g['target_value'] > 0 ? min(100, round($g['current_value']/$g['target_value']*100)) : 0;
                $gStatusClass = ['active'=>'sv-badge-cyan','completed'=>'sv-badge-green','failed'=>'sv-badge-red'][$g['status']] ?? 'sv-badge-cyan';
            ?>
            <div class="sv-goal-row">
                <div class="sv-goal-header">
                    <div>
                        <div class="sv-goal-title"><?= htmlspecialchars($g['title']) ?></div>
                        <?php if ($g['subject_name']): ?>
                        <div style="font-size:12px;color:var(--text-muted);margin-top:2px"><?= htmlspecialchars($g['subject_name']) ?></div>
                        <?php endif; ?>
                    </div>
                    <div style="display:flex;flex-direction:column;align-items:flex-end;gap:4px">
                        <span class="sv-badge <?= $gStatusClass ?>"><?= ucfirst($g['status']) ?></span>
                        <?php if ($g['deadline']): ?>
                        <span style="font-size:11px;color:var(--text-muted)">Due <?= date('M j, Y',strtotime($g['deadline'])) ?></span>
                        <?php endif; ?>
                    </div>
                </div>
                <div style="display:flex;align-items:center;gap:10px;margin-top:6px">
                    <div class="sv-goal-bar-track" style="flex:1">
                        <div class="sv-goal-bar-fill" style="width:<?= $gpct ?>%"></div>
                    </div>
                    <span class="sv-goal-progress"><?= $g['current_value'] ?> / <?= $g['target_value'] ?> <?= htmlspecialchars($g['unit']) ?> (<?= $gpct ?>%)</span>
                </div>
            </div>
            <?php endforeach; ?>
            <?php else: ?>
            <div class="sv-empty"><div class="sv-empty-icon">🎯</div>Goals set කර නැත.</div>
            <?php endif; ?>
        </div>

        <!-- ── SUBJECTS ── -->
        <div class="sv-tab-pane" id="svtab-subjects">
            <?php if ($subjects): ?>
            <table class="sv-table">
                <thead>
                    <tr>
                        <th>Subject</th>
                        <th>Sessions</th>
                        <th>Study Time</th>
                        <th>Target Marks</th>
                    </tr>
                </thead>
                <tbody>
                <?php foreach ($subjects as $s): ?>
                <tr>
                    <td>
                        <div style="display:flex;align-items:center;gap:10px">
                            <div style="width:14px;height:14px;border-radius:4px;background:<?= htmlspecialchars($s['color'] ?? '#6366f1') ?>;flex-shrink:0"></div>
                            <span style="font-weight:500"><?= htmlspecialchars($s['name']) ?></span>
                        </div>
                    </td>
                    <td><?= $s['session_cnt'] ?></td>
                    <td><span class="sv-badge sv-badge-purple"><?= floor($s['mins']/60) ?>h <?= $s['mins']%60 ?>m</span></td>
                    <td><?= $s['target_marks'] ?? 100 ?>%</td>
                </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
            <?php else: ?>
            <div class="sv-empty"><div class="sv-empty-icon">📚</div>Subjects add කර නැත.</div>
            <?php endif; ?>
        </div>

        <!-- ── ACHIEVEMENTS ── -->
        <div class="sv-tab-pane" id="svtab-achievements">
            <?php if ($achievements): ?>
            <div class="sv-achieve-grid">
                <?php foreach ($achievements as $a): ?>
                <div class="sv-achieve-card">
                    <div class="sv-achieve-icon"><?= $a['icon'] ?></div>
                    <div>
                        <div class="sv-achieve-title"><?= htmlspecialchars($a['title']) ?></div>
                        <div class="sv-achieve-desc"><?= htmlspecialchars($a['description']) ?></div>
                        <div class="sv-achieve-xp">+<?= $a['xp_reward'] ?> XP • <?= date('M j', strtotime($a['earned_at'])) ?></div>
                    </div>
                </div>
                <?php endforeach; ?>
            </div>
            <?php else: ?>
            <div class="sv-empty"><div class="sv-empty-icon">🏆</div>Achievements තවම earn නොකළ.</div>
            <?php endif; ?>
        </div>

    </div><!-- sv-tab-body -->
</div><!-- sv-tabs -->

<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.0/dist/chart.umd.min.js"></script>
<script>
// ── Tab switching ────────────────────────────────────────────────
function svTab(id, btn) {
    document.querySelectorAll('.sv-tab-pane').forEach(p => p.classList.remove('active'));
    document.querySelectorAll('.sv-tab-btn').forEach(b => b.classList.remove('active'));
    document.getElementById('svtab-' + id).classList.add('active');
    btn.classList.add('active');
    // Lazy-init charts when their tab opens
    if (id === 'overview') { initOverviewCharts(); }
    if (id === 'marks')    { initMarksChart(); }
}

// ── Chart helpers ────────────────────────────────────────────────
let actChartInst = null, subChartInst = null, marksChartInst = null;

// Detect dark mode
function isDark() {
    return document.documentElement.getAttribute('data-theme') === 'dark'
        || window.matchMedia('(prefers-color-scheme: dark)').matches;
}
function textColor() { return isDark() ? 'rgba(255,255,255,0.55)' : 'rgba(0,0,0,0.45)'; }
function gridColor() { return isDark() ? 'rgba(255,255,255,0.06)' : 'rgba(0,0,0,0.06)'; }

function initOverviewCharts() {
    // Activity line chart
    if (!actChartInst && document.getElementById('actChart')) {
        actChartInst = new Chart(document.getElementById('actChart'), {
            type: 'bar',
            data: {
                labels: <?= $actLabels ?>,
                datasets: [{
                    label: 'Minutes',
                    data: <?= $actMins ?>,
                    backgroundColor: 'rgba(99,102,241,0.5)',
                    borderColor: '#6366f1',
                    borderWidth: 1,
                    borderRadius: 4,
                }]
            },
            options: {
                responsive: true, maintainAspectRatio: false,
                plugins: { legend: { display: false } },
                scales: {
                    x: { ticks: { color: textColor(), maxRotation: 45, font: { size: 10 } }, grid: { color: gridColor() } },
                    y: { ticks: { color: textColor(), font: { size: 10 } }, grid: { color: gridColor() }, beginAtZero: true }
                }
            }
        });
    }
    // Subject doughnut
    if (!subChartInst && document.getElementById('subChart')) {
        const labels = <?= $subjectLabels ?>;
        if (labels.length > 0) {
            subChartInst = new Chart(document.getElementById('subChart'), {
                type: 'doughnut',
                data: {
                    labels: labels,
                    datasets: [{
                        data: <?= $subjectMins ?>,
                        backgroundColor: <?= $subjectColors ?>,
                        borderWidth: 2,
                        borderColor: isDark() ? '#1a1a2e' : '#ffffff',
                    }]
                },
                options: {
                    responsive: true, maintainAspectRatio: false,
                    cutout: '62%',
                    plugins: {
                        legend: {
                            position: 'right',
                            labels: { color: textColor(), font: { size: 11 }, boxWidth: 12, padding: 10 }
                        }
                    }
                }
            });
        }
    }
}

function initMarksChart() {
    if (!marksChartInst && document.getElementById('marksChart')) {
        const labels = <?= $markLabels ?>;
        if (labels.length > 0) {
            marksChartInst = new Chart(document.getElementById('marksChart'), {
                type: 'bar',
                data: {
                    labels: labels,
                    datasets: [{
                        label: '%',
                        data: <?= $markPcts ?>,
                        backgroundColor: <?= $markPcts ?>.map(v => v >= 75 ? 'rgba(16,185,129,0.6)' : v >= 50 ? 'rgba(245,158,11,0.6)' : 'rgba(239,68,68,0.6)'),
                        borderRadius: 4,
                    }]
                },
                options: {
                    responsive: true, maintainAspectRatio: false,
                    plugins: { legend: { display: false } },
                    scales: {
                        x: { ticks: { color: textColor(), font: { size: 10 }, maxRotation: 40 }, grid: { display: false } },
                        y: { min: 0, max: 100, ticks: { color: textColor(), font: { size: 10 }, callback: v => v+'%' }, grid: { color: gridColor() } }
                    }
                }
            });
        }
    }
}

// Init overview on load (it's the default tab)
document.addEventListener('DOMContentLoaded', initOverviewCharts);
</script>

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