<?php
declare(strict_types=1);

require __DIR__ . '/../partials/auth.php';

$pageTitle = 'Student Report';
$pageSubtitle = 'Detailed learning progress and XP';
$activeTeacherNav = 'analytics';

require_once __DIR__ . '/../../config/database.php';
$pdo = getDbConnection();

function h(string $value): string {
    return htmlspecialchars($value, ENT_QUOTES, 'UTF-8');
}

function reportTeacherScope(PDO $pdo): array {
    $role=(string)($_SESSION['user_role']??'teacher');
    if($role==='admin') return ['role'=>'admin','ready'=>true,'province_id'=>0,'school_id'=>0,'province'=>'','school'=>''];
    $q=$pdo->prepare("SELECT tp.province_id,tp.school_id,tp.province,tp.school_name,p.name province_master,s.name school_master FROM teacher_profiles tp LEFT JOIN provinces p ON p.id=tp.province_id LEFT JOIN schools s ON s.id=tp.school_id WHERE tp.user_id=? LIMIT 1");
    $q->execute([(int)($_SESSION['user_id']??0)]); $r=$q->fetch(PDO::FETCH_ASSOC)?:[];
    $pid=(int)($r['province_id']??0); $sid=(int)($r['school_id']??0);
    $pn=trim((string)($r['province_master']??$r['province']??'')); $sn=trim((string)($r['school_master']??$r['school_name']??''));
    return ['role'=>'teacher','ready'=>(($pid>0&&$sid>0)||($pn!==''&&$sn!=='')),'province_id'=>$pid,'school_id'=>$sid,'province'=>$pn,'school'=>$sn];
}
function reportStudentScopeSql(array $s,string $a='s'): string {
    if(($s['role']??'')!=='teacher') return ''; if(empty($s['ready'])) return ' AND 1=0';
    return ((int)$s['province_id']>0&&(int)$s['school_id']>0) ? " AND {$a}.province_id=? AND {$a}.school_id=?" : " AND TRIM({$a}.province)=? AND TRIM({$a}.school_name)=?";
}
function reportStudentScopeParams(array $s): array {
    if(($s['role']??'')!=='teacher'||empty($s['ready'])) return [];
    return ((int)$s['province_id']>0&&(int)$s['school_id']>0) ? [(int)$s['province_id'],(int)$s['school_id']] : [(string)$s['province'],(string)$s['school']];
}

$reportScope=reportTeacherScope($pdo);
$studentId = max(0, (int)($_GET['student_id'] ?? 0));
$export = trim((string)($_GET['export'] ?? ''));
if ($studentId <= 0) {
    header('Location: ./');
    exit;
}

$studentStmt = $pdo->prepare(
    "SELECT
        id,
        full_name,
        phone,
        email,
        province,
        school_name,
        class_name,
        last_login_at,
        status
     FROM students
     WHERE id = ?" . reportStudentScopeSql($reportScope,'students') . "
     LIMIT 1"
);
$studentStmt->execute(array_merge([$studentId],reportStudentScopeParams($reportScope)));
$student = $studentStmt->fetch(PDO::FETCH_ASSOC);

if (!$student) {
    http_response_code(404);
    exit('Student not found.');
}

/*
 * Activity progress is the source of scores/attempts.
 * xp_transactions is the only XP ledger.
 * XP context is also used as a fallback for activities that existed during
 * testing but were later deleted from activities.
 */
