<?php
declare(strict_types=1);

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

$pageTitle = 'Daily Learning Report';
$pageSubtitle = 'Who learned, what they practised, and when';
$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']];
}

function tableExists(PDO $pdo, string $table): bool {
    $stmt = $pdo->prepare(
        "SELECT COUNT(*)
         FROM information_schema.TABLES
         WHERE TABLE_SCHEMA = DATABASE()
           AND TABLE_NAME = ?"
    );
    $stmt->execute([$table]);
    return (int)$stmt->fetchColumn() > 0;
}

function tableColumns(PDO $pdo, string $table): array {
    if (!tableExists($pdo, $table)) return [];
    $rows = $pdo->query("SHOW COLUMNS FROM `" . str_replace('`', '``', $table) . "`")
        ->fetchAll(PDO::FETCH_ASSOC);
    $out = [];
    foreach ($rows as $row) {
        $name = (string)($row['Field'] ?? '');
        if ($name !== '') $out[$name] = true;
    }
    return $out;
}

function academicYearLabelColumn(PDO $pdo): ?string {
    $cols = tableColumns($pdo, 'academic_years');
    foreach (['name','year_name','label','title','school_year'] as $candidate) {
        if (isset($cols[$candidate])) return $candidate;
    }
    return null;
}

/*
 * Từ thời điểm Shared XP Engine mới được cài, student_activity_attempts lưu
 * từng lượt học nên báo cáo theo ngày là chính xác.
 * Dữ liệu cũ trước thời điểm này không thể khôi phục đầy đủ từng lượt học.
 */
$hasAttemptLog = tableExists($pdo, 'student_activity_attempts');
$reportScope=reportTeacherScope($pdo);

if (!tableExists($pdo, 'academic_years')) {
    http_response_code(500);
    exit('Missing required table: academic_years');
}

$academicYearCols = tableColumns($pdo, 'academic_years');
$yearLabelColumn = academicYearLabelColumn($pdo);
if ($yearLabelColumn === null || !isset($academicYearCols['id'])) {
    http_response_code(500);
    exit('Bảng academic_years chưa có cấu trúc phù hợp.');
}

$yearSelect = "SELECT id, `{$yearLabelColumn}` AS year_label"
    . (isset($academicYearCols['start_date']) ? ", start_date" : ", NULL AS start_date")
    . (isset($academicYearCols['end_date']) ? ", end_date" : ", NULL AS end_date")
    . " FROM academic_years"
    . (isset($academicYearCols['start_date']) ? " ORDER BY start_date DESC, id DESC" : " ORDER BY id DESC");

$academicYearRows = $pdo->query($yearSelect)->fetchAll(PDO::FETCH_ASSOC);
$academicYearId = max(0, (int)($_GET['academic_year_id'] ?? 0));

if ($academicYearId <= 0 && $academicYearRows !== []) {
    if (isset($academicYearCols['is_active'])) {
        $active = $pdo->query("SELECT id FROM academic_years WHERE is_active = 1 ORDER BY id DESC LIMIT 1")->fetchColumn();
        if ($active !== false) $academicYearId = (int)$active;
    } elseif (isset($academicYearCols['is_current'])) {
        $active = $pdo->query("SELECT id FROM academic_years WHERE is_current = 1 ORDER BY id DESC LIMIT 1")->fetchColumn();
        if ($active !== false) $academicYearId = (int)$active;
    } elseif (isset($academicYearCols['status'])) {
        $active = $pdo->query("SELECT id FROM academic_years WHERE status IN ('active','current') ORDER BY id DESC LIMIT 1")->fetchColumn();
        if ($active !== false) $academicYearId = (int)$active;
    }
    if ($academicYearId <= 0) $academicYearId = (int)($academicYearRows[0]['id'] ?? 0);
}

$selectedYear = null;
foreach ($academicYearRows as $yearRow) {
    if ((int)$yearRow['id'] === $academicYearId) {
        $selectedYear = $yearRow;
        break;
    }
}
if (!$selectedYear && $academicYearRows !== []) {
    $selectedYear = $academicYearRows[0];
    $academicYearId = (int)$selectedYear['id'];
}
$yearLabel = (string)($selectedYear['year_label'] ?? '');

$date = trim((string)($_GET['date'] ?? date('Y-m-d')));
if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $date)) {
    $date = date('Y-m-d');
}

