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

$PAGE_TITLE = 'Assessments';
$ACTIVE = 'assessments';

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

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

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

$db->set_charset('utf8mb4');

/* ---------------- Helpers ---------------- */

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

function sas_table_exists(mysqli $db, string $table): bool {
    $safe = $db->real_escape_string($table);
    $res = $db->query("SHOW TABLES LIKE '{$safe}'");
    $ok = $res && $res->num_rows > 0;
    if ($res) $res->free();
    return $ok;
}

function sas_col_exists(mysqli $db, string $table, string $col): bool {
    $safeTable = preg_replace('/[^a-zA-Z0-9_]/', '', $table);
    $safeCol = $db->real_escape_string($col);
    $res = $db->query("SHOW COLUMNS FROM `{$safeTable}` LIKE '{$safeCol}'");
    $ok = $res && $res->num_rows > 0;
    if ($res) $res->free();
    return $ok;
}

function sas_first_col(mysqli $db, string $table, array $cols): ?string {
    if (!sas_table_exists($db, $table)) return null;

    foreach ($cols as $col) {
        if (sas_col_exists($db, $table, $col)) {
            return $col;
        }
    }

    return null;
}

function sas_fmt_dt($date, string $empty = '—'): string {
    $date = trim((string)$date);

    if ($date === '' || $date === '0000-00-00' || $date === '0000-00-00 00:00:00') {
        return $empty;
    }

    $time = strtotime($date);
    return $time ? date('d M Y, h:i A', $time) : $date;
}

function sas_short(?string $text, int $limit = 120): string {
    $text = trim(strip_tags((string)$text));

    if ($text === '') return '';

    if (function_exists('mb_strimwidth')) {
        return mb_strimwidth($text, 0, $limit, '...', 'UTF-8');
    }

    return strlen($text) > $limit ? substr($text, 0, $limit) . '...' : $text;
}

function sas_file_url(?string $path): string {
    $path = trim((string)$path);

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

    return '/elms/' . ltrim($path, '/');
}

function sas_status_badge(string $workflow, bool $hasSubmission, bool $upcoming, bool $closed, bool $overdue): array {
    $workflow = strtolower(trim($workflow));

    if ($workflow === 'released' || $workflow === 'published') {
        return ['Result Released', 'status-success', 'bi-award'];
    }

    if (in_array($workflow, ['coord_approved', 'approved'], true)) {
        return ['Approved', 'status-success', 'bi-check2-circle'];
    }

    if (in_array($workflow, ['under_review', 'coord_review', 'coordinator_review', 'admin_review'], true)) {
        return ['Under Review', 'status-info', 'bi-hourglass-split'];
    }

    if ($workflow === 'graded_provisional') {
        return ['Marked', 'status-primary', 'bi-pencil-square'];
    }

    if ($workflow === 'needs_correction') {
        return ['Correction Required', 'status-danger', 'bi-arrow-counterclockwise'];
    }

    if ($hasSubmission || in_array($workflow, ['submitted', 'pending'], true)) {
        return ['Submitted', 'status-primary', 'bi-cloud-check'];
    }

    if ($upcoming) {
        return ['Upcoming', 'status-muted', 'bi-calendar-event'];
    }

    if ($closed) {
        return ['Closed', 'status-muted', 'bi-lock'];
    }

    if ($overdue) {
        return ['Overdue', 'status-danger', 'bi-exclamation-triangle'];
    }

    return ['Pending', 'status-warning', 'bi-clock-history'];
}

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

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

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

if (!sas_table_exists($db, 'studentss')) {
    http_response_code(500);
    exit('studentss table not found');
}

$studentSelect = ['id'];

foreach (['full_name', 'name', 'student_name', 'academic_email', 'center_reg_no', 'reference_no', 'lms_status', 'course_id'] as $col) {
    if (sas_col_exists($db, 'studentss', $col)) {
        $studentSelect[] = "`{$col}`";
    }
}

