<?php
// /elms/student/modules.php
declare(strict_types=1);

$PAGE_TITLE = 'My Modules';
$ACTIVE = 'modules';

require_once __DIR__ . '/../includes/student_auth.php';

$mysqli = $mysqli ?? ($conn ?? null);

if (!$mysqli instanceof mysqli) {
    http_response_code(500);
    exit('DB connection failed');
}

$mysqli->set_charset('utf8mb4');

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

if (!function_exists('table_exists')) {
    function table_exists(mysqli $db, string $table): bool {
        $table = $db->real_escape_string($table);
        $q = $db->query("SHOW TABLES LIKE '{$table}'");
        return $q && $q->num_rows > 0;
    }
}

if (!function_exists('col_exists')) {
    function col_exists(mysqli $db, string $table, string $col): bool {
        $table = $db->real_escape_string($table);
        $col = $db->real_escape_string($col);
        $q = $db->query("SHOW COLUMNS FROM `{$table}` LIKE '{$col}'");
        return $q && $q->num_rows > 0;
    }
}

if (!function_exists('exam_grade_from_percent')) {
    function exam_grade_from_percent(float $percent): array {
        if ($percent >= 75) return ['A', 'Distinction', 'success'];
        if ($percent >= 65) return ['B', 'Merit', 'primary'];
        if ($percent >= 55) return ['C', 'Credit', 'info'];
        if ($percent >= 40) return ['S', 'Pass', 'warning'];
        return ['F', 'Fail', 'danger'];
    }
}

$student_id = (int)($GLOBALS['STUDENT_ID'] ?? ($_SESSION['student_id'] ?? 0));
$selected_course_id = (int)($_GET['course_id'] ?? 0);

/*
|--------------------------------------------------------------------------
| Student
|--------------------------------------------------------------------------
*/

$studentCols = "id, full_name, academic_email, center_reg_no, reference_no, lms_status";

if (table_exists($mysqli, 'studentss') && col_exists($mysqli, 'studentss', 'course_id')) {
    $studentCols .= ", course_id";
}

$st = $mysqli->prepare("SELECT $studentCols FROM studentss WHERE id=? LIMIT 1");
$st->bind_param('i', $student_id);
$st->execute();
$student = $st->get_result()->fetch_assoc();
$st->close();

if (!$student) {
    session_destroy();
    header('Location: /elms/student/login.php');
    exit;
}

$_SESSION['student_name']   = $student['full_name'] ?? ($_SESSION['student_name'] ?? 'Student');
$_SESSION['academic_email'] = $student['academic_email'] ?? ($_SESSION['academic_email'] ?? '');
$_SESSION['center_reg_no']  = $student['center_reg_no'] ?? ($_SESSION['center_reg_no'] ?? '');

$GLOBALS['STUDENT_NAME']   = $_SESSION['student_name'];
$GLOBALS['STUDENT_EMAIL']  = $_SESSION['academic_email'];
$GLOBALS['STUDENT_REG_NO'] = $_SESSION['center_reg_no'];

$studentCenterRegNo = trim((string)($student['center_reg_no'] ?? ''));

$lms_status = strtolower(trim((string)($student['lms_status'] ?? 'active')));

if (in_array($lms_status, ['inactive', 'suspended'], true)) {
    session_destroy();
    header('Location: /elms/student/login.php');
    exit;
}

/*
|--------------------------------------------------------------------------
| Get Student Course IDs
|--------------------------------------------------------------------------
*/

$courseIds = [];
$courses = [];
$batches = [];

if (table_exists($mysqli, 'enrollments') && table_exists($mysqli, 'batches')) {
    $sql = "
        SELECT DISTINCT
            b.id AS batch_id,
            b.batch_name,
            b.batch_code,
            b.course_id,
            c.course_name
        FROM enrollments e
        INNER JOIN batches b ON b.id = e.batch_id
        LEFT JOIN courses c ON c.id = b.course_id
        WHERE e.student_id = ?
          AND b.course_id IS NOT NULL
        ORDER BY b.id DESC
    ";

    $st = $mysqli->prepare($sql);

    if ($st) {
        $st->bind_param('i', $student_id);
        $st->execute();
        $rs = $st->get_result();

        while ($row = $rs->fetch_assoc()) {
            $cid = (int)($row['course_id'] ?? 0);

            if ($cid > 0) {
                $courseIds[$cid] = $cid;

                $courses[$cid] = [
                    'id' => $cid,
                    'course_name' => $row['course_name'] ?: ('Course #' . $cid),
                ];

                $batches[$cid][] = [
                    'batch_id' => (int)$row['batch_id'],
                    'batch_name' => $row['batch_name'] ?: ($row['batch_code'] ?: 'Batch'),
                    'batch_code' => $row['batch_code'] ?? '',
                ];
            }
        }

        $st->close();
    }
}

if (!$courseIds && !empty($student['course_id'])) {
    $cid = (int)$student['course_id'];
    $courseIds[$cid] = $cid;

    $courseName = 'Course #' . $cid;

    if (table_exists($mysqli, 'courses')) {
        $q = $mysqli->query("SELECT course_name FROM courses WHERE id={$cid} LIMIT 1");
        $r = $q ? $q->fetch_assoc() : null;

        if ($r && !empty($r['course_name'])) {
            $courseName = $r['course_name'];
        }
    }

    $courses[$cid] = [
        'id' => $cid,
        'course_name' => $courseName,
    ];
}