$bookId = max(0, (int)($_GET['book_id'] ?? 0));
$levelId = max(0, (int)($_GET['level_id'] ?? 0));
$unitId = max(0, (int)($_GET['unit_id'] ?? 0));
$lessonId = max(0, (int)($_GET['lesson_id'] ?? 0));
$export = trim((string)($_GET['export'] ?? ''));

$books = $pdo->query(
    "SELECT id, name
     FROM books
     WHERE status = 'active'
     ORDER BY sort_order, id"
)->fetchAll(PDO::FETCH_ASSOC);

$levelsParams = [];
$levelsWhere = ["status = 'active'"];
if ($bookId > 0) {
    $levelsWhere[] = 'book_id = ?';
    $levelsParams[] = $bookId;
}
$levelsStmt = $pdo->prepare(
    "SELECT id, name
     FROM levels
     WHERE " . implode(' AND ', $levelsWhere) . "
     ORDER BY sort_order, level_number, id"
);
$levelsStmt->execute($levelsParams);
$levels = $levelsStmt->fetchAll(PDO::FETCH_ASSOC);

$unitsParams = [];
$unitsWhere = ["status = 'active'"];
if ($bookId > 0) {
    $unitsWhere[] = 'book_id = ?';
    $unitsParams[] = $bookId;
}
if ($levelId > 0) {
    $unitsWhere[] = 'level_id = ?';
    $unitsParams[] = $levelId;
}
$unitsStmt = $pdo->prepare(
    "SELECT id, unit_number, title
     FROM units
     WHERE " . implode(' AND ', $unitsWhere) . "
     ORDER BY sort_order, id"
);
$unitsStmt->execute($unitsParams);
$units = $unitsStmt->fetchAll(PDO::FETCH_ASSOC);

$lessonsParams = [];
$lessonsWhere = ["status = 'active'"];
if ($unitId > 0) {
    $lessonsWhere[] = 'unit_id = ?';
    $lessonsParams[] = $unitId;
}
$lessonsStmt = $pdo->prepare(
    "SELECT id, lesson_number, title
     FROM lessons
     WHERE " . implode(' AND ', $lessonsWhere) . "
     ORDER BY sort_order, id"
);
$lessonsStmt->execute($lessonsParams);
$lessons = $lessonsStmt->fetchAll(PDO::FETCH_ASSOC);

$summary = [
    'students' => 0,
    'attempts' => 0,
    'passed_attempts' => 0,
    'avg_score' => 0,
];
$rows = [];

if ($hasAttemptLog) {
    $where=["sa.academic_year_id = ?", "DATE(sa.attempted_at) = ?"];
    $params=[$academicYearId, $date];
    if($reportScope['role']==='teacher'){ $ss=reportStudentScopeSql($reportScope,'s'); if($ss!==''){ $where[]=preg_replace('/^\s*AND\s+/i','',$ss); $params=array_merge($params,reportStudentScopeParams($reportScope)); } }

    if ($bookId > 0) {
        $where[] = 'sa.book_id = ?';
        $params[] = $bookId;
    }
    if ($levelId > 0) {
        $where[] = 'sa.level_id = ?';
        $params[] = $levelId;
    }
    if ($unitId > 0) {
        $where[] = 'sa.unit_id = ?';
        $params[] = $unitId;
    }
    if ($lessonId > 0) {
        $where[] = 'sa.lesson_id = ?';
        $params[] = $lessonId;
    }

    $whereSql = implode(' AND ', $where);

    $summaryStmt = $pdo->prepare(
        "SELECT
            COUNT(DISTINCT sa.student_id) AS students,
            COUNT(*) AS attempts,
            SUM(CASE WHEN sa.passed = 1 THEN 1 ELSE 0 END) AS passed_attempts,
            ROUND(AVG(sa.score), 0) AS avg_score
         FROM student_activity_attempts sa
         INNER JOIN students s ON s.id = sa.student_id
         WHERE {$whereSql}"
    );
    $summaryStmt->execute($params);
    $summaryRow = $summaryStmt->fetch(PDO::FETCH_ASSOC) ?: [];

    $summary['students'] = (int)($summaryRow['students'] ?? 0);
    $summary['attempts'] = (int)($summaryRow['attempts'] ?? 0);
    $summary['passed_attempts'] = (int)($summaryRow['passed_attempts'] ?? 0);
    $summary['avg_score'] = (int)($summaryRow['avg_score'] ?? 0);

    $detailStmt = $pdo->prepare(
        "SELECT
            s.id AS student_id,
            s.full_name,
            s.province,
            s.school_name,
            s.class_name,

            COUNT(*) AS attempts,
            COUNT(DISTINCT sa.activity_id) AS activities_done,
            SUM(CASE WHEN sa.passed = 1 THEN 1 ELSE 0 END) AS passed_attempts,
            ROUND(AVG(sa.score), 0) AS avg_score,
            MAX(sa.score) AS best_score,
            MIN(sa.attempted_at) AS first_learning,
            MAX(sa.attempted_at) AS last_learning,

            GROUP_CONCAT(
                DISTINCT CONCAT(
                    COALESCE(a.title, REPLACE(sa.activity_type, '_', ' ')),
                    ' (', sa.score, '%)'
                )
                ORDER BY a.sort_order, sa.activity_id
                SEPARATOR ' • '
            ) AS activity_summary

         FROM student_activity_attempts sa
         INNER JOIN students s ON s.id = sa.student_id
         LEFT JOIN activities a ON a.id = sa.activity_id
         WHERE {$whereSql}
         GROUP BY
            s.id,
            s.full_name,
            s.province,
            s.school_name,
            s.class_name
         ORDER BY last_learning DESC, s.full_name ASC"
    );
    $detailStmt->execute($params);
    $rows = $detailStmt->fetchAll(PDO::FETCH_ASSOC);
}