$rowsStmt = $pdo->prepare(
    "SELECT
        scp.content_id AS activity_id,
        scp.status,
        scp.best_score,
        scp.attempt_count,
        scp.first_started_at,
        scp.completed_at,
        scp.last_attempt_at,

        COALESCE(a.title, x.activity_title, CONCAT('Activity #', scp.content_id)) AS activity_title,
        COALESCE(a.activity_type, x.activity_type, 'activity') AS activity_type,

        COALESCE(le.id, x.lesson_id, 0) AS lesson_id,
        COALESCE(le.title, x.lesson_title, '') AS lesson_title,
        COALESCE(le.lesson_number, x.lesson_number, '') AS lesson_number,

        COALESCE(u.id, x.unit_id, 0) AS unit_id,
        COALESCE(u.unit_number, x.unit_number, '') AS unit_number,
        COALESCE(u.title, x.unit_title, '') AS unit_title,

        COALESCE(lv.id, x.level_id, 0) AS level_id,
        COALESCE(lv.name, x.level_name, '') AS level_name,

        COALESCE(b.id, x.book_id, 0) AS book_id,
        COALESCE(b.name, x.book_name, '') AS book_name,

        COALESCE(x.completion_xp, 0) AS completion_xp,
        COALESCE(x.practice_xp, 0) AS practice_xp,
        COALESCE(x.other_xp, 0) AS other_xp,
        COALESCE(x.total_xp, 0) AS total_xp

     FROM student_content_progress scp

     LEFT JOIN activities a
       ON a.id = scp.content_id
      AND scp.content_type = 'activity'

     LEFT JOIN lessons le ON le.id = a.lesson_id
     LEFT JOIN units u ON u.id = le.unit_id
     LEFT JOIN levels lv ON lv.id = u.level_id
     LEFT JOIN books b ON b.id = lv.book_id

     LEFT JOIN (
        SELECT
            xt.student_id,
            COALESCE(xt.activity_id, xt.reference_id) AS activity_key,
            MAX(xt.activity_type) AS activity_type,
            MAX(CONCAT(
                UCASE(LEFT(REPLACE(COALESCE(xt.activity_type,'Activity'),'_',' '),1)),
                SUBSTRING(REPLACE(COALESCE(xt.activity_type,'Activity'),'_',' '),2)
            )) AS activity_title,

            MAX(xt.lesson_id) AS lesson_id,
            MAX(le2.title) AS lesson_title,
            MAX(le2.lesson_number) AS lesson_number,

            MAX(xt.unit_id) AS unit_id,
            MAX(u2.unit_number) AS unit_number,
            MAX(u2.title) AS unit_title,

            MAX(xt.level_id) AS level_id,
            MAX(lv2.name) AS level_name,

            MAX(xt.book_id) AS book_id,
            MAX(b2.name) AS book_name,

            SUM(CASE WHEN xt.xp_source = 'completion' THEN xt.xp_change ELSE 0 END) AS completion_xp,
            SUM(CASE WHEN xt.xp_source IN ('practice','new_best') THEN xt.xp_change ELSE 0 END) AS practice_xp,
            SUM(CASE WHEN xt.xp_source IS NULL OR xt.xp_source NOT IN ('completion','practice','new_best') THEN xt.xp_change ELSE 0 END) AS other_xp,
            SUM(xt.xp_change) AS total_xp
        FROM xp_transactions xt
        LEFT JOIN lessons le2 ON le2.id = xt.lesson_id
        LEFT JOIN units u2 ON u2.id = xt.unit_id
        LEFT JOIN levels lv2 ON lv2.id = xt.level_id
        LEFT JOIN books b2 ON b2.id = xt.book_id
        WHERE xt.student_id = ?
        GROUP BY xt.student_id, COALESCE(xt.activity_id, xt.reference_id)
     ) x
       ON x.student_id = scp.student_id
      AND x.activity_key = scp.content_id

     WHERE scp.student_id = ?
       AND scp.content_type = 'activity'
       AND scp.status <> 'not_started'

     ORDER BY
        book_id ASC,
        level_id ASC,
        unit_id ASC,
        lesson_id ASC,
        COALESCE(a.sort_order, 999999) ASC,
        scp.content_id ASC"
);
$rowsStmt->execute([$studentId, $studentId]);
$rows = $rowsStmt->fetchAll(PDO::FETCH_ASSOC);

$totalXpStmt = $pdo->prepare(
    "SELECT
        COALESCE(SUM(CASE WHEN xp_source = 'completion' THEN xp_change ELSE 0 END),0) AS completion_xp,
        COALESCE(SUM(CASE WHEN xp_source IN ('practice','new_best') THEN xp_change ELSE 0 END),0) AS practice_xp,
        COALESCE(SUM(CASE WHEN xp_source IS NULL OR xp_source NOT IN ('completion','practice','new_best') THEN xp_change ELSE 0 END),0) AS other_xp,
        COALESCE(SUM(xp_change),0) AS total_xp
     FROM xp_transactions
     WHERE student_id = ?"
);
$totalXpStmt->execute([$studentId]);
$xpSummary = $totalXpStmt->fetch(PDO::FETCH_ASSOC) ?: [];

$completedActivities = 0;
$totalAttempts = 0;
$scoreSum = 0;
$scoreCount = 0;
$lastLearning = '';