/* Apply selected course filter from dashboard */
if ($selected_course_id > 0) {
    if (isset($courseIds[$selected_course_id])) {
        $courseIds = [$selected_course_id => $selected_course_id];

        if (isset($courses[$selected_course_id])) {
            $courses = [$selected_course_id => $courses[$selected_course_id]];
        }

        if (isset($batches[$selected_course_id])) {
            $batches = [$selected_course_id => $batches[$selected_course_id]];
        }
    } else {
        $courseIds = [];
        $courses = [];
        $batches = [];
    }
}

/*
|--------------------------------------------------------------------------
| Choose Module Table
|--------------------------------------------------------------------------
*/

$moduleTable = null;

foreach (['course_modules', 'lms_modules'] as $tbl) {
    if (!table_exists($mysqli, $tbl)) {
        continue;
    }

    if (!col_exists($mysqli, $tbl, 'id') || !col_exists($mysqli, $tbl, 'course_id')) {
        continue;
    }

    if ($courseIds) {
        $ids = implode(',', array_map('intval', array_values($courseIds)));
        $q = $mysqli->query("SELECT COUNT(*) AS n FROM `$tbl` WHERE course_id IN ($ids)");
        $r = $q ? $q->fetch_assoc() : null;

        if ((int)($r['n'] ?? 0) > 0) {
            $moduleTable = $tbl;
            break;
        }
    }

    if ($moduleTable === null) {
        $moduleTable = $tbl;
    }
}

$titleCol = null;
$orderCol = null;

if ($moduleTable) {
    $titleCol = col_exists($mysqli, $moduleTable, 'title') ? 'title' : (col_exists($mysqli, $moduleTable, 'name') ? 'name' : 'id');
    $orderCol = col_exists($mysqli, $moduleTable, 'sort_order') ? 'sort_order' : 'id';
}

/*
|--------------------------------------------------------------------------
| Content / Assessment Tables
|--------------------------------------------------------------------------
*/

$contentTable = null;

foreach (['lms_content', 'module_content', 'contents'] as $tbl) {
    if (table_exists($mysqli, $tbl) && col_exists($mysqli, $tbl, 'module_id')) {
        $contentTable = $tbl;
        break;
    }
}

$assessmentTable = null;

foreach (['lms_assessments', 'assessments', 'assignments', 'course_assessments'] as $tbl) {
    if (table_exists($mysqli, $tbl)) {
        $assessmentTable = $tbl;
        break;
    }
}

/*
|--------------------------------------------------------------------------
| Fetch Modules
|--------------------------------------------------------------------------
*/

$modulesByCourse = [];
$totalModules = 0;
$totalContent = 0;
$totalAssessments = 0;
$allModuleIds = [];

if ($courseIds && $moduleTable) {
    $ids = implode(',', array_map('intval', array_values($courseIds)));

    $joinSemester = table_exists($mysqli, 'elms_module_semesters') && col_exists($mysqli, 'elms_module_semesters', 'module_id');

    $semesterSelect = $joinSemester ? "COALESCE(ms.semester_no, 1) AS semester_no" : "1 AS semester_no";
    $semesterJoin = $joinSemester ? "LEFT JOIN elms_module_semesters ms ON ms.module_id = m.id" : "";

    $sql = "
        SELECT
            m.id,
            m.course_id,
            m.`$titleCol` AS title,
            $semesterSelect
        FROM `$moduleTable` m
        $semesterJoin
        WHERE m.course_id IN ($ids)
        ORDER BY m.course_id ASC, semester_no ASC, m.`$orderCol` ASC, m.id ASC
    ";

    $q = $mysqli->query($sql);

    while ($q && $m = $q->fetch_assoc()) {
        $mid = (int)$m['id'];
        $cid = (int)$m['course_id'];
        $sem = (int)($m['semester_no'] ?? 1);

        if ($sem <= 0) {
            $sem = 1;
        }

        $m['content_count'] = 0;
        $m['assessment_count'] = 0;

        if (!isset($modulesByCourse[$cid])) {
            $modulesByCourse[$cid] = [];
        }

        if (!isset($modulesByCourse[$cid][$sem])) {
            $modulesByCourse[$cid][$sem] = [];
        }

        $modulesByCourse[$cid][$sem][$mid] = $m;
        $allModuleIds[] = $mid;
        $totalModules++;
    }
}

/*
|--------------------------------------------------------------------------
| Content Counts
|--------------------------------------------------------------------------
*/