$selectedContext = [];
if ($bookId > 0) {
    foreach ($books as $item) if ((int)$item['id'] === $bookId) $selectedContext[] = (string)$item['name'];
}
if ($levelId > 0) {
    foreach ($levels as $item) if ((int)$item['id'] === $levelId) $selectedContext[] = (string)$item['name'];
}
if ($unitId > 0) {
    foreach ($units as $item) if ((int)$item['id'] === $unitId) $selectedContext[] = (string)$item['unit_number'];
}
if ($lessonId > 0) {
    foreach ($lessons as $item) if ((int)$item['id'] === $lessonId) $selectedContext[] = (string)$item['title'];
}

/*
 * Export exactly the currently selected Daily Learning Report.
 * Data comes from student_activity_attempts using the same filters/query above.
 */
if ($export === 'excel') {
    $filename = 'EnglishSpeak-Daily-Learning-' . $date . '-' . date('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 - Daily Learning Report']);
    fputcsv($out, ['Academic year', $yearLabel]);
    fputcsv($out, ['Date', date('d/m/Y', strtotime($date))]);
    fputcsv($out, ['Context', $selectedContext ? implode(' • ', $selectedContext) : 'All']);
    fputcsv($out, []);
    fputcsv($out, ['Students learning', $summary['students']]);
    fputcsv($out, ['Activity attempts', $summary['attempts']]);
    fputcsv($out, ['Passed attempts', $summary['passed_attempts']]);
    fputcsv($out, ['Average score', $summary['avg_score'] . '%']);
    fputcsv($out, []);

    fputcsv($out, [
        'Student',
        'Province',
        'School',
        'Class',
        'Activities',
        'Attempts',
        'Passed',
        'Average score',
        'Best score',
        'Activities practised',
        'First learning',
        'Last learning',
    ]);

    foreach ($rows as $row) {
        fputcsv($out, [
            (string)$row['full_name'],
            (string)($row['province'] ?? ''),
            (string)($row['school_name'] ?? ''),
            (string)($row['class_name'] ?? ''),
            (int)$row['activities_done'],
            (int)$row['attempts'],
            (int)$row['passed_attempts'],
            (int)$row['avg_score'] . '%',
            (int)$row['best_score'] . '%',
            (string)($row['activity_summary'] ?? ''),
            !empty($row['first_learning']) ? date('d/m/Y H:i', strtotime((string)$row['first_learning'])) : '',
            !empty($row['last_learning']) ? date('d/m/Y H:i', strtotime((string)$row['last_learning'])) : '',
        ]);
    }

    fclose($out);
    exit;
}

/*
 * PDF export: clean A4 landscape print view using the exact current filters.
 * Browser print dialog can save the report directly as PDF.
 */