$sql = "SELECT " . implode(', ', $studentSelect) . " FROM studentss WHERE id = ? LIMIT 1";
$stmt = $db->prepare($sql);
$stmt->bind_param('i', $studentId);
$stmt->execute();
$student = $stmt->get_result()->fetch_assoc();
$stmt->close();

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

$studentName = $student['full_name'] ?? ($student['name'] ?? ($student['student_name'] ?? 'Student'));

$_SESSION['student_name']   = $studentName;
$_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'];

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

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

/* ---------------- Student courses / batches ---------------- */

$courseIds = [];
$batchIds = [];
$courses = [];

if (sas_table_exists($db, 'enrollments') && sas_table_exists($db, 'batches')) {
    $batchNameCol = sas_first_col($db, 'batches', ['batch_name', 'name', 'title']) ?? 'id';
    $courseNameCol = sas_table_exists($db, 'courses') ? (sas_first_col($db, 'courses', ['course_name', 'name', 'title']) ?? 'id') : null;

    $sql = "
        SELECT DISTINCT
            b.id AS batch_id,
            b.course_id,
            COALESCE(b.`{$batchNameCol}`, CONCAT('Batch #', b.id)) AS batch_name
            " . ($courseNameCol ? ", COALESCE(c.`{$courseNameCol}`, CONCAT('Course #', b.course_id)) AS course_name" : ", CONCAT('Course #', b.course_id) AS course_name") . "
        FROM enrollments e
        INNER JOIN batches b ON b.id = e.batch_id
        " . ($courseNameCol ? "LEFT JOIN courses c ON c.id = b.course_id" : "") . "
        WHERE e.student_id = ?
          AND b.course_id IS NOT NULL
    ";

    $stmt = $db->prepare($sql);

    if ($stmt) {
        $stmt->bind_param('i', $studentId);
        $stmt->execute();
        $res = $stmt->get_result();

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

            if ($bid > 0) $batchIds[$bid] = $bid;

            if ($cid > 0) {
                $courseIds[$cid] = $cid;
                $courses[$cid] = $row['course_name'] ?: ('Course #' . $cid);
            }
        }

        $stmt->close();
    }
}

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

    if ($cid > 0) {
        $courseIds[$cid] = $cid;
        $courses[$cid] = 'Course #' . $cid;

        if (sas_table_exists($db, 'courses')) {
            $courseNameCol = sas_first_col($db, 'courses', ['course_name', 'name', 'title']) ?? 'id';
            $res = $db->query("SELECT COALESCE(`{$courseNameCol}`, CONCAT('Course #', id)) AS name FROM courses WHERE id = {$cid} LIMIT 1");
            $row = $res ? $res->fetch_assoc() : null;

            if (!empty($row['name'])) {
                $courses[$cid] = (string)$row['name'];
            }

            if ($res) $res->free();
        }
    }
}

/* ---------------- Assessment source ---------------- */

$assessmentTable = null;

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

$submissionTable = sas_table_exists($db, 'lms_submissions') ? 'lms_submissions' : '';

/* ---------------- Fetch assessments ---------------- */

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

