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

$PAGE_TITLE = 'Lessons';
$ACTIVE = 'lessons';

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($v): string {
        return htmlspecialchars((string)$v, 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('first_col')) {
    function first_col(mysqli $db, string $table, array $cols): ?string {
        foreach ($cols as $c) {
            if (col_exists($db, $table, $c)) return $c;
        }
        return null;
    }
}

if (!function_exists('content_href')) {
    function content_href(?string $p): string {
        if (!$p) return '';
        $p = str_replace('\\', '/', trim($p));
        if ($p === '') return '';

        if (preg_match('#^https?://#i', $p)) return $p;
        if (str_starts_with($p, '/elms/')) return $p;
        if (str_starts_with($p, '/uploads/')) return '/elms' . $p;

        if (preg_match('#^(uploads/|content/|assessments/|submissions/|student/|games/)#i', $p)) {
            return '/elms/' . ltrim($p, '/');
        }

        if (str_starts_with($p, '/')) return $p;

        return '/elms/uploads/content/' . ltrim($p, '/');
    }
}

if (!function_exists('icon_for_type')) {
    function icon_for_type(string $type): string {
        return match (strtolower($type)) {
            'pdf'   => 'bi-file-earmark-pdf',
            'video' => 'bi-play-btn',
            'link'  => 'bi-link-45deg',
            'text'  => 'bi-card-text',
            'quiz'  => 'bi-question-circle',
            'game'  => 'bi-controller',
            default => 'bi-file-earmark',
        };
    }
}

if (!function_exists('detect_content_type')) {
    function detect_content_type(array $it): string {
        $type = strtolower(trim((string)($it['content_type'] ?? '')));
        $path = strtolower((string)(($it['url'] ?? '') ?: ($it['file_path'] ?? '')));

        if ($type !== '') return $type;
        if (preg_match('#\.pdf($|\?)#', $path)) return 'pdf';
        if (preg_match('#\.(mp4|webm|ogg|mov)($|\?)#', $path)) return 'video';
        if (str_contains($path, 'game')) return 'game';

        return 'link';
    }
}

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

if ($module_id <= 0) {
    header('Location: /elms/student/modules.php');
    exit;
}

/* 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'];

$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;
}

/* Student Courses */
$courseIds = [];

if (table_exists($mysqli, 'enrollments') && table_exists($mysqli, 'batches')) {
    $sql = "
        SELECT DISTINCT b.course_id
        FROM enrollments e
        INNER JOIN batches b ON b.id = e.batch_id
        WHERE e.student_id = ?
          AND b.course_id IS NOT NULL
    ";

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

        while ($r = $rs->fetch_assoc()) {
            $cid = (int)($r['course_id'] ?? 0);
            if ($cid > 0) $courseIds[$cid] = $cid;
        }

        $st->close();
    }
}

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

/* 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;

    $chk = $mysqli->prepare("SELECT id, course_id FROM `$tbl` WHERE id=? LIMIT 1");
    if ($chk) {
        $chk->bind_param('i', $module_id);
        $chk->execute();
        $found = $chk->get_result()->fetch_assoc();
        $chk->close();

        if ($found) {
            $moduleTable = $tbl;
            if ($course_id <= 0) {
                $course_id = (int)$found['course_id'];
            }
            break;
        }
    }
}

function render_lesson_error(string $title, string $message, string $icon = 'bi-exclamation-triangle', string $color = 'text-danger'): void {
    require __DIR__ . '/../includes/student_layout_top.php';
    ?>
    <div class="lux-empty">
        <i class="bi <?= h($icon) ?> fs-1 <?= h($color) ?> d-block mb-3"></i>
        <h2 class="h5 fw-bold"><?= h($title) ?></h2>
        <p class="text-muted mb-0"><?= h($message) ?></p>
        <a href="/elms/student/modules.php" class="btn btn-primary rounded-pill mt-3 px-4">
            Back to Modules
        </a>
    </div>

    <style>
        .lux-empty {
            background: #fff;
            border: 1px solid #e5e7eb;
            border-radius: 24px;
            padding: 44px 22px;
            text-align: center;
            box-shadow: 0 14px 34px rgba(15, 23, 42, .055);
        }
    </style>
    <?php
    require __DIR__ . '/../includes/student_layout_bottom.php';
    exit;
}

if (!$moduleTable) {
    render_lesson_error('Module not found', 'This module does not exist.');
}

/* Security */
if ($course_id > 0 && $courseIds && !isset($courseIds[$course_id])) {
    render_lesson_error('Access denied', 'This module is not assigned to your course.', 'bi-lock', 'text-warning');
}

$titleCol = col_exists($mysqli, $moduleTable, 'title')
    ? 'title'
    : (col_exists($mysqli, $moduleTable, 'name') ? 'name' : 'id');