foreach ($rows as $row) {
    if ((string)$row['status'] === 'completed') {
        $completedActivities++;
    }

    $totalAttempts += (int)$row['attempt_count'];

    if ((int)$row['best_score'] > 0) {
        $scoreSum += (int)$row['best_score'];
        $scoreCount++;
    }

    $candidate = (string)($row['last_attempt_at'] ?? '');
    if ($candidate !== '' && ($lastLearning === '' || strtotime($candidate) > strtotime($lastLearning))) {
        $lastLearning = $candidate;
    }
}

$averageBestScore = $scoreCount > 0 ? (int)round($scoreSum / $scoreCount) : 0;

$grouped = [];
foreach ($rows as $row) {
    $bookName = trim((string)$row['book_name']) ?: 'Unknown Book';
    $levelName = trim((string)$row['level_name']);
    $unitNumber = trim((string)$row['unit_number']);
    $unitTitle = trim((string)$row['unit_title']);
    $lessonTitle = trim((string)$row['lesson_title']);
    $lessonNumber = trim((string)$row['lesson_number']);

    $bookKey = (string)$row['book_id'] . '|' . $bookName . '|' . $levelName;
    $unitKey = (string)$row['unit_id'] . '|' . $unitNumber . '|' . $unitTitle;
    $lessonKey = (string)$row['lesson_id'] . '|' . $lessonTitle . '|' . $lessonNumber;

    if (!isset($grouped[$bookKey])) {
        $grouped[$bookKey] = [
            'book_name' => $bookName,
            'level_name' => $levelName,
            'units' => [],
        ];
    }

    if (!isset($grouped[$bookKey]['units'][$unitKey])) {
        $grouped[$bookKey]['units'][$unitKey] = [
            'unit_number' => $unitNumber,
            'unit_title' => $unitTitle,
            'lessons' => [],
        ];
    }

    if (!isset($grouped[$bookKey]['units'][$unitKey]['lessons'][$lessonKey])) {
        $grouped[$bookKey]['units'][$unitKey]['lessons'][$lessonKey] = [
            'lesson_title' => $lessonTitle,
            'lesson_number' => $lessonNumber,
            'activities' => [],
        ];
    }

    $grouped[$bookKey]['units'][$unitKey]['lessons'][$lessonKey]['activities'][] = $row;
}

/*
 * Export Student Detail Report as Excel-compatible CSV.
 * Uses the exact rows and XP summary already loaded above.
 */