if ($assessmentTable && $courseIds) {
    $idCol = sas_col_exists($db, $assessmentTable, 'id') ? 'id' : 'assessment_id';

    $titleCol = sas_first_col($db, $assessmentTable, ['title', 'name', 'assessment_title']) ?? $idCol;
    $courseCol = sas_col_exists($db, $assessmentTable, 'course_id') ? 'course_id' : null;
    $moduleCol = sas_col_exists($db, $assessmentTable, 'module_id') ? 'module_id' : null;

    $descCol = sas_first_col($db, $assessmentTable, ['description', 'brief', 'instructions', 'details']);
    $dueCol = sas_first_col($db, $assessmentTable, ['due_at', 'due_date', 'deadline', 'end_date', 'available_to']);
    $availableFromCol = sas_first_col($db, $assessmentTable, ['available_from', 'open_at', 'start_at']);
    $availableToCol = sas_first_col($db, $assessmentTable, ['available_to', 'close_at', 'end_at']);
    $releaseCol = sas_first_col($db, $assessmentTable, ['release_at', 'marks_release_at', 'result_release_at']);

    $activeCol = sas_first_col($db, $assessmentTable, ['active', 'is_active', 'status']);
    $typeCol = sas_first_col($db, $assessmentTable, ['type', 'assessment_type']);
    $marksCol = sas_first_col($db, $assessmentTable, ['max_score', 'total_marks', 'marks', 'max_marks']);

    $courseNameCol = sas_table_exists($db, 'courses') ? (sas_first_col($db, 'courses', ['course_name', 'name', 'title']) ?? 'id') : null;
    $moduleNameCol = sas_table_exists($db, 'course_modules') ? (sas_first_col($db, 'course_modules', ['title', 'module_name', 'name']) ?? 'id') : null;

    $courseIdList = implode(',', array_map('intval', array_values($courseIds)));
    $batchIdList = $batchIds ? implode(',', array_map('intval', array_values($batchIds))) : '0';

    $select = [];
    $select[] = "a.`{$idCol}` AS id";
    $select[] = "a.`{$titleCol}` AS title";
    $select[] = $courseCol ? "a.`{$courseCol}` AS course_id" : "0 AS course_id";
    $select[] = $moduleCol ? "a.`{$moduleCol}` AS module_id" : "0 AS module_id";
    $select[] = $descCol ? "a.`{$descCol}` AS description" : "'' AS description";
    $select[] = $dueCol ? "a.`{$dueCol}` AS due_at" : "NULL AS due_at";
    $select[] = $availableFromCol ? "a.`{$availableFromCol}` AS available_from" : "NULL AS available_from";
    $select[] = $availableToCol ? "a.`{$availableToCol}` AS available_to" : "NULL AS available_to";
    $select[] = $releaseCol ? "a.`{$releaseCol}` AS release_at" : "NULL AS release_at";
    $select[] = $typeCol ? "a.`{$typeCol}` AS assessment_type" : "'assessment' AS assessment_type";
    $select[] = $marksCol ? "a.`{$marksCol}` AS max_score" : "100 AS max_score";

    if ($courseNameCol && $courseCol) {
        $select[] = "COALESCE(c.`{$courseNameCol}`, CONCAT('Course #', a.`{$courseCol}`)) AS course_name";
    } else {
        $select[] = "'' AS course_name";
    }

    if ($moduleNameCol && $moduleCol) {
        $select[] = "COALESCE(cm.`{$moduleNameCol}`, CONCAT('Module #', a.`{$moduleCol}`)) AS module_name";
    } else {
        $select[] = "'' AS module_name";
    }

    if (sas_table_exists($db, 'lms_assessment_attachments')) {
        $select[] = "(SELECT file_path FROM lms_assessment_attachments aa WHERE aa.assessment_id = a.`{$idCol}` ORDER BY aa.id DESC LIMIT 1) AS attachment_path";
    } else {
        $select[] = "'' AS attachment_path";
    }

    if ($submissionTable) {
        $select[] = "s.id AS submission_id";
        $select[] = sas_col_exists($db, $submissionTable, 'workflow_status') ? "s.workflow_status" : "'' AS workflow_status";
        $select[] = sas_col_exists($db, $submissionTable, 'final_score') ? "s.final_score" : "NULL AS final_score";
        $select[] = sas_col_exists($db, $submissionTable, 'submitted_at') ? "s.submitted_at" : (sas_col_exists($db, $submissionTable, 'updated_at') ? "s.updated_at AS submitted_at" : "NULL AS submitted_at");
        $select[] = sas_col_exists($db, $submissionTable, 'lecturer_feedback') ? "s.lecturer_feedback" : (sas_col_exists($db, $submissionTable, 'feedback') ? "s.feedback AS lecturer_feedback" : "'' AS lecturer_feedback");
    } else {
        $select[] = "NULL AS submission_id";
        $select[] = "'' AS workflow_status";
        $select[] = "NULL AS final_score";
        $select[] = "NULL AS submitted_at";
        $select[] = "'' AS lecturer_feedback";
    }

    $joins = [];

    if ($courseNameCol && $courseCol) {
        $joins[] = "LEFT JOIN courses c ON c.id = a.`{$courseCol}`";
    }

    if ($moduleNameCol && $moduleCol) {
        $joins[] = "LEFT JOIN course_modules cm ON cm.id = a.`{$moduleCol}`";
    }

    if ($submissionTable) {
        $joins[] = "
            LEFT JOIN {$submissionTable} s
              ON s.assessment_id = a.`{$idCol}`
             AND s.student_id = {$studentId}
        ";
    }

    $where = [];

    if ($courseCol) {
        $where[] = "a.`{$courseCol}` IN ({$courseIdList})";
    }

    if ($moduleFilter > 0 && $moduleCol) {
        $where[] = "a.`{$moduleCol}` = {$moduleFilter}";
    }

    if ($activeCol) {
        if ($activeCol === 'status') {
            $where[] = "LOWER(COALESCE(a.`{$activeCol}`,'')) NOT IN ('inactive','disabled','draft','archived')";
        } else {
            $where[] = "(a.`{$activeCol}` IS NULL OR a.`{$activeCol}` IN (1,'1','active','Active','ACTIVE','yes','YES'))";
        }
    }

    /*
     * Target visibility:
     * 1) Direct student target
     * 2) Batch target matching student's enrolled batches
     * 3) No target records exist for this assessment → show by course
     */
    $targetConditions = [];

    if (sas_table_exists($db, 'lms_assessment_students')) {
        $targetConditions[] = "
            EXISTS (
                SELECT 1
                FROM lms_assessment_students ast
                WHERE ast.assessment_id = a.`{$idCol}`
                  AND ast.student_id = {$studentId}
            )
        ";
    }

    if (sas_table_exists($db, 'lms_assessment_batches')) {
        $targetConditions[] = "
            EXISTS (
                SELECT 1
                FROM lms_assessment_batches ab
                WHERE ab.assessment_id = a.`{$idCol}`
                  AND ab.batch_id IN ({$batchIdList})
            )
        ";

        $targetConditions[] = "
            NOT EXISTS (
                SELECT 1
                FROM lms_assessment_batches ab2
                WHERE ab2.assessment_id = a.`{$idCol}`
            )
            " . (sas_table_exists($db, 'lms_assessment_students') ? "
            AND NOT EXISTS (
                SELECT 1
                FROM lms_assessment_students ast2
                WHERE ast2.assessment_id = a.`{$idCol}`
            )
            " : "") . "
        ";
    } elseif (sas_table_exists($db, 'lms_assessment_students')) {
        $targetConditions[] = "
            NOT EXISTS (
                SELECT 1
                FROM lms_assessment_students ast2
                WHERE ast2.assessment_id = a.`{$idCol}`
            )
        ";
    }

    if ($targetConditions) {
        $where[] = "(" . implode(" OR ", $targetConditions) . ")";
    }

    if (!$where) {
        $where[] = "1=1";
    }

    $orderExpr = $dueCol ? "a.`{$dueCol}` ASC, a.`{$idCol}` DESC" : "a.`{$idCol}` DESC";

    $sql = "
        SELECT " . implode(",\n               ", $select) . "
        FROM `{$assessmentTable}` a
        " . implode("\n        ", $joins) . "
        WHERE " . implode(" AND ", $where) . "
        ORDER BY {$orderExpr}
        LIMIT 300
    ";

    $res = $db->query($sql);

    if ($res) {
        while ($row = $res->fetch_assoc()) {
            $rows[] = $row;
        }

        $res->free();
    }
}