/* Module Details */
$sql = "
    SELECT 
        m.id,
        m.course_id,
        m.`$titleCol` AS title,
        c.course_name
    FROM `$moduleTable` m
    LEFT JOIN courses c ON c.id = m.course_id
    WHERE m.id = ?
    LIMIT 1
";

$st = $mysqli->prepare($sql);
$st->bind_param('i', $module_id);
$st->execute();
$module = $st->get_result()->fetch_assoc();
$st->close();

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

$course_id = (int)$module['course_id'];

/* Content Table */
$contentTable = null;

foreach (['lms_content', 'module_content', 'contents', 'lms_contents', 'lms_module_contents', 'module_contents', 'lms_content_items'] as $tbl) {
    if (!table_exists($mysqli, $tbl)) {
        continue;
    }

    if ($tbl === 'lms_content_items') {
        if (col_exists($mysqli, $tbl, 'unit_id')) {
            $contentTable = $tbl;
            break;
        }
    } else {
        if (col_exists($mysqli, $tbl, 'module_id')) {
            $contentTable = $tbl;
            break;
        }
    }
}

/* Fetch Content */
$items = [];

if ($contentTable) {
    $cols = [
        'id'           => col_exists($mysqli, $contentTable, 'id') ? 'id' : null,
        'title'        => first_col($mysqli, $contentTable, ['title', 'name', 'content_title', 'file_name']),
        'type'         => first_col($mysqli, $contentTable, ['content_type', 'type', 'material_type']),
        'description'  => first_col($mysqli, $contentTable, ['description', 'body']),
        'file_path'    => first_col($mysqli, $contentTable, ['file_path', 'file', 'path']),
        'url'          => first_col($mysqli, $contentTable, ['url', 'link', 'source_path_or_url', 'file_url']),
        'sort_order'   => first_col($mysqli, $contentTable, ['sort_order', 'ordering', 'display_order']),
        'active'       => first_col($mysqli, $contentTable, ['active', 'is_active', 'status']),
        'require_paid' => col_exists($mysqli, $contentTable, 'require_paid') ? 'require_paid' : null,
        'session_id'   => col_exists($mysqli, $contentTable, 'session_id') ? 'session_id' : null,
    ];

    $select = [];
    $select[] = $cols['id'] ? "c.`{$cols['id']}` AS id" : "0 AS id";
    $select[] = $cols['title'] ? "c.`{$cols['title']}` AS title" : "CONCAT('Content #', c.id) AS title";
    $select[] = $cols['type'] ? "c.`{$cols['type']}` AS content_type" : "'' AS content_type";
    $select[] = $cols['description'] ? "c.`{$cols['description']}` AS description" : "'' AS description";
    $select[] = $cols['file_path'] ? "c.`{$cols['file_path']}` AS file_path" : "'' AS file_path";
    $select[] = $cols['url'] ? "c.`{$cols['url']}` AS url" : "'' AS url";
    $select[] = $cols['require_paid'] ? "c.`{$cols['require_paid']}` AS require_paid" : "0 AS require_paid";
    $select[] = $cols['session_id'] ? "c.`{$cols['session_id']}` AS session_id" : "0 AS session_id";

    $moduleKey = ($contentTable === 'lms_content_items') ? 'unit_id' : 'module_id';
$whereParts = ["c.`{$moduleKey}` = ?"];
    $bindTypes = "i";
$bindValues = [$module_id];

    if ($cols['active']) {
        $whereParts[] = "(c.`{$cols['active']}` IS NULL OR c.`{$cols['active']}` IN (1,'1','active','Active','ACTIVE','yes','YES','published','Published'))";
    }

    $joinSession = "";
    $sessionSelect = ",
        'Session 01' AS session_title,
        '' AS session_description,
        0 AS session_sort_order
    ";

    if (
    $cols['session_id'] &&
    table_exists($mysqli, 'lms_content_sessions') &&
    col_exists($mysqli, 'lms_content_sessions', 'id')
) {
    $joinSession = "
    LEFT JOIN lms_content_sessions s
        ON s.id = c.`{$cols['session_id']}`
       AND s.`module_id` = c.`module_id`
";

    $sessionSelect = ",
        COALESCE(NULLIF(s.title,''), 'Session 01') AS session_title,
        COALESCE(s.description,'') AS session_description,
        COALESCE(s.sort_order,0) AS session_sort_order
    ";
}

    $orderBy = $cols['sort_order']
        ? "session_sort_order ASC, c.`{$cols['sort_order']}` ASC, c.`id` ASC"
        : "session_sort_order ASC, c.`id` ASC";

    $sql = "
        SELECT " . implode(", ", $select) . $sessionSelect . "
        FROM `$contentTable` c
        $joinSession
        WHERE " . implode(" AND ", $whereParts) . "
        ORDER BY $orderBy
    ";

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

    if (!$st) {
        die('SQL Prepare failed: ' . h($mysqli->error) . '<br><pre>' . h($sql) . '</pre>');
    }

    $st->bind_param($bindTypes, ...$bindValues);
    $st->execute();
    $rs = $st->get_result();

    while ($r = $rs->fetch_assoc()) {
        $r['content_type'] = detect_content_type($r);
        $r['open_url'] = content_href(($r['url'] ?? '') ?: ($r['file_path'] ?? ''));

        if ($r['content_type'] === 'quiz' && !$r['open_url']) {
            $r['open_url'] = "/elms/student/assessments/assessments.php?module_id={$module_id}&course_id={$course_id}";
        }

        if ($r['content_type'] === 'game' && !$r['open_url']) {
            $r['open_url'] = "/elms/student/games/games.php?module_id={$module_id}&course_id={$course_id}";
        }

        $r['session_title'] = trim((string)($r['session_title'] ?? ''));
        if ($r['session_title'] === '') {
            $r['session_title'] = 'Session 01';
        }

        $items[] = $r;
    }

    $st->close();
}