if ($contentTable && $modulesByCourse && $allModuleIds) {
    $midList = implode(',', array_map('intval', $allModuleIds));

    $activeSql = '';

    if (col_exists($mysqli, $contentTable, 'active')) {
        $activeSql = " AND active IN (1,'1','active','Active','ACTIVE')";
    }

    $q = $mysqli->query("
        SELECT module_id, COUNT(*) AS n
        FROM `$contentTable`
        WHERE module_id IN ($midList)
        $activeSql
        GROUP BY module_id
    ");

    while ($q && $r = $q->fetch_assoc()) {
        $mid = (int)$r['module_id'];
        $cnt = (int)$r['n'];
        $totalContent += $cnt;

        foreach ($modulesByCourse as $cid => $sems) {
            foreach ($sems as $sem => $mods) {
                if (isset($modulesByCourse[$cid][$sem][$mid])) {
                    $modulesByCourse[$cid][$sem][$mid]['content_count'] = $cnt;
                }
            }
        }
    }
}

$viewedByModule = [];

if (
    table_exists($mysqli, 'lms_student_content_progress') &&
    $allModuleIds
) {
    $midList = implode(',', array_map('intval', $allModuleIds));

    $q = $mysqli->query("
        SELECT module_id, COUNT(DISTINCT content_id) AS n
        FROM lms_student_content_progress
        WHERE student_id = {$student_id}
          AND module_id IN ($midList)
        GROUP BY module_id
    ");

    while ($q && $r = $q->fetch_assoc()) {
        $viewedByModule[(int)$r['module_id']] = (int)$r['n'];
    }
}

/*
|--------------------------------------------------------------------------
| Assessment Counts - Released + Exact Module only
|--------------------------------------------------------------------------
*/

$totalAssessments = 0;

foreach ($modulesByCourse as $cid => $sems) {
    foreach ($sems as $sem => $mods) {
        foreach ($mods as $mid => $m) {
            $modulesByCourse[$cid][$sem][$mid]['assessment_count'] = 0;
        }
    }
}

if (
    table_exists($mysqli, 'lms_assessments') &&
    (
        table_exists($mysqli, 'lms_assessment_students') ||
        (table_exists($mysqli, 'lms_assessment_batches') && table_exists($mysqli, 'enrollments'))
    )
) {
    $releaseSql = '';

    if (col_exists($mysqli, 'lms_assessments', 'workflow_status')) {
        $releaseSql = " AND a.workflow_status = 'released'";
    } elseif (col_exists($mysqli, 'lms_assessments', 'status')) {
        $releaseSql = " AND a.status = 'released'";
    } elseif (col_exists($mysqli, 'lms_assessments', 'is_released')) {
        $releaseSql = " AND a.is_released = 1";
    } elseif (col_exists($mysqli, 'lms_assessments', 'release_at')) {
    $releaseSql = " AND (a.release_at IS NULL OR a.release_at <= NOW())";
} elseif (col_exists($mysqli, 'lms_assessments', 'released_at')) {
    $releaseSql = " AND a.released_at IS NOT NULL";
}

    foreach ($modulesByCourse as $cid => $sems) {
        foreach ($sems as $sem => $mods) {
            foreach ($mods as $mid => $m) {
                $sqlA = "
                    SELECT COUNT(DISTINCT a.id) AS n
                    FROM lms_assessments a
                    LEFT JOIN lms_assessment_students ast
                        ON ast.assessment_id = a.id
                       AND ast.student_id = ?
                    LEFT JOIN lms_assessment_batches ab
                        ON ab.assessment_id = a.id
                    LEFT JOIN enrollments e
                        ON e.batch_id = ab.batch_id
                       AND e.student_id = ?
                    WHERE a.active = 1
                      $releaseSql
                      AND a.course_id = ?
                      AND a.module_id = ?
                      AND (ast.student_id IS NOT NULL OR e.student_id IS NOT NULL)
                ";

                $stA = $mysqli->prepare($sqlA);
                if ($stA) {
                    $stA->bind_param('iiii', $student_id, $student_id, $cid, $mid);
                    $stA->execute();
                    $cnt = (int)($stA->get_result()->fetch_assoc()['n'] ?? 0);
                    $stA->close();

                    $modulesByCourse[$cid][$sem][$mid]['assessment_count'] = $cnt;
                    $totalAssessments += $cnt;
                }
            }
        }
    }
}

/*
|--------------------------------------------------------------------------
| Course Exams - Final only / Last attempt only per unit
|--------------------------------------------------------------------------
*/

$examResultsByCourse = [];
$totalFinalExams = 0;

foreach ($courseIds as $cid) {
    $examResultsByCourse[(int)$cid] = [];
}

if (
    $courseIds &&
    $studentCenterRegNo !== '' &&
    table_exists($mysqli, 'results') &&
    table_exists($mysqli, 'exams')
) {
    $ids = implode(',', array_map('intval', array_values($courseIds)));

    $hasUnits = table_exists($mysqli, 'units');
    $hasCourseModules = table_exists($mysqli, 'course_modules');

    $rCourseSql = col_exists($mysqli, 'results', 'course_id') ? "r.course_id" : "NULL";
    $rUnitSql = col_exists($mysqli, 'results', 'unit_id') ? "r.unit_id" : "NULL";
    $rModuleNameSql = col_exists($mysqli, 'results', 'module_name') ? "r.module_name" : "NULL";
    $rReferenceSql = col_exists($mysqli, 'results', 'reference_no') ? "r.reference_no" : "NULL";
    $rDateSql = col_exists($mysqli, 'results', 'date_taken') ? "r.date_taken" : "NULL";
    $rGradeSql = col_exists($mysqli, 'results', 'grade') ? "r.grade" : "NULL";
    $rStatusSql = col_exists($mysqli, 'results', 'status') ? "r.status" : "NULL";

    $eCourseSql = col_exists($mysqli, 'exams', 'course_id') ? "e.course_id" : "NULL";
    $eUnitSql = col_exists($mysqli, 'exams', 'unit_id') ? "e.unit_id" : "NULL";
    $eTitleSql = col_exists($mysqli, 'exams', 'title') ? "e.title" : "NULL";
    $eUnitExamSql = col_exists($mysqli, 'exams', 'unit_exam') ? "e.unit_exam" : "NULL";
    $eExamTypeSql = col_exists($mysqli, 'exams', 'exam_type') ? "e.exam_type" : "NULL";

    $unitJoin = '';
    $unitNameSql = "NULL";
    $unitModuleIdSql = "NULL";

    if ($hasUnits) {
        $unitJoin = "LEFT JOIN units u ON u.id = COALESCE($rUnitSql, $eUnitSql)";
        $unitNameSql = col_exists($mysqli, 'units', 'name') ? "u.name" : "NULL";
        $unitModuleIdSql = col_exists($mysqli, 'units', 'module_id') ? "u.module_id" : "NULL";
    }

    $cmJoin = '';
    $cmTitleSql = "NULL";

    if ($hasCourseModules) {
        $cmJoin = "LEFT JOIN course_modules cm ON cm.id = $unitModuleIdSql";
        $cmTitleSql = col_exists($mysqli, 'course_modules', 'title') ? "cm.title" : "NULL";
    }

    $sqlExam = "
        SELECT
            r.id AS result_id,
            r.exam_id,
            COALESCE($rCourseSql, $eCourseSql) AS course_id,
            COALESCE($rUnitSql, $eUnitSql, r.exam_id) AS unit_key,
            r.score,
            r.total,
            $rDateSql AS date_taken,
            $rGradeSql AS result_grade,
            $rStatusSql AS result_status,
            $rModuleNameSql AS result_module_name,
            $eTitleSql AS exam_title,
            $eUnitExamSql AS unit_exam,
            $eExamTypeSql AS exam_type,
            $unitNameSql AS unit_name,
            $unitModuleIdSql AS module_id,
            $cmTitleSql AS module_title
        FROM results r
        INNER JOIN exams e ON e.id = r.exam_id
        $unitJoin
        $cmJoin
        INNER JOIN (
            SELECT
                COALESCE(r2.unit_id, e2.unit_id, r2.exam_id) AS unit_key,
                MAX(r2.id) AS last_result_id
            FROM results r2
            INNER JOIN exams e2 ON e2.id = r2.exam_id
            WHERE r2.reference_no = ?
              AND COALESCE(r2.course_id, e2.course_id) IN ($ids)
              AND (
                    LOWER(COALESCE(e2.exam_type, '')) = 'final'
                 OR LOWER(COALESCE(e2.unit_exam, '')) LIKE '%final%'
                 OR LOWER(COALESCE(e2.title, '')) LIKE '%final%'
                 OR LOWER(COALESCE(r2.module_name, '')) LIKE '%final%'
              )
            GROUP BY COALESCE(r2.unit_id, e2.unit_id, r2.exam_id)
        ) latest ON latest.last_result_id = r.id
        WHERE $rReferenceSql = ?
          AND COALESCE($rCourseSql, $eCourseSql) IN ($ids)
          AND (
                LOWER(COALESCE($eExamTypeSql, '')) = 'final'
             OR LOWER(COALESCE($eUnitExamSql, '')) LIKE '%final%'
             OR LOWER(COALESCE($eTitleSql, '')) LIKE '%final%'
             OR LOWER(COALESCE($rModuleNameSql, '')) LIKE '%final%'
          )
        ORDER BY COALESCE($rCourseSql, $eCourseSql) ASC, unit_key ASC, r.id DESC
    ";

    $stExam = $mysqli->prepare($sqlExam);

    if ($stExam) {
        $stExam->bind_param('ss', $studentCenterRegNo, $studentCenterRegNo);
        $stExam->execute();
        $rsExam = $stExam->get_result();

        while ($row = $rsExam->fetch_assoc()) {
            $cid = (int)($row['course_id'] ?? 0);
            if (!isset($examResultsByCourse[$cid])) {
                continue;
            }

            $score = (float)($row['score'] ?? 0);
            $total = (float)($row['total'] ?? 0);
            $percent = $total > 0 ? round(($score / $total) * 100, 2) : 0;
            [$gradeCalc, $statusCalc, $badgeClass] = exam_grade_from_percent($percent);

            $row['percent'] = $percent;
            $row['display_grade'] = trim((string)($row['result_grade'] ?? '')) !== '' ? $row['result_grade'] : $gradeCalc;
            $row['display_status'] = trim((string)($row['result_status'] ?? '')) !== '' ? $row['result_status'] : $statusCalc;
            $row['badge_class'] = $badgeClass;

            $moduleTitle = trim((string)($row['module_title'] ?? ''));
            $unitName = trim((string)($row['unit_name'] ?? ''));
            $resultModule = trim((string)($row['result_module_name'] ?? ''));
            $unitExam = trim((string)($row['unit_exam'] ?? ''));
            $examTitle = trim((string)($row['exam_title'] ?? ''));

            $row['display_module_name'] = $moduleTitle !== '' ? $moduleTitle : ($resultModule !== '' ? $resultModule : ($unitName !== '' ? $unitName : ($unitExam !== '' ? $unitExam : $examTitle)));
            $row['display_exam_name'] = $unitExam !== '' ? $unitExam : ($examTitle !== '' ? $examTitle : 'Final Exam');

            $examResultsByCourse[$cid][] = $row;
            $totalFinalExams++;
        }

        $stExam->close();
    }
}

require_once __DIR__ . '/../includes/student_layout_top.php';
?>

<style>
.modules-top-summary {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 16px;
    margin-bottom: 22px;
}

.modules-summary-card,
.modules-side-card,
.modules-main-card {
    background: #fff;
    border: 1px solid #e5e7eb;
    border-radius: 18px;
    box-shadow: 0 8px 22px rgba(15,23,42,.045);
}

.modules-summary-card {
    padding: 18px;
}

.modules-summary-icon {
    width: 40px;
    height: 40px;
    border-radius: 13px;
    background: #eff6ff;
    color: #034ea2;
    display: grid;
    place-items: center;
    font-size: 1.15rem;
    margin-bottom: 12px;
}

.modules-summary-value {
    font-size: 1.65rem;
    font-weight: 900;
    color: #1f2937;
    line-height: 1;
}

.modules-summary-label {
    color: #7b8190;
    font-weight: 750;
    font-size: .82rem;
    margin-top: 7px;
}

.modules-workspace {
    display: grid;
    grid-template-columns: 310px minmax(0, 1fr);
    gap: 22px;
    align-items: start;
}

.modules-side-card {
    padding: 16px;
    position: sticky;
    top: 98px;
}

.modules-side-title {
    font-weight: 900;
    color: #263247;
    margin-bottom: 14px;
}

.course-side-item {
    display: block;
    border: 1px solid #e5e7eb;
    border-radius: 15px;
    padding: 13px;
    color: #3f4652;
    margin-bottom: 10px;
    transition: .16s ease;
    background: #fff;
    text-decoration: none;
}

.course-side-item:hover,
.course-side-item.active {
    border-color: #034ea2;
    background: #f8fbff;
}

.course-side-name {
    font-weight: 850;
    line-height: 1.35;
    font-size: .92rem;
}

.course-side-meta {
    color: #7b8190;
    font-size: .76rem;
    margin-top: 5px;
    font-weight: 650;
}

.modules-main-card {
    overflow: hidden;
}

.modules-main-head {
    padding: 20px 22px;
    border-bottom: 1px solid #e5e7eb;
    background: linear-gradient(180deg, #ffffff, #fafbff);
}

.modules-main-title {
    margin: 0;
    font-size: 1.35rem;
    font-weight: 900;
    color: #12386f;
    letter-spacing: -.3px;
}

.modules-main-sub {
    color: #7b8190;
    margin-top: 6px;
    font-weight: 650;
}

.modules-tabs {
    display: flex;
    gap: 8px;
    margin-top: 16px;
    flex-wrap: wrap;
}

.modules-tab-btn {
    border: 1px solid #dbe3ef;
    background: #fff;
    color: #526071;
    border-radius: 999px;
    padding: 8px 14px;
    font-weight: 900;
    font-size: .82rem;
    transition: .15s ease;
}

.modules-tab-btn.active,
.modules-tab-btn:hover {
    background: #034ea2;
    color: #fff;
    border-color: #034ea2;
}

.modules-tab-panel {
    display: none;
}

.modules-tab-panel.active {
    display: block;
}

.modules-course-block {
    border-bottom: 1px solid #eef2f7;
}

.modules-course-block:last-child {
    border-bottom: 0;
}

.modules-course-block.hide-course {
    display: none;
}

.modules-course-block.show-course {
    display: block;
}

.modules-course-header {
    padding: 20px 22px 12px;
    display: flex;
    align-items: flex-start;
    justify-content: space-between;
    gap: 14px;
}

.course-title-clean {
    font-size: 1.12rem;
    font-weight: 900;
    color: #263247;
    margin: 0;
}

.batch-pill {
    display: inline-flex;
    align-items: center;
    gap: 5px;
    padding: 5px 9px;
    border-radius: 999px;
    background: #eff6ff;
    color: #034ea2;
    font-size: .73rem;
    font-weight: 800;
    margin-top: 8px;
    margin-right: 4px;
}

.semester-block {
    padding: 8px 22px 22px;
}

.semester-title-row {
    display: flex;
    align-items: center;
    gap: 10px;
    margin: 12px 0 14px;
}

.semester-icon {
    width: 34px;
    height: 34px;
    border-radius: 12px;
    background: #034ea2;
    color: #fff;
    display: grid;
    place-items: center;
}

.semester-title {
    font-weight: 900;
    color: #263247;
}

.semester-sub {
    font-size: .78rem;
    color: #7b8190;
    font-weight: 650;
}

.module-list {
    border: 1px solid #e5e7eb;
    border-radius: 16px;
    overflow: hidden;
    background: #fff;
}

.module-row-clean {
    display: grid;
    grid-template-columns: minmax(0, 1fr) 150px 125px 95px 38px;
    align-items: center;
    gap: 14px;
    padding: 18px 20px;
    min-height: 92px;
    border-bottom: 1px solid #eef2f7;
    color: #263247;
}

.module-row-clean:last-child {
    border-bottom: 0;
}

.module-row-clean:hover {
    background: #f8fbff;
}

.module-title-clean {
    font-weight: 850;
    line-height: 1.35;
}

.module-sub-clean {
    color: #7b8190;
    font-size: .78rem;
    font-weight: 650;
    margin-top: 4px;
}

.module-row-right {
    display: contents;
}

.module-progress-wrap {
    width: 145px;
    margin: 0;
}

.module-progress-meta {
    display: flex;
    justify-content: space-between;
    gap: 8px;
    color: #7b8190;
    font-size: .72rem;
    font-weight: 800;
    margin-bottom: 5px;
}

.module-progress-meta strong {
    color: #034ea2;
}

.module-progress-track {
    height: 7px;
    border-radius: 999px;
    background: #e5eaf2;
    overflow: hidden;
}

.module-progress-fill {
    height: 100%;
    border-radius: 999px;
    background: #034ea2;
}

.module-count-pill {
    height: 30px;
    min-width: 108px;
    display: inline-flex;
    justify-content: center;
    align-items: center;
    gap: 6px;
    border-radius: 999px;
    padding: 6px 12px;
    background: #f8fafc;
    border: 1px solid #e5e7eb;
    color: #526071;
    font-weight: 800;
    font-size: .72rem;
    white-space: nowrap;
}

.module-open-btn,
.module-arrow {
    width: 34px;
    height: 34px;
    border-radius: 50%;
    border: 1px solid #e5e7eb;
    background: #fff;
    color: #034ea2;
    display: grid;
    place-items: center;
    transition: .15s ease;
    text-decoration: none;
}

.module-open-btn:hover,
.module-arrow:hover {
    background: #034ea2;
    color: #fff;
    border-color: #034ea2;
}

.module-empty-box {
    background: #fff;
    border: 1px dashed #cbd5e1;
    border-radius: 18px;
    padding: 42px 18px;
    text-align: center;
    color: #7b8190;
}

.module-empty-box i {
    font-size: 2.2rem;
    display: block;
    color: #cbd5e1;
    margin-bottom: 10px;
}

.exam-list-clean {
    padding: 20px 22px 24px;
}

.exam-row-clean {
    display: grid;
    grid-template-columns: minmax(0, 1fr) 110px 110px 120px;
    align-items: center;
    gap: 14px;
    padding: 17px 18px;
    border-bottom: 1px solid #eef2f7;
    color: #263247;
}

.exam-row-clean:last-child {
    border-bottom: 0;
}

.exam-row-clean:hover {
    background: #f8fbff;
}

.exam-score-clean {
    font-size: 1rem;
    font-weight: 950;
    color: #12386f;
    white-space: nowrap;
}

.exam-date-clean {
    color: #7b8190;
    font-size: .76rem;
    font-weight: 750;
    white-space: nowrap;
}

.exam-badge-clean {
    display: inline-flex;
    justify-content: center;
    align-items: center;
    border-radius: 999px;
    padding: 7px 11px;
    font-size: .74rem;
    font-weight: 900;
    white-space: nowrap;
}

.exam-badge-clean.success { background: #ecfdf3; color: #027a48; }
.exam-badge-clean.primary { background: #eff6ff; color: #034ea2; }
.exam-badge-clean.info { background: #ecfeff; color: #0e7490; }
.exam-badge-clean.warning { background: #fffbeb; color: #b45309; }
.exam-badge-clean.danger { background: #fef2f2; color: #b42318; }

@media (max-width: 1050px) {
    .modules-workspace {
        grid-template-columns: 1fr;
    }

    .modules-side-card {
        position: static;
    }

    .course-side-scroll {
        display: flex;
        gap: 10px;
        overflow-x: auto;
        padding-bottom: 4px;
    }

    .course-side-item {
        min-width: 240px;
        margin-bottom: 0;
    }
}

@media (max-width: 900px) {
    .modules-top-summary {
        grid-template-columns: 1fr;
    }

    .modules-course-header {
        display: block;
    }

    .module-row-clean {
        grid-template-columns: 1fr;
        gap: 10px;
    }

    .module-row-right {
        display: grid;
        grid-template-columns: 130px 1fr 1fr 38px;
        width: 100%;
        gap: 8px;
    }

    .module-count-pill {
        min-width: auto;
    }

    .exam-row-clean {
        grid-template-columns: 1fr;
        gap: 9px;
    }
}
</style>

<div class="student-page-tabs"></div>

<div class="modules-top-summary">
    <div class="modules-summary-card">
        <div class="modules-summary-icon">
            <i class="bi bi-journal-bookmark"></i>
        </div>
        <div class="modules-summary-value"><?= (int)$totalModules ?></div>
        <div class="modules-summary-label">Total Modules</div>
    </div>

    <div class="modules-summary-card">
        <div class="modules-summary-icon">
            <i class="bi bi-play-circle"></i>
        </div>
        <div class="modules-summary-value"><?= (int)$totalContent ?></div>
        <div class="modules-summary-label">Lessons / Content</div>
    </div>

    <div class="modules-summary-card">
        <div class="modules-summary-icon">
            <i class="bi bi-clipboard-check"></i>
        </div>
        <div class="modules-summary-value"><?= (int)$totalAssessments ?></div>
        <div class="modules-summary-label">Assessments</div>
    </div>
</div>

<?php if (!$courseIds): ?>

    <div class="module-empty-box">
        <i class="bi bi-info-circle"></i>
        <h2 class="h5 fw-bold">Course enrollment not found</h2>
        <p class="mb-0">
            This student is not linked with a course or batch. Please check studentss.course_id or enrollments table.
        </p>
    </div>

<?php elseif (!$moduleTable): ?>

    <div class="module-empty-box">
        <i class="bi bi-exclamation-triangle"></i>
        <h2 class="h5 fw-bold">Modules table not found</h2>
        <p class="mb-0">
            Need course_modules or lms_modules table with id and course_id columns.
        </p>
    </div>

<?php elseif (!$modulesByCourse): ?>

    <div class="module-empty-box">
        <i class="bi bi-journal-x"></i>
        <h2 class="h5 fw-bold">No modules added yet</h2>
        <p class="mb-0">
            Modules were not found for this student's course.
        </p>
        <div class="small text-muted mt-3">
            Current module table: <strong><?= h($moduleTable) ?></strong>
        </div>
    </div>

<?php else: ?>

    <div class="modules-workspace">
        <aside class="modules-side-card">
            <div class="modules-side-title">My Courses</div>

            <div class="course-side-scroll">
                <?php $firstCourse = true; ?>
                <?php foreach ($courseIds as $cid): ?>
                    <?php
                    $courseName = $courses[$cid]['course_name'] ?? ('Course #' . $cid);
                    $semGroups = $modulesByCourse[$cid] ?? [];
                    $courseModuleCount = 0;

                    foreach ($semGroups as $mods) {
                        $courseModuleCount += count($mods);
                    }
                    ?>
                    <a href="javascript:void(0)"
                       class="course-side-item <?= $firstCourse ? 'active' : '' ?>"
                       data-course-id="<?= (int)$cid ?>">
                        <div class="course-side-name"><?= h($courseName) ?></div>
                        <div class="course-side-meta">
                            <?= (int)$courseModuleCount ?> module(s)
                        </div>
                    </a>
                    <?php $firstCourse = false; ?>
                <?php endforeach; ?>
            </div>
        </aside>

        <section class="modules-main-card">
            <div class="modules-main-head">
                <h2 class="modules-main-title">Learning Modules</h2>
                <div class="modules-main-sub">
                    Select a module to open materials, lessons, activities and assessment tasks.
                </div>

                <div class="modules-tabs">
                    <button type="button" class="modules-tab-btn active" data-tab-target="learning">
                        Learning Modules
                    </button>
                    <button type="button" class="modules-tab-btn" data-tab-target="exams">
                        Course Exams
                    </button>
                </div>
            </div>

            <div class="modules-tab-panel active" data-tab-panel="learning">
                <?php $firstMainCourse = true; ?>
                <?php foreach ($courseIds as $cid): ?>
                    <?php
                    $courseName = $courses[$cid]['course_name'] ?? ('Course #' . $cid);
                    $courseBatchList = $batches[$cid] ?? [];
                    $semGroups = $modulesByCourse[$cid] ?? [];
                    ?>

                    <div class="modules-course-block <?= $firstMainCourse ? 'show-course' : 'hide-course' ?>"
                         id="course-<?= (int)$cid ?>"
                         data-course-block="<?= (int)$cid ?>">
                        <div class="modules-course-header">
                            <div>
                                <h3 class="course-title-clean"><?= h($courseName) ?></h3>

                                <?php if ($courseBatchList): ?>
                                    <div>
                                        <?php foreach ($courseBatchList as $b): ?>
                                            <span class="batch-pill">
                                                <i class="bi bi-people"></i>
                                                <?= h($b['batch_name']) ?>
                                            </span>
                                        <?php endforeach; ?>
                                    </div>
                                <?php endif; ?>
                            </div>

                            <a href="/elms/student/assessments/assessments.php?course_id=<?= (int)$cid ?>"
                               class="btn btn-sm btn-outline-primary rounded-pill px-3 fw-bold">
                                Assessments
                            </a>
                        </div>

                        <?php if (!$semGroups): ?>
                            <div class="px-4 pb-4">
                                <div class="alert alert-warning mb-0 rounded-4">
                                    No modules found for this course.
                                </div>
                            </div>
                        <?php else: ?>

                            <?php foreach ($semGroups as $semNo => $mods): ?>
                                <div class="semester-block">
                                    <div class="semester-title-row">
                                        <div class="semester-icon">
                                            <i class="bi bi-layers"></i>
                                        </div>

                                        <div>
                                            <div class="semester-title">Semester <?= (int)$semNo ?></div>
                                            <div class="semester-sub"><?= count($mods) ?> module(s)</div>
                                        </div>
                                    </div>

                                    <div class="module-list">
                                        <?php foreach ($mods as $m): ?>
                                            <?php
                                            $mid = (int)$m['id'];
                                            $contentCount = (int)($m['content_count'] ?? 0);
                                            $assessmentCount = (int)($m['assessment_count'] ?? 0);
                                            $viewedCount = (int)($viewedByModule[$mid] ?? 0);
                                            $learnPercent = $contentCount > 0 ? min(100, round(($viewedCount / $contentCount) * 100)) : 0;
                                            ?>

                                            <div class="module-row-clean">
                                                <div>
                                                    <div class="module-title-clean">
                                                        <?= h($m['title']) ?>
                                                    </div>
                                                    <div class="module-sub-clean">
                                                        Module ID <?= (int)$mid ?>
                                                    </div>
                                                </div>

                                                <div class="module-progress-wrap">
                                                    <div class="module-progress-meta">
                                                        <span>Learning Progress</span>
                                                        <strong><?= (int)$learnPercent ?>%</strong>
                                                    </div>
                                                    <div class="module-progress-track">
                                                        <div class="module-progress-fill" style="width: <?= (int)$learnPercent ?>%;"></div>
                                                    </div>
                                                </div>

                                                <span class="module-count-pill">
                                                    <i class="bi bi-play-circle"></i>
                                                    <?= (int)$contentCount ?> Lesson(s)
                                                </span>

                                                <span class="module-count-pill">
                                                    <i class="bi bi-clipboard-check"></i>
                                                    <?= (int)$assessmentCount ?> Task(s)
                                                </span>

                                                <a href="/elms/student/module_content.php?module_id=<?= (int)$mid ?>&course_id=<?= (int)$cid ?>"
                                                   class="module-arrow"
                                                   title="Open Module">
                                                    <i class="bi bi-arrow-right"></i>
                                                </a>
                                            </div>
                                        <?php endforeach; ?>
                                    </div>
                                </div>
                            <?php endforeach; ?>

                        <?php endif; ?>
                    </div>
                    <?php $firstMainCourse = false; ?>
                <?php endforeach; ?>
            </div>

            <div class="modules-tab-panel" data-tab-panel="exams">
                <?php $firstExamCourse = true; ?>
                <?php foreach ($courseIds as $cid): ?>
                    <?php
                    $courseName = $courses[$cid]['course_name'] ?? ('Course #' . $cid);
                    $courseBatchList = $batches[$cid] ?? [];
                    $courseExamRows = $examResultsByCourse[$cid] ?? [];
                    ?>

                    <div class="modules-course-block <?= $firstExamCourse ? 'show-course' : 'hide-course' ?>"
                         data-exam-course-block="<?= (int)$cid ?>">
                        <div class="modules-course-header">
                            <div>
                                <h3 class="course-title-clean"><?= h($courseName) ?></h3>

                                <?php if ($courseBatchList): ?>
                                    <div>
                                        <?php foreach ($courseBatchList as $b): ?>
                                            <span class="batch-pill">
                                                <i class="bi bi-people"></i>
                                                <?= h($b['batch_name']) ?>
                                            </span>
                                        <?php endforeach; ?>
                                    </div>
                                <?php endif; ?>
                            </div>

                            <span class="module-count-pill">
                                <i class="bi bi-award"></i>
                                <?= count($courseExamRows) ?> Final Result(s)
                            </span>
                        </div>

                        <div class="exam-list-clean">
                            <?php if (!$courseExamRows): ?>
                                <div class="module-empty-box">
                                    <i class="bi bi-clipboard-x"></i>
                                    <h2 class="h5 fw-bold">No final exam results yet</h2>
                                    <p class="mb-0">
                                        Final exam last attempt results for this selected course will appear here.
                                    </p>
                                </div>
                            <?php else: ?>
                                <div class="module-list">
                                    <?php foreach ($courseExamRows as $er): ?>
                                        <?php
                                        $dateTaken = trim((string)($er['date_taken'] ?? ''));
                                        $dateText = $dateTaken !== '' ? date('d M Y', strtotime($dateTaken)) : '-';
                                        $scoreText = (int)($er['score'] ?? 0) . '/' . (int)($er['total'] ?? 0);
                                        $percentText = number_format((float)($er['percent'] ?? 0), 0) . '%';
                                        ?>
                                        <div class="exam-row-clean">
                                            <div>
                                                <div class="module-title-clean">
                                                    <?= h($er['display_module_name'] ?? 'Final Exam') ?>
                                                </div>
                                                <div class="module-sub-clean">
                                                    <?= h($er['display_exam_name'] ?? 'Final Exam') ?> . Last Attempt
                                                </div>
                                            </div>

                                            <div class="exam-score-clean">
                                                <?= h($scoreText) ?>
                                                <div class="module-sub-clean"><?= h($percentText) ?></div>
                                            </div>

                                            <div>
                                                <span class="exam-badge-clean <?= h($er['badge_class'] ?? 'secondary') ?>">
                                                    <?= h($er['display_grade'] ?? '-') ?> กค <?= h($er['display_status'] ?? '-') ?>
                                                </span>
                                            </div>

                                            <div class="exam-date-clean">
                                                <i class="bi bi-calendar-check"></i>
                                                <?= h($dateText) ?>
                                            </div>
                                        </div>
                                    <?php endforeach; ?>
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>
                    <?php $firstExamCourse = false; ?>
                <?php endforeach; ?>
            </div>
        </section>
    </div>

<?php endif; ?>

<script>
document.addEventListener('DOMContentLoaded', function () {
    const links = document.querySelectorAll('.course-side-item');
    const blocks = document.querySelectorAll('[data-course-block]');
    const examBlocks = document.querySelectorAll('[data-exam-course-block]');
    const tabButtons = document.querySelectorAll('[data-tab-target]');
    const tabPanels = document.querySelectorAll('[data-tab-panel]');
    const mainTitle = document.querySelector('.modules-main-title');
    const mainSub = document.querySelector('.modules-main-sub');

    function showCourse(courseId) {
        blocks.forEach(function (block) {
            if (block.getAttribute('data-course-block') === courseId) {
                block.classList.remove('hide-course');
                block.classList.add('show-course');
            } else {
                block.classList.remove('show-course');
                block.classList.add('hide-course');
            }
        });

        examBlocks.forEach(function (block) {
            if (block.getAttribute('data-exam-course-block') === courseId) {
                block.classList.remove('hide-course');
                block.classList.add('show-course');
            } else {
                block.classList.remove('show-course');
                block.classList.add('hide-course');
            }
        });
    }

    function showTab(tabName) {
        tabButtons.forEach(function (btn) {
            btn.classList.toggle('active', btn.getAttribute('data-tab-target') === tabName);
        });

        tabPanels.forEach(function (panel) {
            panel.classList.toggle('active', panel.getAttribute('data-tab-panel') === tabName);
        });

        if (mainTitle && mainSub) {
            if (tabName === 'exams') {
                mainTitle.textContent = 'Course Exams';
                mainSub.textContent = 'Final exam results are shown for the selected course. Only the last attempt per unit is displayed.';
            } else {
                mainTitle.textContent = 'Learning Modules';
                mainSub.textContent = 'Select a module to open materials, lessons, activities and assessment tasks.';
            }
        }
    }

    links.forEach(function (link) {
        link.addEventListener('click', function () {
            const courseId = link.getAttribute('data-course-id');

            links.forEach(function (x) {
                x.classList.remove('active');
            });

            link.classList.add('active');
            showCourse(courseId);
        });
    });

    tabButtons.forEach(function (btn) {
        btn.addEventListener('click', function () {
            showTab(btn.getAttribute('data-tab-target'));
        });
    });

    const active = document.querySelector('.course-side-item.active');
    if (active) {
        showCourse(active.getAttribute('data-course-id'));
    }

    showTab('learning');
});
</script>

<?php require_once __DIR__ . '/../includes/student_layout_bottom.php'; ?>