if ($export === 'excel') {
    $safeName = preg_replace('/[^A-Za-z0-9_-]+/', '-', (string)$student['full_name']);
    $safeName = trim((string)$safeName, '-');
    if ($safeName === '') {
        $safeName = 'student-' . $studentId;
    }

    $filename = 'EnglishSpeak-Student-Report-' . $safeName . '-' . date('Y-m-d-His') . '.csv';

    header('Content-Type: text/csv; charset=UTF-8');
    header('Content-Disposition: attachment; filename="' . $filename . '"');
    header('Cache-Control: no-store, no-cache, must-revalidate');

    $out = fopen('php://output', 'wb');
    fwrite($out, "\xEF\xBB\xBF");

    fputcsv($out, ['EnglishSpeak - Student Report']);
    fputcsv($out, ['Student', (string)$student['full_name']]);
    fputcsv($out, ['Phone', (string)($student['phone'] ?? '')]);
    fputcsv($out, ['Email', (string)($student['email'] ?? '')]);
    fputcsv($out, ['Province', (string)($student['province'] ?? '')]);
    fputcsv($out, ['School', (string)($student['school_name'] ?? '')]);
    fputcsv($out, ['Class', (string)($student['class_name'] ?? '')]);
    fputcsv($out, []);

    fputcsv($out, ['Activities completed', $completedActivities]);
    fputcsv($out, ['Average best score', $averageBestScore . '%']);
    fputcsv($out, ['Attempts', $totalAttempts]);
    fputcsv($out, ['Completion XP', (int)($xpSummary['completion_xp'] ?? 0)]);
    fputcsv($out, ['Practice XP', (int)($xpSummary['practice_xp'] ?? 0)]);
    fputcsv($out, ['Other XP', (int)($xpSummary['other_xp'] ?? 0)]);
    fputcsv($out, ['Total XP', (int)($xpSummary['total_xp'] ?? 0)]);
    fputcsv($out, ['Last learning', $lastLearning !== '' ? date('d/m/Y H:i', strtotime($lastLearning)) : '']);
    fputcsv($out, []);

    fputcsv($out, [
        'Book',
        'Level',
        'Unit',
        'Unit title',
        'Lesson',
        'Lesson title',
        'Activity',
        'Activity type',
        'Status',
        'Best score',
        'Attempts',
        'Completion XP',
        'Practice XP',
        'Other XP',
        'Total XP',
        'First started',
        'Completed at',
        'Last learning',
    ]);

    foreach ($rows as $activity) {
        $unitNumber = trim((string)($activity['unit_number'] ?? ''));
        $lessonNumber = trim((string)($activity['lesson_number'] ?? ''));
        $activityName = trim((string)($activity['activity_title'] ?? ''));
        if ($activityName === '') {
            $activityName = ucwords(str_replace('_', ' ', (string)($activity['activity_type'] ?? 'activity')));
        }

        fputcsv($out, [
            (string)($activity['book_name'] ?? ''),
            (string)($activity['level_name'] ?? ''),
            $unitNumber,
            (string)($activity['unit_title'] ?? ''),
            $lessonNumber,
            (string)($activity['lesson_title'] ?? ''),
            $activityName,
            ucwords(str_replace('_', ' ', (string)($activity['activity_type'] ?? 'activity'))),
            (string)($activity['status'] ?? ''),
            (int)($activity['best_score'] ?? 0) . '%',
            (int)($activity['attempt_count'] ?? 0),
            (int)($activity['completion_xp'] ?? 0),
            (int)($activity['practice_xp'] ?? 0),
            (int)($activity['other_xp'] ?? 0),
            (int)($activity['total_xp'] ?? 0),
            !empty($activity['first_started_at']) ? date('d/m/Y H:i', strtotime((string)$activity['first_started_at'])) : '',
            !empty($activity['completed_at']) ? date('d/m/Y H:i', strtotime((string)$activity['completed_at'])) : '',
            !empty($activity['last_attempt_at']) ? date('d/m/Y H:i', strtotime((string)$activity['last_attempt_at'])) : '',
        ]);
    }

    fclose($out);
    exit;
}

/*
 * PDF export: clean A4 landscape print view.
 * Uses the same Student Report data already loaded above.
 * Browser print dialog can save directly as PDF.
 */