$selected_id = (int)($_GET['content_id'] ?? 0);
$selected = null;

if ($items) {
    foreach ($items as $it) {
        if ((int)$it['id'] === $selected_id) {
            $selected = $it;
            break;
        }
    }

    if (!$selected) {
        $selected = $items[0];
    }
}

if ($selected && table_exists($mysqli, 'lms_student_content_progress')) {
    $contentProgressId = (int)($selected['id'] ?? 0);

    if ($contentProgressId > 0) {
        $stmt = $mysqli->prepare("
            INSERT INTO lms_student_content_progress (student_id, module_id, content_id)
            VALUES (?, ?, ?)
            ON DUPLICATE KEY UPDATE viewed_at = NOW()
        ");

        if ($stmt) {
            $stmt->bind_param('iii', $student_id, $module_id, $contentProgressId);
            $stmt->execute();
            $stmt->close();
        }
    }
}

$groupedItems = [];
foreach ($items as $it) {
    $title = trim((string)($it['session_title'] ?? 'Session 01'));
    $desc  = trim((string)($it['session_description'] ?? ''));

    if ($title === '') $title = 'Session 01';

    if (!isset($groupedItems[$title])) {
        $groupedItems[$title] = [
            'description' => $desc,
            'items' => [],
        ];
    }

    $groupedItems[$title]['items'][] = $it;
}

$assessments = [];
$totalAssessments = 0;
$pendingCount = 0;
$submittedCount = 0;
$correctionCount = 0;
$reviewCount = 0;
$releasedCount = 0;

if (table_exists($mysqli, 'lms_assessments') && table_exists($mysqli, 'lms_submissions')) {
    $sqlA = "
        SELECT DISTINCT
            a.id,
            a.title,
            COALESCE(a.description,'') AS description,
            COALESCE(a.description,'') AS brief_text,
            COALESCE(aa.file_path,'') AS brief_file,
            COALESCE(a.type,'assessment') AS type,
            a.course_id,
            a.module_id,
            a.due_at,
            a.release_at,
            a.max_score,
            s.id AS submission_id,
            s.submitted_at,
            s.workflow_status,
            s.final_score,
            s.provisional_score,
            s.score,
            s.released_at
        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 = ?
        LEFT JOIN lms_submissions s
            ON s.assessment_id = a.id
           AND s.student_id = ?
        LEFT JOIN lms_assessment_attachments aa
            ON aa.assessment_id = a.id
        WHERE a.active = 1
          AND a.course_id = ?
          AND a.module_id = ?
          AND (ast.student_id IS NOT NULL OR e.student_id IS NOT NULL)
        ORDER BY a.id DESC
    ";

    $stA = $mysqli->prepare($sqlA);
    if ($stA) {
        $stA->bind_param('iiiii', $student_id, $student_id, $student_id, $course_id, $module_id);
        $stA->execute();
        $rsA = $stA->get_result();

        while ($a = $rsA->fetch_assoc()) {
            $workflow = strtolower(trim((string)($a['workflow_status'] ?? '')));
            $hasSubmission = !empty($a['submission_id']);

            if (!$hasSubmission || $workflow === '') {
                $a['display_status'] = 'Pending';
                $a['status_class'] = 'status-warning';
                $a['status_icon'] = 'bi-clock';
                $pendingCount++;
            } elseif ($workflow === 'submitted') {
                $a['display_status'] = 'Submitted';
                $a['status_class'] = 'status-info';
                $a['status_icon'] = 'bi-cloud-check';
                $submittedCount++;
            } elseif ($workflow === 'needs_correction') {
                $a['display_status'] = 'Correction';
                $a['status_class'] = 'status-danger';
                $a['status_icon'] = 'bi-arrow-clockwise';
                $correctionCount++;
            } elseif (in_array($workflow, ['under_review','coord_approved','admin_review','approved'], true)) {
                $a['display_status'] = 'Review';
                $a['status_class'] = 'status-primary';
                $a['status_icon'] = 'bi-hourglass-split';
                $reviewCount++;
            } elseif ($workflow === 'released') {
                $a['display_status'] = 'Released';
                $a['status_class'] = 'status-success';
                $a['status_icon'] = 'bi-award';
                $releasedCount++;
            } else {
                $a['display_status'] = ucfirst($workflow);
                $a['status_class'] = 'status-muted';
                $a['status_icon'] = 'bi-info-circle';
            }

            $assessments[] = $a;
        }

        $stA->close();
    }
}

$totalAssessments = count($assessments);

$assessmentUrl = "/elms/student/assessments/assessments.php?module_id={$module_id}&course_id={$course_id}";


foreach ($items as &$it) {
    $it['session_title'] = trim((string)($it['session_title'] ?? 'Session 01'));
    if ($it['session_title'] === '') {
        $it['session_title'] = 'Session 01';
    }

    $type = strtolower((string)($it['content_type'] ?? 'link'));
    $path = strtolower((string)(($it['url'] ?? '') ?: ($it['file_path'] ?? '')));

    if ($type === '' || $type === 'link') {
        if (preg_match('#\.pdf($|\?)#', $path)) $type = 'pdf';
        elseif (preg_match('#\.(mp4|webm|ogg|mov)($|\?)#', $path)) $type = 'video';
        elseif (str_contains($path, 'game')) $type = 'game';
    }

    $it['content_type'] = $type ?: 'link';
    $it['open_url'] = content_href(($it['url'] ?? '') ?: ($it['file_path'] ?? ''));

    if ($it['content_type'] === 'quiz' && !$it['open_url']) {
        $it['open_url'] = "/elms/student/assessments/assessments.php?module_id={$module_id}&course_id={$course_id}";
    }

    if ($it['content_type'] === 'game' && !$it['open_url']) {
        $it['open_url'] = "/elms/student/games/games.php?module_id={$module_id}&course_id={$course_id}";
    }
}
unset($it);

$groupedItems = [];
foreach ($items as $it) {
    $title = trim((string)($it['session_title'] ?? 'Session 01'));
    $desc  = trim((string)($it['session_description'] ?? ''));

    if ($title === '') $title = 'Session 01';

    if (!isset($groupedItems[$title])) {
        $groupedItems[$title] = [
            'description' => $desc,
            'items' => [],
        ];
    }

    $groupedItems[$title]['items'][] = $it;
}

$assessmentUrl = "/elms/student/assessments/assessments.php?module_id={$module_id}&course_id={$course_id}";

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

<style>
.student-page-tabs {
    display: flex;
    gap: 26px;
    border-bottom: 1px solid #e5e7eb;
    margin-bottom: 18px;
}

.student-page-tabs button {
    border: 0;
    background: transparent;
    padding: 12px 0;
    font-weight: 900;
    font-size: .82rem;
    color: #6b7280;
}

.student-page-tabs button.active {
    color: #034ea2;
    border-bottom: 2px solid #034ea2;
}

.module-shell {
    display: grid;
    grid-template-columns: 250px minmax(0, 1fr);
    gap: 20px;
    align-items: start;
}

.module-shell.assessment-mode {
    grid-template-columns: 1fr;
}

.module-shell.assessment-mode .module-side-panel {
    display: none;
}

.module-side-panel,
.module-content-panel {
    background: #fff;
    border: 1px solid #e5e7eb;
    border-radius: 16px;
    box-shadow: 0 8px 22px rgba(15,23,42,.045);
}

.module-side-panel {
    padding: 14px;
    position: sticky;
    top: 98px;
}

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

.module-session-only {
    width: 100%;
    display: block;
    border: 1px solid #e5e7eb;
    background: #fff;
    color: #111827;
    border-radius: 12px;
    padding: 12px;
    margin-bottom: 10px;
    text-align: left;
    transition: .16s ease;
    min-height: 78px;
}

.module-session-only:hover,
.module-session-only.active {
    border-color: #034ea2;
    background: #f8fbff;
}

.module-session-only .session-name {
    display: inline-block;
    background: #034ea2;
    color: #fff;
    border-radius: 7px;
    padding: 5px 12px;
    font-size: .82rem;
    font-weight: 900;
    margin-bottom: 9px;
}

.module-session-only .session-desc {
    display: block;
    color: #1f2937;
    font-size: .82rem;
    font-weight: 600;
    line-height: 1.35;
    white-space: normal;
}

.module-content-panel {
    overflow: hidden;
}

.module-hero {
    padding: 24px 24px 20px;
    background: linear-gradient(180deg, #ffffff, #fafbff);
    border-bottom: 1px solid #e5e7eb;
}

.module-kicker {
    display: inline-flex;
    align-items: center;
    gap: 6px;
    background: #eff6ff;
    color: #034ea2;
    border-radius: 999px;
    padding: 6px 10px;
    font-size: .75rem;
    font-weight: 850;
    margin-bottom: 12px;
}

.module-title-v2 {
    color: #12386f;
    font-size: 1.55rem;
    font-weight: 950;
    margin: 0;
    line-height: 1.2;
}

.module-course-v2 {
    display: none !important;
}

.module-main-body {
    padding: 20px;
}

.material-list-body {
    display: grid;
    grid-template-columns: repeat(2, minmax(0, 1fr));
    gap: 12px;
}

.material-item {
    display: flex;
    align-items: center;
    gap: 12px;
    padding: 14px;
    border: 1px solid #eef2f7;
    border-radius: 15px;
    color: #263247;
    background: #fff;
    transition: .16s ease;
    width: 100%;
    text-align: left;
}

.material-item:hover {
    border-color: #034ea2;
    background: #f8fbff;
}

.material-icon {
    width: 40px;
    height: 40px;
    border-radius: 13px;
    background: #eff6ff;
    color: #034ea2;
    display: grid;
    place-items: center;
    flex: 0 0 auto;
    font-size: 1.1rem;
}

.material-title {
    font-weight: 850;
    line-height: 1.35;
    font-size: .9rem;
}

.material-meta {
    color: #7b8190;
    font-size: .75rem;
    font-weight: 700;
    margin-top: 4px;
}

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

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

.assessment-frame {
    width: 100%;
    height: 78vh;
    border: 0;
    border-radius: 14px;
    background: #fff;
}

::-webkit-scrollbar-button {
    display: none;
    width: 0;
    height: 0;
}

@media (max-width: 1200px) {
    .module-shell,
    .material-list-body {
        grid-template-columns: 1fr;
    }

    .module-side-panel {
        position: static;
    }
}
/* remove session name under material cards */
.material-meta {
    display: none !important;
}

/* reduce material box size */
.material-list-body {
    gap: 9px !important;
}

.material-item {
    padding: 10px 12px !important;
    min-height: 56px !important;
    border-radius: 12px !important;
}

.material-icon {
    width: 34px !important;
    height: 34px !important;
    border-radius: 10px !important;
    font-size: .95rem !important;
}

.material-title {
    font-size: .84rem !important;
    line-height: 1.2 !important;
}

.module-main-body {
    padding: 14px 16px !important;
}
.module-tab-link {
    border: 0;
    background: transparent;
    padding: 12px 0;
    font-weight: 900;
    font-size: .82rem;
    color: #6b7280;
    text-decoration: none;
}

.module-tab-link:hover {
    color: #034ea2;
}
.assessment-list-card {
    background: #fff;
    border: 1px solid #e5e7eb;
    border-radius: 16px;
    overflow: hidden;
}

.assessment-list-head {
    padding: 16px 18px;
    border-bottom: 1px solid #e5e7eb;
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 12px;
}

.assessment-list-head h3 {
    margin: 0;
    color: #034ea2;
    font-size: 1rem;
    font-weight: 950;
}

.assessment-list-head p {
    margin: 4px 0 0;
    color: #64748b;
    font-size: .82rem;
    font-weight: 650;
}

.assessment-list-head span {
    background: #f8fafc;
    border-radius: 999px;
    padding: 6px 10px;
    font-size: .75rem;
    font-weight: 900;
}

.assessment-row {
    display: grid;
    grid-template-columns: minmax(0, 1fr) 180px 110px 42px;
    gap: 16px;
    align-items: center;
    padding: 16px 18px;
    border-bottom: 1px solid #eef2f7;
}

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

.assessment-row h4 {
    margin: 0;
    font-size: .92rem;
    font-weight: 950;
    color: #111827;
}

.assessment-row p {
    margin: 5px 0 0;
    color: #64748b;
    font-size: .78rem;
    font-weight: 650;
}

.assessment-date strong {
    display: block;
    font-size: .72rem;
    text-transform: uppercase;
    color: #64748b;
    font-weight: 900;
}

.assessment-date span {
    display: block;
    margin-top: 4px;
    color: #111827;
    font-size: .8rem;
    font-weight: 850;
}

.assessment-status {
    background: #fff7ed;
    color: #c2410c;
    border-radius: 0;
    padding: 8px 14px;
    font-size: .78rem;
    font-weight: 900;
    text-align: center;
}

.assessment-open {
    width: 34px;
    height: 34px;
    border: 1px solid #dbeafe;
    color: #034ea2;
    border-radius: 50%;
    display: grid;
    place-items: center;
    text-decoration: none;
}

@media (max-width: 900px) {
    .assessment-row {
        grid-template-columns: 1fr;
    }
}
.assessment-kpi-grid {
    display: grid !important;
    grid-template-columns: repeat(6, minmax(0, 1fr)) !important;
    gap: 12px !important;
    margin: 0 0 16px !important;
}

.assessment-kpi {
    background: #fff !important;
    border: 1px solid #e5e7eb !important;
    border-radius: 15px !important;
    padding: 16px !important;
    min-height: 92px !important;
    display: block !important;
}

.assessment-kpi i {
    width: 32px !important;
    height: 32px !important;
    border-radius: 10px !important;
    background: #eff6ff !important;
    color: #034ea2 !important;
    display: grid !important;
    place-items: center !important;
    margin-bottom: 10px !important;
}

.assessment-kpi strong {
    display: block !important;
    font-size: 1.35rem !important;
    color: #020617 !important;
    font-weight: 950 !important;
    line-height: 1 !important;
}

.assessment-kpi span {
    display: block !important;
    color: #64748b !important;
    font-size: .75rem !important;
    font-weight: 800 !important;
    margin-top: 7px !important;
}

@media (max-width: 1100px) {
    .assessment-kpi-grid {
        grid-template-columns: repeat(3, minmax(0, 1fr)) !important;
    }
}
.assessment-list-card {
    background: #fff;
    border: 1px solid #e5e7eb;
    border-radius: 16px;
    overflow: hidden;
}

.assessment-list-head {
    padding: 16px 18px;
    border-bottom: 1px solid #e5e7eb;
    display: flex;
    align-items: center;
    justify-content: space-between;
}

.assessment-list-head h3 {
    margin: 0;
    color: #034ea2;
    font-size: 1rem;
    font-weight: 950;
}

.assessment-list-head p {
    margin: 4px 0 0;
    color: #64748b;
    font-size: .82rem;
    font-weight: 650;
}

.assessment-list-head span {
    background: #f8fafc;
    border-radius: 999px;
    padding: 6px 10px;
    font-size: .75rem;
    font-weight: 900;
}

.assessment-row {
    display: grid;
    grid-template-columns: minmax(0, 1fr) 130px 150px 150px 110px 38px;
    gap: 14px;
    align-items: center;
    padding: 16px 18px;
    border-bottom: 1px solid #eef2f7;
}

.assessment-row h4 {
    margin: 0;
    font-size: .9rem;
    font-weight: 950;
    color: #111827;
}

.assessment-row p {
    margin: 5px 0 0;
    color: #64748b;
    font-size: .76rem;
    font-weight: 650;
}

.assessment-date strong {
    display: block;
    font-size: .7rem;
    text-transform: uppercase;
    color: #64748b;
    font-weight: 900;
}

.assessment-date span {
    display: block;
    margin-top: 4px;
    color: #111827;
    font-size: .78rem;
    font-weight: 850;
}

.assessment-status {
    background: #fff7ed;
    color: #c2410c;
    padding: 8px 12px;
    font-size: .76rem;
    font-weight: 900;
    text-align: center;
}

.assessment-open {
    width: 34px;
    height: 34px;
    border: 1px solid #dbeafe;
    color: #034ea2;
    border-radius: 50%;
    display: grid;
    place-items: center;
    text-decoration: none;
}

@media (max-width: 1000px) {
    .assessment-kpi-grid,
    .assessment-row {
        grid-template-columns: 1fr;
    }
}
.assessment-open {
    background: #fff;
    border: 1px solid #dbeafe;
    cursor: pointer;
}
.assessment-status.status-warning {
    background: #fff7ed;
    color: #c2410c;
}

.assessment-status.status-info,
.assessment-status.status-primary {
    background: #dbeafe;
    color: #1d4ed8;
}

.assessment-status.status-danger {
    background: #fee2e2;
    color: #dc2626;
}

.assessment-status.status-success {
    background: #dcfce7;
    color: #15803d;
}

.assessment-status.status-muted {
    background: #f1f5f9;
    color: #64748b;
}
.module-shell.assessment-mode .materials-empty-box {
    display: none !important;
}

</style>

<div class="student-page-tabs">
    <button type="button" class="active module-tab-btn" data-tab="all">All Materials</button>
    <button type="button" class="module-tab-btn" data-tab="video">Video Materials</button>
    <button type="button" class="module-tab-btn" data-tab="assessments">Assessments</button>
</div>

<div class="module-shell" id="moduleShell">
    <aside class="module-side-panel">
        <div class="module-side-title">All Materials</div>

        <?php if ($groupedItems): ?>
    <?php $firstSession = array_key_first($groupedItems); ?>

    <?php foreach ($groupedItems as $sessionTitle => $sessionData): ?>
        <button type="button"
                class="module-session-only <?= $sessionTitle === $firstSession ? 'active' : '' ?>"
                data-session="<?= h($sessionTitle) ?>">
            <span class="session-name"><?= h($sessionTitle) ?></span>

            <?php if (trim((string)$sessionData['description']) !== ''): ?>
                <span class="session-desc"><?= h($sessionData['description']) ?></span>
            <?php endif; ?>
        </button>
    <?php endforeach; ?>
<?php else: ?>
            <div class="module-empty-v2 py-4">
                <i class="bi bi-journal-x"></i>
                No materials
            </div>
        <?php endif; ?>
    </aside>

    <section class="module-content-panel">
        <div class="module-hero">
            <div class="module-kicker">
                <i class="bi bi-book"></i>
                <?= h($module['course_name'] ?? ('Course #' . $course_id)) ?>
            </div>

            <h2 class="module-title-v2"><?= h($module['title'] ?? 'Module') ?></h2>

            
        </div>

        <div class="module-main-body">
            <?php if (!$contentTable): ?>

                <div class="module-empty-v2">
                    <i class="bi bi-folder-x"></i>
                    <h3 class="h5 fw-bold">Content table not found</h3>
                    <p class="mb-0">Need lms_content table with module_id column.</p>
                </div>

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

    <div class="module-empty-v2 materials-empty-box">
        <i class="bi bi-journal-x"></i>
        <h3 class="h5 fw-bold">No materials added yet</h3>
        <p class="mb-0">Admin has not added content for this module yet.</p>
    </div>

            <?php else: ?>

                <div class="module-tab-panel" data-tab-panel="all">
                    <div class="material-list-body">
                        <?php foreach ($items as $it): ?>
    <?php
    $type = strtolower((string)($it['content_type'] ?? 'link'));
    $session = (string)($it['session_title'] ?? 'Session 01');
    ?>
    <button type="button"
            class="material-item session-material"
            data-session="<?= h($session) ?>"
            data-type="<?= h($type) ?>"
            data-elms-open
            data-url="<?= h($it['open_url'] ?? '') ?>"
            data-title="<?= h($it['title'] ?? 'Material') ?>">
        <div class="material-icon">
            <i class="bi <?= h(icon_for_type($type)) ?>"></i>
        </div>

        <div>
            <div class="material-title"><?= h($it['title'] ?? 'Untitled') ?></div>
            <div class="material-meta"><?= h($session) ?></div>
        </div>
    </button>
<?php endforeach; ?>
                    </div>
                </div>

                <div class="module-tab-panel d-none" data-tab-panel="video">
                    <?php
                    $videoItems = array_values(array_filter($items, fn($it) => strtolower((string)($it['content_type'] ?? '')) === 'video'));
                    ?>

                    <?php if ($videoItems): ?>
                        <div class="material-list-body">
                            <?php foreach ($videoItems as $it): ?>
    <?php
    $type = strtolower((string)($it['content_type'] ?? 'video'));
    $session = (string)($it['session_title'] ?? 'Session 01');
    ?>
    <button type="button"
            class="material-item session-material"
            data-session="<?= h($session) ?>"
            data-type="<?= h($type) ?>"
            data-elms-open
            data-url="<?= h($it['open_url'] ?? '') ?>"
            data-title="<?= h($it['title'] ?? 'Video') ?>">
        <div class="material-icon">
            <i class="bi bi-play-btn"></i>
        </div>

        <div>
            <div class="material-title"><?= h($it['title'] ?? 'Video') ?></div>
        </div>
    </button>

                            <?php endforeach; ?>
                        </div>
                    <?php else: ?>
                        <div class="module-empty-v2">
                            <i class="bi bi-play-btn"></i>
                            No video materials found for this module.
                        </div>
                    <?php endif; ?>
                </div>
            <?php endif; ?>
        </div>
    </section>
</div>
<div class="module-tab-panel d-none" data-tab-panel="assessments">
    <div class="assessment-kpi-grid">
        <div class="assessment-kpi">
            <i class="bi bi-clipboard"></i>
            <strong><?= (int)$totalAssessments ?></strong>
            <span>Total</span>
        </div>

        <div class="assessment-kpi">
            <i class="bi bi-clock"></i>
            <strong><?= (int)$pendingCount ?></strong>
            <span>Pending</span>
        </div>

        <div class="assessment-kpi">
            <i class="bi bi-cloud-check"></i>
            <strong><?= (int)$submittedCount ?></strong>
            <span>Submitted</span>
        </div>

        <div class="assessment-kpi">
            <i class="bi bi-arrow-clockwise"></i>
            <strong><?= (int)$correctionCount ?></strong>
            <span>Correction</span>
        </div>

        <div class="assessment-kpi">
            <i class="bi bi-hourglass-split"></i>
            <strong><?= (int)$reviewCount ?></strong>
            <span>Review</span>
        </div>

        <div class="assessment-kpi">
            <i class="bi bi-award"></i>
            <strong><?= (int)$releasedCount ?></strong>
            <span>Released</span>
        </div>
    </div>

    <?php if ($assessments): ?>
        <div class="assessment-list-card mt-3">
            <div class="assessment-list-head">
                <div>
                    <h3>Assessment List</h3>
                    <p>Submit work, track correction requests, review status, and released marks.</p>
                </div>
                <span><?= count($assessments) ?> record(s)</span>
            </div>

            <?php foreach ($assessments as $a): ?>
                <div class="assessment-row">
                    <div>
                        <h4><?= h($a['title'] ?? 'Assessment') ?></h4>
                        <p>Assessment . <?= h($module['course_name'] ?? 'Course') ?></p>
                    </div>
                    
                    
                    <div>
    <?php if (!empty($a['brief_file'])): ?>
        <a href="<?= h(content_href($a['brief_file'])) ?>"
           target="_blank"
           class="btn btn-sm btn-outline-primary rounded-pill fw-bold">
            <i class="bi bi-paperclip me-1"></i>
            Brief
        </a>
    <?php elseif (!empty($a['brief_text'])): ?>
        <button type="button"
                class="btn btn-sm btn-outline-primary rounded-pill fw-bold"
                onclick="alert(<?= json_encode($a['brief_text']) ?>)">
            <i class="bi bi-card-text me-1"></i>
            Brief
        </button>
    <?php else: ?>
        <span class="text-muted small">No Brief</span>
    <?php endif; ?>
</div>
                    
                    

                    <div class="assessment-date">
    <strong>Submission Date</strong>
    <span><?= !empty($a['submitted_at']) ? h($a['submitted_at']) : 'Not set' ?></span>
</div>

<div class="assessment-date">
    <strong>Marks Release Date</strong>
    <span><?= !empty($a['released_at']) ? h($a['released_at']) : (!empty($a['release_at']) ? h($a['release_at']) : 'Not set') ?></span>
</div>

<span class="assessment-status <?= h($a['status_class'] ?? 'status-warning') ?>">
    <i class="bi <?= h($a['status_icon'] ?? 'bi-clock') ?> me-1"></i>
    <?= h($a['display_status'] ?? 'Pending') ?>
</span>

<a class="assessment-open"
   href="/elms/student/assessments/submit.php?assessment_id=<?= (int)$a['id'] ?>&module_id=<?= (int)$module_id ?>&course_id=<?= (int)$course_id ?>">
    <i class="bi bi-arrow-right"></i>
</a>
                </div>
            <?php endforeach; ?>
        </div>
    <?php else: ?>
        <div class="module-empty-v2">
            <i class="bi bi-clipboard-x"></i>
            <h3 class="h5 fw-bold">No assessments available</h3>
            <p class="mb-0">There are no active assessments assigned to this module yet.</p>
        </div>
    <?php endif; ?>
</div>
<script>
document.addEventListener('DOMContentLoaded', function () {
    const shell = document.getElementById('moduleShell');
    const tabButtons = document.querySelectorAll('.module-tab-btn');
    const panels = document.querySelectorAll('.module-tab-panel');
    const sessionButtons = document.querySelectorAll('.module-session-only');
    ;

    let currentSession = sessionButtons.length ? sessionButtons[0].getAttribute('data-session') : '';

    function filterMaterials(tab) {
    document.querySelectorAll('.session-material').forEach(function (item) {
        const session = item.getAttribute('data-session') || '';
        const type = item.getAttribute('data-type') || '';
        const panel = item.closest('.module-tab-panel');
        const panelTab = panel ? panel.getAttribute('data-tab-panel') : '';

        let show = session === currentSession;

        if (tab === 'video') {
            show = show && type === 'video' && panelTab === 'video';
        } else if (tab === 'all') {
            show = show && panelTab === 'all';
        }

        item.style.display = show ? '' : 'none';
    });
}

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

        panels.forEach(function (panel) {
            panel.classList.toggle('d-none', panel.getAttribute('data-tab-panel') !== tab);
        });

        if (shell) {
            shell.classList.toggle('assessment-mode', tab === 'assessments');
        }

        filterMaterials(tab);
    }

    tabButtons.forEach(function (btn) {
        btn.addEventListener('click', function () {
            openTab(btn.getAttribute('data-tab') || 'all');
        });
    });

    sessionButtons.forEach(function (btn) {
        btn.addEventListener('click', function () {
            currentSession = btn.getAttribute('data-session') || '';

            sessionButtons.forEach(function (b) {
                b.classList.toggle('active', b === btn);
            });

            const activeTab = document.querySelector('.module-tab-btn.active');
            openTab(activeTab ? activeTab.getAttribute('data-tab') : 'all');
        });
    });

    document.addEventListener('click', function (e) {
        const opener = e.target.closest('[data-elms-open]');
        if (!opener) return;

        const url = opener.getAttribute('data-url') || '';
        const title = opener.getAttribute('data-title') || 'Material';

        if (!url) return;

        const modalEl = document.getElementById('gameOpenModal');
        const frame = document.getElementById('gameOpenFrame');
        const modalTitle = document.getElementById('gameOpenModalTitle');

        if (!modalEl || !frame || typeof bootstrap === 'undefined') {
            window.open(url, '_blank');
            return;
        }

        if (modalTitle) modalTitle.textContent = title;
        frame.src = url;

        bootstrap.Modal.getOrCreateInstance(modalEl).show();

        modalEl.addEventListener('hidden.bs.modal', function () {
            frame.src = 'about:blank';
        }, { once: true });
    });

    openTab('all');
});
</script>
<?php require_once __DIR__ . '/../includes/student_layout_bottom.php'; ?>