/* ---------------- Stats ---------------- */

$now = time();

foreach ($rows as $row) {
    $totalAssessments++;

    $workflow = strtolower(trim((string)($row['workflow_status'] ?? '')));
    $hasSubmission = !empty($row['submission_id']);

    $availableFrom = trim((string)($row['available_from'] ?? ''));
    $availableTo = trim((string)($row['available_to'] ?? ''));
    $dueAt = trim((string)($row['due_at'] ?? ''));

    $upcoming = $availableFrom !== '' && strtotime($availableFrom) && strtotime($availableFrom) > $now;
    $closed = $availableTo !== '' && strtotime($availableTo) && strtotime($availableTo) < $now;
    $overdue = $dueAt !== '' && strtotime($dueAt) && strtotime($dueAt) < $now && !$hasSubmission;

    if (in_array($workflow, ['released', 'published'], true)) {
        $releasedCount++;
    } elseif ($workflow === 'needs_correction') {
        $correctionCount++;
    } elseif (in_array($workflow, ['under_review', 'coord_review', 'coordinator_review', 'admin_review', 'coord_approved', 'approved', 'graded_provisional'], true)) {
        $reviewCount++;
    } elseif ($hasSubmission || in_array($workflow, ['submitted', 'pending'], true)) {
        $submittedCount++;
    } elseif (!$upcoming && !$closed) {
        $pendingCount++;
    }
}

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