if ($export === 'pdf') {
    $contextText = $selectedContext ? implode(' • ', $selectedContext) : 'All';
    ?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>EnglishSpeak - Daily Learning Report</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}
.meta{color:#555;line-height:1.5;margin-bottom:12px}
.stats{display:grid;grid-template-columns:repeat(4,1fr);gap:8px;margin:10px 0 14px}
.stat{border:1px solid #bbb;border-radius:7px;padding:8px}
.stat span{display:block;color:#666;font-size:8px}
.stat strong{display:block;font-size:16px;margin-top:3px}
table{width:100%;border-collapse:collapse}
th,td{border:1px solid #bbb;padding:5px 6px;text-align:left;vertical-align:top}
th{background:#f1f1f1;font-size:8px;text-transform:uppercase}
.num{text-align:right;white-space:nowrap}
.activities{max-width:330px;line-height:1.4}
.nowrap{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 - Daily Learning Report</h1>
<div class="meta">
    Academic year: <strong><?= h($yearLabel) ?></strong>
    • Date: <strong><?= h(date('d/m/Y', strtotime($date))) ?></strong>
    • <?= h($contextText) ?>
    <br>Generated: <?= h(date('d/m/Y H:i')) ?>
</div>

<div class="stats">
    <div class="stat"><span>Students learning</span><strong><?= number_format($summary['students']) ?></strong></div>
    <div class="stat"><span>Activity attempts</span><strong><?= number_format($summary['attempts']) ?></strong></div>
    <div class="stat"><span>Passed attempts</span><strong><?= number_format($summary['passed_attempts']) ?></strong></div>
    <div class="stat"><span>Average score</span><strong><?= $summary['avg_score'] ?>%</strong></div>
</div>

<?php if (!$rows): ?>
<p>No recorded learning attempts for this filter.</p>
<?php else: ?>
<table>
<thead>
<tr>
    <th>Student</th>
    <th>Province / School</th>
    <th>Class</th>
    <th class="num">Activities</th>
    <th class="num">Attempts</th>
    <th class="num">Passed</th>
    <th class="num">Average</th>
    <th class="num">Best</th>
    <th>Activities practised</th>
    <th>First / Last</th>
</tr>
</thead>
<tbody>
<?php foreach ($rows as $row): ?>
<tr>
    <td><strong><?= h((string)$row['full_name']) ?></strong></td>
    <td>
        <?= h((string)($row['province'] ?: '—')) ?>
        <?php if (!empty($row['school_name'])): ?><br><?= h((string)$row['school_name']) ?><?php endif; ?>
    </td>
    <td><?= h((string)($row['class_name'] ?: '—')) ?></td>
    <td class="num"><?= number_format((int)$row['activities_done']) ?></td>
    <td class="num"><?= number_format((int)$row['attempts']) ?></td>
    <td class="num"><?= number_format((int)$row['passed_attempts']) ?></td>
    <td class="num"><?= (int)$row['avg_score'] ?>%</td>
    <td class="num"><?= (int)$row['best_score'] ?>%</td>
    <td class="activities"><?= h((string)$row['activity_summary']) ?></td>
    <td class="nowrap">
        <?= h(date('H:i', strtotime((string)$row['first_learning']))) ?>
        → <?= h(date('H:i', strtotime((string)$row['last_learning']))) ?>
    </td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<?php endif; ?>

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

ob_start();
?>

<style>
.daily-page{display:grid;gap:18px}
.daily-top{display:flex;justify-content:space-between;align-items:flex-end;gap:16px}
.daily-top h2{margin:0;font-size:28px}
.daily-top p{margin:5px 0 0;color:var(--muted)}
.daily-filter{display:grid;grid-template-columns:145px 160px repeat(4,minmax(145px,1fr)) auto auto;gap:9px;align-items:center}
.daily-filter input,.daily-filter select{height:40px;border:1px solid var(--border);border-radius:10px;background:var(--surface);padding:0 10px;min-width:0}
.daily-note{padding:12px 14px;border:1px solid #f0d98a;border-radius:12px;background:#fff9df;color:#745400;font-size:12px}
.daily-stats{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:12px}
.daily-stat{padding:16px;border:1px solid var(--border);border-radius:14px;background:var(--surface)}
.daily-stat span{display:block;color:var(--muted);font-size:11px;margin-bottom:6px}
.daily-stat strong{font-size:25px}
.daily-card{border:1px solid var(--border);border-radius:16px;background:var(--surface);overflow:hidden}
.daily-card-head{display:flex;justify-content:space-between;gap:12px;padding:16px 18px;border-bottom:1px solid var(--border)}
.daily-table-wrap{overflow:auto}
.daily-table{width:100%;border-collapse:collapse;min-width:1050px}
.daily-table th,.daily-table td{padding:12px 13px;border-bottom:1px solid var(--border);text-align:left;vertical-align:top}
.daily-table th{font-size:10px;text-transform:uppercase;letter-spacing:.04em;color:var(--muted);background:#fafbfc}
.daily-table tbody tr:last-child td{border-bottom:0}
.num{text-align:right!important;font-variant-numeric:tabular-nums}
.student-cell{display:grid;gap:3px}
.student-cell a{font-weight:800;color:inherit;text-decoration:none}
.student-cell small{color:var(--muted)}
.activity-summary{max-width:380px;font-size:12px;line-height:1.5}
.daily-empty{padding:50px 20px;text-align:center;color:var(--muted)}
@media(max-width:1200px){.daily-filter{grid-template-columns:repeat(3,minmax(0,1fr))}}
@media(max-width:900px){.daily-top{align-items:stretch;flex-direction:column}.daily-stats{grid-template-columns:1fr 1fr}.daily-filter{grid-template-columns:1fr 1fr}}
@media(max-width:560px){.daily-filter{grid-template-columns:1fr}}
</style>

<div class="daily-page">
    <div>
        <a href="./" style="color:inherit;text-decoration:none;font-weight:700;font-size:13px;">← Back to Analytics</a>
    </div>

    <div class="daily-top">
        <div>
            <span class="section-kicker">Teacher Report</span>
            <h2>Daily Learning Report</h2>
            <p>See how many students learned in a specific Lesson on a specific day.</p>
        </div>
    </div>

    <?php if (!$hasAttemptLog): ?>
        <div class="daily-note">
            The activity-attempt log has not been created yet. Install the updated
            <strong>xp_engine.php</strong>, then complete one student activity. The table
            will be created automatically and daily reporting will start from that point.
        </div>
    <?php endif; ?>

    <form method="get" class="daily-filter" id="dailyFilterForm">
        <select name="academic_year_id" id="academicYearFilter">
            <?php foreach ($academicYearRows as $yearOption): ?>
                <option value="<?= (int)$yearOption['id'] ?>" <?= $academicYearId === (int)$yearOption['id'] ? 'selected' : '' ?>>
                    <?= h((string)$yearOption['year_label']) ?>
                </option>
            <?php endforeach; ?>
        </select>

        <input type="date" name="date" id="dateFilter" value="<?= h($date) ?>">

        <select name="book_id" id="bookFilter">
            <option value="0">All books</option>
            <?php foreach ($books as $item): ?>
                <option value="<?= (int)$item['id'] ?>" <?= $bookId === (int)$item['id'] ? 'selected' : '' ?>>
                    <?= h((string)$item['name']) ?>
                </option>
            <?php endforeach; ?>
        </select>

        <select name="level_id" id="levelFilter">
            <option value="0">All grades</option>
            <?php foreach ($levels as $item): ?>
                <option value="<?= (int)$item['id'] ?>" <?= $levelId === (int)$item['id'] ? 'selected' : '' ?>>
                    <?= h((string)$item['name']) ?>
                </option>
            <?php endforeach; ?>
        </select>

        <select name="unit_id" id="unitFilter">
            <option value="0">All units</option>
            <?php foreach ($units as $item): ?>
                <option value="<?= (int)$item['id'] ?>" <?= $unitId === (int)$item['id'] ? 'selected' : '' ?>>
                    <?= h((string)$item['unit_number'] . ' • ' . (string)$item['title']) ?>
                </option>
            <?php endforeach; ?>
        </select>

        <select name="lesson_id" id="lessonFilter">
            <option value="0">All lessons</option>
            <?php foreach ($lessons as $item): ?>
                <option value="<?= (int)$item['id'] ?>" <?= $lessonId === (int)$item['id'] ? 'selected' : '' ?>>
                    <?= h((string)$item['title']) ?>
                </option>
            <?php endforeach; ?>
        </select>

        <button class="button button-secondary" type="submit" name="export" value="excel">Export Excel</button>
        <button class="button button-secondary" type="submit" name="export" value="pdf">Export PDF</button>
        <a class="button button-secondary" href="daily.php?academic_year_id=<?= (int)$academicYearId ?>">Today</a>
    </form>

    <script>
    (function () {
        const form = document.getElementById('dailyFilterForm');
        if (!form) return;

        const academicYear = document.getElementById('academicYearFilter');
        const date = document.getElementById('dateFilter');
        const book = document.getElementById('bookFilter');
        const level = document.getElementById('levelFilter');
        const unit = document.getElementById('unitFilter');
        const lesson = document.getElementById('lessonFilter');

        const submitFilter = () => {
            form.requestSubmit();
        };

        academicYear?.addEventListener('change', submitFilter);
        date?.addEventListener('change', submitFilter);

        book?.addEventListener('change', () => {
            if (level) level.value = '0';
            if (unit) unit.value = '0';
            if (lesson) lesson.value = '0';
            submitFilter();
        });

        level?.addEventListener('change', () => {
            if (unit) unit.value = '0';
            if (lesson) lesson.value = '0';
            submitFilter();
        });

        unit?.addEventListener('change', () => {
            if (lesson) lesson.value = '0';
            submitFilter();
        });

        lesson?.addEventListener('change', submitFilter);
    })();
    </script>

    <div style="color:var(--muted);font-size:12px;">
        Năm học <?= h($yearLabel) ?> • <?= h(date('d/m/Y', strtotime($date))) ?>
        <?php if ($selectedContext): ?>
            • <?= h(implode(' • ', $selectedContext)) ?>
        <?php endif; ?>
    </div>

    <div class="daily-stats">
        <div class="daily-stat">
            <span>Students learning</span>
            <strong><?= number_format($summary['students']) ?></strong>
        </div>
        <div class="daily-stat">
            <span>Activity attempts</span>
            <strong><?= number_format($summary['attempts']) ?></strong>
        </div>
        <div class="daily-stat">
            <span>Passed attempts</span>
            <strong><?= number_format($summary['passed_attempts']) ?></strong>
        </div>
        <div class="daily-stat">
            <span>Average score</span>
            <strong><?= $summary['avg_score'] ?>%</strong>
        </div>
    </div>

    <section class="daily-card">
        <div class="daily-card-head">
            <div>
                <strong>Students</strong>
                <div style="margin-top:3px;color:var(--muted);font-size:11px;">
                    One row per student for the selected date and learning context.
                </div>
            </div>
            <strong><?= count($rows) ?></strong>
        </div>

        <?php if (!$rows): ?>
            <div class="daily-empty">
                No recorded learning attempts for this filter.
            </div>
        <?php else: ?>
            <div class="daily-table-wrap">
                <table class="daily-table">
                    <thead>
                        <tr>
                            <th>Student</th>
                            <th class="num">Activities</th>
                            <th class="num">Attempts</th>
                            <th class="num">Passed</th>
                            <th class="num">Average</th>
                            <th class="num">Best</th>
                            <th>Activities practised</th>
                            <th>First / Last</th>
                        </tr>
                    </thead>
                    <tbody>
                    <?php foreach ($rows as $row): ?>
                        <tr>
                            <td>
                                <div class="student-cell">
                                    <a href="student.php?student_id=<?= (int)$row['student_id'] ?>">
                                        <?= h((string)$row['full_name']) ?>
                                    </a>
                                    <small><?= h((string)($row['school_name'] ?: $row['province'] ?: '—')) ?></small>
                                </div>
                            </td>
                            <td class="num"><?= number_format((int)$row['activities_done']) ?></td>
                            <td class="num"><?= number_format((int)$row['attempts']) ?></td>
                            <td class="num"><?= number_format((int)$row['passed_attempts']) ?></td>
                            <td class="num"><?= (int)$row['avg_score'] ?>%</td>
                            <td class="num"><?= (int)$row['best_score'] ?>%</td>
                            <td class="activity-summary"><?= h((string)$row['activity_summary']) ?></td>
                            <td>
                                <?= h(date('H:i', strtotime((string)$row['first_learning']))) ?>
                                →
                                <?= h(date('H:i', strtotime((string)$row['last_learning']))) ?>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        <?php endif; ?>
    </section>
</div>

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