if ($export === 'pdf') {
    ?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>EnglishSpeak - Student Report - <?= h((string)$student['full_name']) ?></title>
<style>
@page{size:A4 landscape;margin:10mm}
*{box-sizing:border-box}
body{font-family:Arial,"DejaVu Sans",sans-serif;color:#111;margin:0;font-size:10px}
h1{font-size:20px;margin:0 0 4px}
h2{font-size:14px;margin:14px 0 6px}
.meta{color:#555;line-height:1.5;margin-bottom:10px}
.stats{display:grid;grid-template-columns:repeat(5,1fr);gap:7px;margin:10px 0 14px}
.stat{border:1px solid #bbb;border-radius:7px;padding:7px}
.stat span{display:block;color:#666;font-size:8px}
.stat strong{display:block;font-size:15px;margin-top:3px}
.book{margin-top:12px;page-break-inside:avoid}
.book-title{font-size:14px;font-weight:700;border-bottom:2px solid #555;padding-bottom:4px}
.unit-title{font-size:12px;font-weight:700;margin:9px 0 5px}
.lesson-title{font-size:10px;font-weight:700;margin:7px 0 4px}
table{width:100%;border-collapse:collapse;margin-bottom:7px}
th,td{border:1px solid #bbb;padding:4px 5px;text-align:left;vertical-align:top}
th{background:#f1f1f1;font-size:8px;text-transform:uppercase}
.num{text-align:right;white-space:nowrap}
.no-print{margin-bottom:10px}
@media print{.no-print{display:none}body{-webkit-print-color-adjust:exact;print-color-adjust:exact}}
</style>
</head>
<body>
<div class="no-print">
    <button type="button" onclick="window.print()">Save / Print PDF</button>
    <button type="button" onclick="history.back()">Back</button>
</div>

<h1>EnglishSpeak - Student Report</h1>
<div class="meta">
    <strong><?= h((string)$student['full_name']) ?></strong>
    <?php if (!empty($student['class_name'])): ?> • Class: <?= h((string)$student['class_name']) ?><?php endif; ?>
    <?php if (!empty($student['school_name'])): ?> • <?= h((string)$student['school_name']) ?><?php endif; ?>
    <?php if (!empty($student['province'])): ?> • <?= h((string)$student['province']) ?><?php endif; ?>
    <br>Generated: <?= h(date('d/m/Y H:i')) ?>
</div>

<div class="stats">
    <div class="stat"><span>Activities completed</span><strong><?= number_format($completedActivities) ?></strong></div>
    <div class="stat"><span>Average best score</span><strong><?= $averageBestScore ?>%</strong></div>
    <div class="stat"><span>Attempts</span><strong><?= number_format($totalAttempts) ?></strong></div>
    <div class="stat"><span>Completion XP</span><strong>+<?= number_format((int)($xpSummary['completion_xp'] ?? 0)) ?></strong></div>
    <div class="stat"><span>Practice XP / Total XP</span><strong>+<?= number_format((int)($xpSummary['practice_xp'] ?? 0)) ?> / <?= number_format((int)($xpSummary['total_xp'] ?? 0)) ?></strong></div>
</div>

<?php if (!$rows): ?>
<p>This student has no activity learning data yet.</p>
<?php else: ?>
<?php foreach ($grouped as $book): ?>
<section class="book">
    <div class="book-title">
        <?= h((string)$book['book_name']) ?>
        <?php if ((string)$book['level_name'] !== ''): ?> • <?= h((string)$book['level_name']) ?><?php endif; ?>
    </div>

    <?php foreach ($book['units'] as $unit): ?>
        <div class="unit-title">
            <?= h((string)($unit['unit_number'] ?: 'Unit')) ?>
            <?php if ((string)$unit['unit_title'] !== ''): ?> • <?= h((string)$unit['unit_title']) ?><?php endif; ?>
        </div>

        <?php foreach ($unit['lessons'] as $lesson): ?>
            <div class="lesson-title">
                <?= h((string)($lesson['lesson_title'] ?: ('Lesson ' . $lesson['lesson_number']))) ?>
            </div>
            <table>
                <thead>
                <tr>
                    <th>Activity</th>
                    <th>Status</th>
                    <th class="num">Best Score</th>
                    <th class="num">Attempts</th>
                    <th class="num">Completion XP</th>
                    <th class="num">Practice XP</th>
                    <th>Last Learning</th>
                </tr>
                </thead>
                <tbody>
                <?php foreach ($lesson['activities'] as $activity): ?>
                <?php
                    $activityName = trim((string)$activity['activity_title']);
                    if ($activityName === '') {
                        $activityName = ucwords(str_replace('_', ' ', (string)$activity['activity_type']));
                    }
                ?>
                <tr>
                    <td><?= h($activityName) ?></td>
                    <td><?= (string)$activity['status'] === 'completed' ? 'Completed' : 'In progress' ?></td>
                    <td class="num"><?= (int)$activity['best_score'] ?>%</td>
                    <td class="num"><?= number_format((int)$activity['attempt_count']) ?></td>
                    <td class="num">+<?= number_format((int)$activity['completion_xp']) ?></td>
                    <td class="num">+<?= number_format((int)$activity['practice_xp']) ?></td>
                    <td><?= !empty($activity['last_attempt_at']) ? h(date('d/m/Y H:i', strtotime((string)$activity['last_attempt_at']))) : '—' ?></td>
                </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
        <?php endforeach; ?>
    <?php endforeach; ?>
</section>
<?php endforeach; ?>
<?php endif; ?>

<script>
window.addEventListener('load', function () {
    window.setTimeout(function () { window.print(); }, 250);
});
</script>
</body>
</html>
<?php
    exit;
}

ob_start();
?>

<style>
.report-page{display:grid;gap:18px}
.report-back{display:inline-flex;align-items:center;gap:6px;color:inherit;text-decoration:none;font-weight:700;font-size:13px}
.report-student-card{display:flex;justify-content:space-between;gap:18px;align-items:center;padding:18px;border:1px solid var(--border);border-radius:16px;background:var(--surface)}
.report-student-card h2{margin:0 0 5px;font-size:26px}
.report-student-meta{display:flex;flex-wrap:wrap;gap:8px 14px;color:var(--muted);font-size:12px}
.report-xp-badge{min-width:130px;padding:14px 18px;border-radius:14px;background:#fff8df;text-align:center}
.report-xp-badge span{display:block;color:#946200;font-size:11px}
.report-xp-badge strong{display:block;margin-top:3px;color:#8a5a00;font-size:25px}
.report-stats{display:grid;grid-template-columns:repeat(5,minmax(0,1fr));gap:12px}
.report-stat{padding:15px;border:1px solid var(--border);border-radius:14px;background:var(--surface)}
.report-stat span{display:block;color:var(--muted);font-size:11px;margin-bottom:5px}
.report-stat strong{font-size:22px}
.book-report{border:1px solid var(--border);border-radius:16px;background:var(--surface);overflow:hidden}
.book-report-head{padding:16px 18px;background:#f8fbff;border-bottom:1px solid var(--border)}
.book-report-head strong{font-size:17px}
.book-report-head span{margin-left:7px;color:var(--muted);font-size:12px}
.unit-report{padding:16px 18px;border-bottom:1px solid var(--border)}
.unit-report:last-child{border-bottom:0}
.unit-report-title{margin:0 0 12px;font-size:15px}
.unit-report-title small{color:var(--muted);font-weight:400}
.lesson-report{margin-top:12px;border:1px solid var(--border);border-radius:13px;overflow:hidden}
.lesson-report-head{display:flex;justify-content:space-between;gap:10px;padding:11px 13px;background:#fbfcfe}
.lesson-report-head strong{font-size:13px}
.activity-table-wrap{overflow:auto}
.activity-table{width:100%;border-collapse:collapse;min-width:800px}
.activity-table th,.activity-table td{padding:11px 13px;border-top:1px solid var(--border);text-align:left}
.activity-table th{font-size:10px;text-transform:uppercase;letter-spacing:.04em;color:var(--muted)}
.activity-table .num{text-align:right;font-variant-numeric:tabular-nums}
.status-pill{display:inline-flex;padding:3px 8px;border-radius:999px;font-size:10px;font-weight:800}
.status-completed{background:#eaf8ef;color:#177244}
.status-in_progress{background:#fff5dd;color:#8a5d00}
.empty-detail{padding:48px 20px;text-align:center;color:var(--muted);border:1px dashed var(--border);border-radius:16px}
@media(max-width:900px){.report-stats{grid-template-columns:repeat(2,minmax(0,1fr))}}
@media(max-width:620px){.report-student-card{align-items:stretch;flex-direction:column}.report-xp-badge{width:100%}.report-stats{grid-template-columns:1fr 1fr}}
</style>

<div class="report-page">
    <div style="display:flex;justify-content:space-between;align-items:center;gap:10px;">
        <a class="report-back" href="./">← Back to Analytics</a>
        <div style="display:flex;gap:8px;align-items:center;">
            <a
                class="button button-secondary"
                href="?<?= h(http_build_query(['student_id' => $studentId, 'export' => 'excel'])) ?>"
            >Export Excel</a>
            <a
                class="button button-secondary"
                href="?<?= h(http_build_query(['student_id' => $studentId, 'export' => 'pdf'])) ?>"
            >Export PDF</a>
        </div>
    </div>

    <section class="report-student-card">
        <div>
            <span class="section-kicker">Student Report</span>
            <h2><?= h((string)$student['full_name']) ?></h2>
            <div class="report-student-meta">
                <?php if ((string)$student['class_name'] !== ''): ?>
                    <span>Class: <?= h((string)$student['class_name']) ?></span>
                <?php endif; ?>
                <?php if ((string)$student['school_name'] !== ''): ?>
                    <span><?= h((string)$student['school_name']) ?></span>
                <?php endif; ?>
                <?php if ((string)$student['province'] !== ''): ?>
                    <span><?= h((string)$student['province']) ?></span>
                <?php endif; ?>
                <?php if ((string)$student['phone'] !== ''): ?>
                    <span><?= h((string)$student['phone']) ?></span>
                <?php endif; ?>
            </div>
        </div>

        <div class="report-xp-badge">
            <span>Total XP</span>
            <strong><?= number_format((int)($xpSummary['total_xp'] ?? 0)) ?></strong>
        </div>
    </section>

    <section class="report-stats">
        <div class="report-stat">
            <span>Activities completed</span>
            <strong><?= number_format($completedActivities) ?></strong>
        </div>
        <div class="report-stat">
            <span>Average best score</span>
            <strong><?= $averageBestScore ?>%</strong>
        </div>
        <div class="report-stat">
            <span>Attempts</span>
            <strong><?= number_format($totalAttempts) ?></strong>
        </div>
        <div class="report-stat">
            <span>Completion XP</span>
            <strong>+<?= number_format((int)($xpSummary['completion_xp'] ?? 0)) ?></strong>
        </div>
        <div class="report-stat">
            <span>Practice XP</span>
            <strong>+<?= number_format((int)($xpSummary['practice_xp'] ?? 0)) ?></strong>
        </div>
    </section>

    <?php if ($lastLearning !== ''): ?>
        <div style="color:var(--muted);font-size:12px;">
            Last learning: <?= h(date('d/m/Y H:i', strtotime($lastLearning))) ?>
        </div>
    <?php endif; ?>

    <?php if (!$rows): ?>
        <div class="empty-detail">This student has no activity learning data yet.</div>
    <?php else: ?>
        <?php foreach ($grouped as $book): ?>
            <section class="book-report">
                <div class="book-report-head">
                    <strong><?= h((string)$book['book_name']) ?></strong>
                    <?php if ((string)$book['level_name'] !== ''): ?>
                        <span>• <?= h((string)$book['level_name']) ?></span>
                    <?php endif; ?>
                </div>

                <?php foreach ($book['units'] as $unit): ?>
                    <div class="unit-report">
                        <h3 class="unit-report-title">
                            <?= h((string)($unit['unit_number'] ?: 'Unit')) ?>
                            <?php if ((string)$unit['unit_title'] !== ''): ?>
                                <small>• <?= h((string)$unit['unit_title']) ?></small>
                            <?php endif; ?>
                        </h3>

                        <?php foreach ($unit['lessons'] as $lesson): ?>
                            <div class="lesson-report">
                                <div class="lesson-report-head">
                                    <strong>
                                        <?= h((string)($lesson['lesson_title'] ?: ('Lesson ' . $lesson['lesson_number']))) ?>
                                    </strong>
                                </div>

                                <div class="activity-table-wrap">
                                    <table class="activity-table">
                                        <thead>
                                            <tr>
                                                <th>Activity</th>
                                                <th>Status</th>
                                                <th class="num">Best Score</th>
                                                <th class="num">Attempts</th>
                                                <th class="num">Completion XP</th>
                                                <th class="num">Practice XP</th>
                                                <th>Last Learning</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php foreach ($lesson['activities'] as $activity): ?>
                                                <?php
                                                    $status = (string)$activity['status'];
                                                    $activityName = trim((string)$activity['activity_title']);
                                                    if ($activityName === '') {
                                                        $activityName = ucwords(str_replace('_', ' ', (string)$activity['activity_type']));
                                                    }
                                                ?>
                                                <tr>
                                                    <td>
                                                        <strong><?= h($activityName) ?></strong>
                                                        <div style="margin-top:2px;color:var(--muted);font-size:10px;">
                                                            <?= h(ucwords(str_replace('_', ' ', (string)$activity['activity_type']))) ?>
                                                        </div>
                                                    </td>
                                                    <td>
                                                        <span class="status-pill status-<?= h($status) ?>">
                                                            <?= $status === 'completed' ? 'Completed' : 'In progress' ?>
                                                        </span>
                                                    </td>
                                                    <td class="num"><?= (int)$activity['best_score'] ?>%</td>
                                                    <td class="num"><?= number_format((int)$activity['attempt_count']) ?></td>
                                                    <td class="num">+<?= number_format((int)$activity['completion_xp']) ?></td>
                                                    <td class="num">+<?= number_format((int)$activity['practice_xp']) ?></td>
                                                    <td>
                                                        <?= !empty($activity['last_attempt_at'])
                                                            ? h(date('d/m/Y H:i', strtotime((string)$activity['last_attempt_at'])))
                                                            : '—' ?>
                                                    </td>
                                                </tr>
                                            <?php endforeach; ?>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                <?php endforeach; ?>
            </section>
        <?php endforeach; ?>
    <?php endif; ?>
</div>

<?php
$content = ob_get_clean();
require __DIR__ . '/../layouts/app.php';