<style>
    .assess-summary-grid {
        display: grid;
        grid-template-columns: repeat(6, 1fr);
        gap: 14px;
        margin-bottom: 22px;
    }

    .assess-summary-card {
        background: #fff;
        border: 1px solid #e5e7eb;
        border-radius: 18px;
        padding: 16px;
        box-shadow: 0 8px 22px rgba(15,23,42,.04);
    }

    .assess-summary-icon {
        width: 36px;
        height: 36px;
        border-radius: 13px;
        background: #eff6ff;
        color: #034ea2;
        display: grid;
        place-items: center;
        margin-bottom: 10px;
    }

    .assess-summary-value {
        font-size: 1.45rem;
        font-weight: 950;
        color: #111827;
        line-height: 1;
    }

    .assess-summary-label {
        margin-top: 7px;
        color: #7b8190;
        font-size: .76rem;
        font-weight: 850;
    }

    .assessment-module-box {
        background: #fff;
        border: 1px solid #e5e7eb;
        border-radius: 18px;
        box-shadow: 0 8px 22px rgba(15,23,42,.045);
        overflow: hidden;
    }

    .assessment-module-head {
        padding: 18px 20px;
        border-bottom: 1px solid #e5e7eb;
        background: linear-gradient(180deg, #fff, #fafbff);
        display: flex;
        align-items: center;
        justify-content: space-between;
        gap: 14px;
    }

    .assessment-module-title {
        margin: 0;
        font-size: 1.12rem;
        font-weight: 950;
        color: #12386f;
    }

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

    .assessment-list {
        padding: 0 16px 14px;
    }

    .assessment-row-clean {
        display: grid;
        grid-template-columns: minmax(0, 1fr) 165px 165px 150px 42px;
        gap: 14px;
        align-items: center;
        padding: 17px 0;
        border-bottom: 1px solid #eef2f7;
    }

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

    .assessment-name-clean {
        font-weight: 850;
        color: #263247;
        line-height: 1.35;
    }

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

    .assessment-date-label {
        color: #7b8190;
        font-size: .68rem;
        text-transform: uppercase;
        font-weight: 900;
        letter-spacing: .04em;
        margin-bottom: 3px;
    }

    .assessment-date-value {
        color: #334155;
        font-weight: 750;
        font-size: .8rem;
        line-height: 1.35;
    }

    .assessment-status-pill {
        display: inline-flex;
        align-items: center;
        justify-content: center;
        gap: 6px;
        border-radius: 0;
        padding: 6px 10px;
        font-size: .72rem;
        font-weight: 850;
        min-width: 118px;
        border: 0;
        text-align: center;
    }

    .status-warning {
        background: #fff7ed;
        color: #c2410c;
    }

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

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

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

    .status-muted {
        background: #f1f5f9;
        color: #64748b;
    }

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

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

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

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

    .assessment-filter-note {
        display: inline-flex;
        align-items: center;
        gap: 8px;
        padding: 8px 12px;
        border-radius: 999px;
        background: #eff6ff;
        color: #034ea2;
        font-weight: 850;
        font-size: .8rem;
        margin-bottom: 16px;
    }

    @media (max-width: 1100px) {
        .assess-summary-grid {
            grid-template-columns: repeat(3, 1fr);
        }

        .assessment-row-clean {
            grid-template-columns: minmax(0, 1fr) 140px 140px 135px 38px;
        }
    }

    @media (max-width: 768px) {
        .assess-summary-grid {
            grid-template-columns: repeat(2, 1fr);
        }

        .assessment-row-clean {
            grid-template-columns: 1fr;
            gap: 8px;
            padding: 16px 0;
        }

        .assessment-status-pill {
            width: fit-content;
        }

        .assessment-open-btn {
            width: 100%;
            border-radius: 12px;
            height: 38px;
        }
    }
</style>

<div class="student-page-tabs">
    <a href="/elms/student/assessments/assessments.php" class="active">Assessments</a>
</div>

<div class="assess-summary-grid">
    <div class="assess-summary-card">
        <div class="assess-summary-icon"><i class="bi bi-clipboard"></i></div>
        <div class="assess-summary-value"><?= (int)$totalAssessments ?></div>
        <div class="assess-summary-label">Total</div>
    </div>

    <div class="assess-summary-card">
        <div class="assess-summary-icon"><i class="bi bi-clock-history"></i></div>
        <div class="assess-summary-value"><?= (int)$pendingCount ?></div>
        <div class="assess-summary-label">Pending</div>
    </div>

    <div class="assess-summary-card">
        <div class="assess-summary-icon"><i class="bi bi-cloud-check"></i></div>
        <div class="assess-summary-value"><?= (int)$submittedCount ?></div>
        <div class="assess-summary-label">Submitted</div>
    </div>

    <div class="assess-summary-card">
        <div class="assess-summary-icon"><i class="bi bi-arrow-counterclockwise"></i></div>
        <div class="assess-summary-value"><?= (int)$correctionCount ?></div>
        <div class="assess-summary-label">Correction</div>
    </div>

    <div class="assess-summary-card">
        <div class="assess-summary-icon"><i class="bi bi-hourglass-split"></i></div>
        <div class="assess-summary-value"><?= (int)$reviewCount ?></div>
        <div class="assess-summary-label">Review</div>
    </div>

    <div class="assess-summary-card">
        <div class="assess-summary-icon"><i class="bi bi-award"></i></div>
        <div class="assess-summary-value"><?= (int)$releasedCount ?></div>
        <div class="assess-summary-label">Released</div>
    </div>
</div>

<?php if ($moduleFilter > 0): ?>
    <div class="assessment-filter-note">
        <i class="bi bi-funnel"></i>
        Module filter active: <?= (int)$moduleFilter ?>
        <a href="/elms/student/assessments/assessments.php" class="ms-2 text-decoration-underline">Clear</a>
    </div>
<?php endif; ?>

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

    <div class="assessment-empty">
        <i class="bi bi-info-circle"></i>
        <h5 class="fw-bold">Course enrollment not found</h5>
        <p class="mb-0">This student is not linked with a course or batch.</p>
    </div>

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

    <div class="assessment-empty">
        <i class="bi bi-exclamation-triangle"></i>
        <h5 class="fw-bold">Assessment table not found</h5>
        <p class="mb-0">Need lms_assessments table.</p>
    </div>

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

    <div class="assessment-empty">
        <i class="bi bi-clipboard-x"></i>
        <h5 class="fw-bold">No assessments available</h5>
        <p class="mb-0">There are no active assessments assigned to you yet.</p>
    </div>

<?php else: ?>

    <div class="assessment-module-box">
        <div class="assessment-module-head">
            <div>
                <h2 class="assessment-module-title">Assessment List</h2>
                <div class="assessment-module-sub">
                    Submit work, track correction requests, review status, and released marks.
                </div>
            </div>

            <span class="badge rounded-pill text-bg-light px-3 py-2">
                <?= number_format(count($rows)) ?> record(s)
            </span>
        </div>

        <div class="assessment-list">
            <?php foreach ($rows as $row): ?>
                <?php
                    $assessmentId = (int)($row['id'] ?? 0);
                    $title = (string)($row['title'] ?? 'Assessment');
                    $courseName = (string)($row['course_name'] ?? ($courses[(int)($row['course_id'] ?? 0)] ?? 'Course'));
                    $moduleName = (string)($row['module_name'] ?? '');
                    $type = (string)($row['assessment_type'] ?? 'Assessment');

                    $availableFrom = (string)($row['available_from'] ?? '');
                    $availableTo = (string)($row['available_to'] ?? '');
                    $dueAt = (string)($row['due_at'] ?? '');
                    $releaseAt = (string)($row['release_at'] ?? '');

                    $submissionId = (int)($row['submission_id'] ?? 0);
                    $workflow = strtolower(trim((string)($row['workflow_status'] ?? '')));

                    $fromTs = $availableFrom !== '' ? strtotime($availableFrom) : false;
                    $toTs = $availableTo !== '' ? strtotime($availableTo) : false;
                    $dueTs = $dueAt !== '' ? strtotime($dueAt) : false;

                    $upcoming = $fromTs && $fromTs > $now;
                    $closed = $toTs && $toTs < $now;
                    $hasSubmission = $submissionId > 0;
                    $overdue = $dueTs && $dueTs < $now && !$hasSubmission;

                    [$statusText, $statusClass, $statusIcon] = sas_status_badge(
                        $workflow,
                        $hasSubmission,
                        (bool)$upcoming,
                        (bool)$closed,
                        (bool)$overdue
                    );

                    $openUrl = "/elms/student/assessments/submit.php?assessment_id=" . $assessmentId;
                ?>

                <div class="assessment-row-clean">
                    <div>
                        <div class="assessment-name-clean">
                            <?= sas_h($title) ?>
                        </div>

                        <div class="assessment-meta-clean">
                            <?= sas_h(ucfirst($type)) ?>

                            <?php if ($courseName !== ''): ?>
                                <span class="mx-1">·</span><?= sas_h($courseName) ?>
                            <?php endif; ?>

                            <?php if ($moduleName !== ''): ?>
                                <span class="mx-1">·</span><?= sas_h($moduleName) ?>
                            <?php endif; ?>
                        </div>
                    </div>

                    <div>
                        <div class="assessment-date-label">Submission Date</div>
                        <div class="assessment-date-value">
                            <?= sas_h(sas_fmt_dt($dueAt, 'Not set')) ?>
                        </div>
                    </div>

                    <div>
                        <div class="assessment-date-label">Marks Release Date</div>
                        <div class="assessment-date-value">
                            <?= sas_h(sas_fmt_dt($releaseAt, 'Not set')) ?>
                        </div>
                    </div>

                    <div>
                        <span class="assessment-status-pill <?= sas_h($statusClass) ?>">
                            <i class="bi <?= sas_h($statusIcon) ?>"></i>
                            <?= sas_h($statusText) ?>
                        </span>
                    </div>

                    <a href="<?= sas_h($openUrl) ?>" class="assessment-open-btn" title="Open assessment">
                        <i class="bi bi-arrow-right"></i>
                    </a>
                </div>

            <?php endforeach; ?>
        </div>
    </div>

<?php endif; ?>

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