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

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

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

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

if (!$mysqli instanceof mysqli) {
    die('Database connection not found.');
}

$mysqli->set_charset('utf8mb4');

$PAGE_TITLE = 'Dashboard';
$ACTIVE     = 'dashboard';

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

if (!function_exists('stu_dash_tbl_exists')) {
    function stu_dash_tbl_exists(mysqli $db, string $table): bool
    {
        $stmt = $db->prepare("
            SELECT 1
            FROM INFORMATION_SCHEMA.TABLES
            WHERE TABLE_SCHEMA = DATABASE()
              AND TABLE_NAME = ?
            LIMIT 1
        ");
        $stmt->bind_param('s', $table);
        $stmt->execute();
        $ok = (bool)$stmt->get_result()->fetch_row();
        $stmt->close();
        return $ok;
    }
}

if (!function_exists('stu_dash_col_exists')) {
    function stu_dash_col_exists(mysqli $db, string $table, string $col): bool
    {
        $stmt = $db->prepare("
            SELECT 1
            FROM INFORMATION_SCHEMA.COLUMNS
            WHERE TABLE_SCHEMA = DATABASE()
              AND TABLE_NAME = ?
              AND COLUMN_NAME = ?
            LIMIT 1
        ");
        $stmt->bind_param('ss', $table, $col);
        $stmt->execute();
        $ok = (bool)$stmt->get_result()->fetch_row();
        $stmt->close();
        return $ok;
    }
}

if (!function_exists('stu_dash_first_col')) {
    function stu_dash_first_col(mysqli $db, string $table, array $cols): ?string
    {
        foreach ($cols as $col) {
            if (stu_dash_col_exists($db, $table, $col)) {
                return $col;
            }
        }
        return null;
    }
}

if (!function_exists('stu_dash_count')) {
    function stu_dash_count(mysqli $db, string $sql): int
    {
        try {
            $res = $db->query($sql);
            if (!$res) return 0;
            return (int)($res->fetch_assoc()['c'] ?? 0);
        } catch (Throwable $e) {
            return 0;
        }
    }
}

if (!function_exists('stu_dash_rows')) {
    function stu_dash_rows(mysqli $db, string $sql): array
    {
        try {
            $res = $db->query($sql);
            if (!$res) return [];
            return $res->fetch_all(MYSQLI_ASSOC);
        } catch (Throwable $e) {
            return [];
        }
    }
}

$studentId = (int)(
    $_SESSION['student_id']
    ?? $_SESSION['user_id']
    ?? $_SESSION['id']
    ?? 0
);

$studentName = (string)(
    $_SESSION['student_name']
    ?? $_SESSION['full_name']
    ?? $_SESSION['user_name']
    ?? 'Student'
);

$hour = (int)date('H');
$greeting = 'Good Evening';

if ($hour < 12) {
    $greeting = 'Good Morning';
} elseif ($hour < 17) {
    $greeting = 'Good Afternoon';
}

$monthTs = strtotime(date('Y-m-01'));
$monthName = date('F, Y', $monthTs);
$daysInMonth = (int)date('t', $monthTs);
$firstDay = (int)date('w', $monthTs);
$todayDay = (int)date('j');

$myCourses = [];
$recentAssessments = [];
$recentResults = [];
$recentNotifications = [];
$dashboardNotices = [];

$totalCourses = 0;
$totalAssessments = 0;
$pendingAssessments = 0;
$releasedResults = 0;
$unreadNotifications = 0;

/*
|--------------------------------------------------------------------------
| My Courses
|--------------------------------------------------------------------------
*/
try {
    if (
        $studentId > 0 &&
        stu_dash_tbl_exists($mysqli, 'enrollments') &&
        stu_dash_tbl_exists($mysqli, 'batches') &&
        stu_dash_tbl_exists($mysqli, 'courses') &&
        stu_dash_col_exists($mysqli, 'enrollments', 'student_id') &&
        stu_dash_col_exists($mysqli, 'enrollments', 'batch_id') &&
        stu_dash_col_exists($mysqli, 'batches', 'course_id')
    ) {
        $courseTitleCol = stu_dash_first_col($mysqli, 'courses', ['course_name', 'name', 'title']) ?? 'id';
        $batchLabelCol  = stu_dash_first_col($mysqli, 'batches', ['batch_name', 'batch_code', 'name', 'title']) ?? 'id';

        $startCol = stu_dash_first_col($mysqli, 'batches', ['batch_start_date', 'start_date', 'created_at']);
        $endCol   = stu_dash_first_col($mysqli, 'batches', ['batch_end_date', 'end_date']);

        $startSelect = $startCol ? "b.`$startCol` AS start_date" : "NULL AS start_date";
        $endSelect   = $endCol ? "b.`$endCol` AS end_date" : "NULL AS end_date";

        $stmt = $mysqli->prepare("
            SELECT DISTINCT
                c.id AS course_id,
                c.`$courseTitleCol` AS course_title,
                b.id AS batch_id,
                b.`$batchLabelCol` AS batch_label,
                $startSelect,
                $endSelect
            FROM enrollments e
            JOIN batches b ON b.id = e.batch_id
            JOIN courses c ON c.id = b.course_id
            WHERE e.student_id = ?
            ORDER BY c.`$courseTitleCol`
            LIMIT 12
        ");
        $stmt->bind_param('i', $studentId);
        $stmt->execute();
        $myCourses = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
        $stmt->close();
    }
} catch (Throwable $e) {
    $myCourses = [];
}

$totalCourses = count($myCourses);

/*
|--------------------------------------------------------------------------
| Assessments
|--------------------------------------------------------------------------
*/
$totalAssessments = 0;
$pendingAssessments = 0;
$recentAssessments = [];

try {
    if (
        $studentId > 0 &&
        stu_dash_tbl_exists($mysqli, 'lms_assessments') &&
        stu_dash_tbl_exists($mysqli, 'lms_submissions')
    ) {
        $sql = "
            SELECT DISTINCT
                a.id,
                a.title,
                COALESCE(a.type, 'Assessment') AS type,
                a.due_at AS due_date,
                a.course_id,
                a.module_id,
                c.course_name,
                s.id AS submission_id,
                s.workflow_status
            FROM lms_assessments a
            LEFT JOIN courses c ON c.id = a.course_id

            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 = ?

            WHERE a.active = 1
              AND (ast.student_id IS NOT NULL OR e.student_id IS NOT NULL)
              AND (
                    s.id IS NULL
                    OR s.workflow_status IS NULL
                    OR s.workflow_status = ''
                    OR s.workflow_status = 'needs_correction'
                  )
            ORDER BY a.id DESC
            LIMIT 5
        ";

        $st = $mysqli->prepare($sql);
        if ($st) {
            $st->bind_param('iii', $studentId, $studentId, $studentId);
            $st->execute();
            $recentAssessments = $st->get_result()->fetch_all(MYSQLI_ASSOC);
            $st->close();
        }

        $pendingAssessments = count($recentAssessments);
        $totalAssessments = $pendingAssessments;
    }
} catch (Throwable $e) {
    $totalAssessments = 0;
    $pendingAssessments = 0;
    $recentAssessments = [];
}

/*
|--------------------------------------------------------------------------
| Results
|--------------------------------------------------------------------------
*/
try {
    if (
        $studentId > 0 &&
        stu_dash_tbl_exists($mysqli, 'lms_submissions') &&
        stu_dash_tbl_exists($mysqli, 'lms_assessments') &&
        stu_dash_col_exists($mysqli, 'lms_submissions', 'student_id') &&
        stu_dash_col_exists($mysqli, 'lms_submissions', 'assessment_id')
    ) {
        $aIdCol    = stu_dash_col_exists($mysqli, 'lms_assessments', 'id') ? 'id' : 'assessment_id';
        $aTitleCol = stu_dash_first_col($mysqli, 'lms_assessments', ['title', 'name']) ?? $aIdCol;

        $scoreSelect = stu_dash_col_exists($mysqli, 'lms_submissions', 'final_score')
            ? 's.final_score'
            : (stu_dash_col_exists($mysqli, 'lms_submissions', 'score') ? 's.score AS final_score' : 'NULL AS final_score');

        $gradeSelect = stu_dash_col_exists($mysqli, 'lms_submissions', 'grade')
            ? 's.grade'
            : 'NULL AS grade';

        $updatedSelect = stu_dash_col_exists($mysqli, 'lms_submissions', 'updated_at')
            ? 's.updated_at'
            : 'NULL AS updated_at';

        $releasedWhere = "s.student_id = {$studentId}";

        if (stu_dash_col_exists($mysqli, 'lms_submissions', 'is_released')) {
            $releasedWhere .= " AND s.is_released = 1";
        } elseif (stu_dash_col_exists($mysqli, 'lms_submissions', 'workflow_status')) {
            $releasedWhere .= " AND s.workflow_status IN ('released','coord_approved','approved')";
        } elseif (stu_dash_col_exists($mysqli, 'lms_submissions', 'status')) {
            $releasedWhere .= " AND s.status IN ('released','approved','marked')";
        }

        $releasedResults = stu_dash_count($mysqli, "
            SELECT COUNT(DISTINCT s.assessment_id) AS c
            FROM lms_submissions s
            WHERE {$releasedWhere}
        ");

        $recentResults = stu_dash_rows($mysqli, "
            SELECT
                a.`$aTitleCol` AS title,
                $scoreSelect,
                $gradeSelect,
                $updatedSelect
            FROM lms_submissions s
            JOIN lms_assessments a ON a.`$aIdCol` = s.assessment_id
            WHERE {$releasedWhere}
            ORDER BY s.id DESC
            LIMIT 5
        ");
    }
} catch (Throwable $e) {
    $releasedResults = 0;
    $recentResults = [];
}

/*
|--------------------------------------------------------------------------
| Notifications
|--------------------------------------------------------------------------
*/
try {
    if ($studentId > 0 && stu_dash_tbl_exists($mysqli, 'lms_notifications')) {
        $where = [];

        if (stu_dash_col_exists($mysqli, 'lms_notifications', 'student_id')) {
            $where[] = "student_id = {$studentId}";
        } elseif (
            stu_dash_col_exists($mysqli, 'lms_notifications', 'receiver_id') &&
            stu_dash_col_exists($mysqli, 'lms_notifications', 'receiver_role')
        ) {
            $where[] = "receiver_id = {$studentId}";
            $where[] = "receiver_role = 'student'";
        } elseif (
            stu_dash_col_exists($mysqli, 'lms_notifications', 'user_id') &&
            stu_dash_col_exists($mysqli, 'lms_notifications', 'user_role')
        ) {
            $where[] = "user_id = {$studentId}";
            $where[] = "user_role = 'student'";
        }

        $mainWhere = $where ? implode(' AND ', $where) : '1=1';

        $unreadWhere = $mainWhere;

        if (stu_dash_col_exists($mysqli, 'lms_notifications', 'is_read')) {
            $unreadWhere .= " AND is_read = 0";
        } elseif (stu_dash_col_exists($mysqli, 'lms_notifications', 'read_at')) {
            $unreadWhere .= " AND read_at IS NULL";
        }

        $unreadNotifications = stu_dash_count($mysqli, "
            SELECT COUNT(*) AS c
            FROM lms_notifications
            WHERE {$unreadWhere}
        ");

        $titleCol = stu_dash_first_col($mysqli, 'lms_notifications', ['title']) ?? null;
        $msgCol   = stu_dash_first_col($mysqli, 'lms_notifications', ['message', 'body']) ?? null;
        $dateCol  = stu_dash_first_col($mysqli, 'lms_notifications', ['created_at', 'date_created']) ?? null;

        $titleSelect = $titleCol ? "`$titleCol` AS title" : "'Notification' AS title";
        $msgSelect   = $msgCol ? "`$msgCol` AS message" : "'' AS message";
        $dateSelect  = $dateCol ? "`$dateCol` AS created_at" : "NULL AS created_at";

        $orderCol = stu_dash_col_exists($mysqli, 'lms_notifications', 'id') ? 'id' : ($dateCol ?: '1');

        $recentNotifications = stu_dash_rows($mysqli, "
            SELECT
                $titleSelect,
                $msgSelect,
                $dateSelect
            FROM lms_notifications
            WHERE {$mainWhere}
            ORDER BY `$orderCol` DESC
            LIMIT 5
        ");
    }
} catch (Throwable $e) {
    $unreadNotifications = 0;
    $recentNotifications = [];
}
/*
|--------------------------------------------------------------------------
| Dashboard Notices
|--------------------------------------------------------------------------
*/
try {
    if (stu_dash_tbl_exists($mysqli, 'lms_student_notices')) {
        $dashboardNotices = stu_dash_rows($mysqli, "
            SELECT title, message, image_path, button_text, button_url
            FROM lms_student_notices
            WHERE status = 'active'
              AND (starts_at IS NULL OR starts_at <= NOW())
              AND (ends_at IS NULL OR ends_at >= NOW())
            ORDER BY sort_order ASC, id DESC
            LIMIT 8
        ");
    }
} catch (Throwable $e) {
    $dashboardNotices = [];
}
require_once __DIR__ . '/../includes/student_layout_top.php';
?>

<style>
    .dash-greeting {
        padding: 18px 0 20px;
    }

    .dash-greeting-small {
        font-size: 1.6rem;
        color: #12386f;
        font-weight: 850;
        margin-bottom: 8px;
    }

    .dash-greeting-name {
        font-size: 2.7rem;
        color: #12386f;
        font-weight: 400;
        letter-spacing: -.9px;
        line-height: 1.12;
    }

    .dash-main-grid {
    display: grid;
    grid-template-columns: minmax(0,1fr) 420px;
    gap: 26px;
    align-items: start;
}

    .dash-section-title {
        color: #3f4652;
        font-weight: 900;
        font-size: 1.45rem;
        margin: 0 0 18px;
    }

    .course-grid {
        display: grid;
        grid-template-columns: repeat(2, minmax(230px, 1fr));
        gap: 18px;
    }

    .course-card-v2 {
        min-height: 210px;
        background: #fff;
        border: 1px solid #e5e7eb;
        border-radius: 18px;
        padding: 24px;
        box-shadow: 0 8px 22px rgba(15,23,42,.045);
        transition: .16s ease;
        display: flex;
        flex-direction: column;
        justify-content: space-between;
    }

    .course-card-v2:hover {
        transform: translateY(-2px);
        border-color: #bfdbfe;
        box-shadow: 0 14px 30px rgba(15,23,42,.075);
    }

    .course-logo-mini {
        width: 36px;
        height: 36px;
        border-radius: 8px;
        background: #f8fafc;
        border: 1px solid #eef2f7;
        display: grid;
        place-items: center;
        color: #034ea2;
        font-weight: 900;
        font-size: .8rem;
    }

    .course-title-v2 {
        color: #3f4652;
        font-weight: 850;
        font-size: 1.05rem;
        line-height: 1.35;
        margin-top: 22px;
        margin-bottom: 18px;
    }

    .course-meta-v2 {
        color: #7b8190;
        font-weight: 650;
        line-height: 1.55;
        font-size: .86rem;
    }

    .course-open-link {
        color: #034ea2;
        font-weight: 850;
        font-size: .84rem;
        margin-top: 14px;
        display: inline-flex;
        align-items: center;
        gap: 6px;
    }

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

    .calendar-head {
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 18px;
        margin-bottom: 18px;
    }

    .cal-nav {
        width: 42px;
        height: 42px;
        border-radius: 50%;
        border: 1px solid #dbe3ef;
        background: #fff;
        color: #526071;
        display: grid;
        place-items: center;
        font-size: 1.3rem;
    }

    .calendar-title {
        font-size: 1.65rem;
        font-weight: 900;
        color: #4b5563;
        min-width: 190px;
        text-align: center;
    }

    .cal-grid {
        display: grid;
        grid-template-columns: repeat(7, 1fr);
        border: 1px solid #e5e7eb;
        border-bottom: 0;
        border-right: 0;
    }

    .cal-cell {
        min-height: 78px;
        border-right: 1px solid #e5e7eb;
        border-bottom: 1px solid #e5e7eb;
        padding: 8px;
        color: #8a8f98;
        font-size: 1rem;
        background: #fff;
    }

    .cal-head-cell {
        min-height: auto;
        font-weight: 850;
        color: #8a8f98;
        text-align: center;
        background: #fff;
        padding: 8px;
    }

    .cal-other {
        color: #c8ccd3;
        background: #fafafa;
    }

    .cal-today {
        background: #eaf7fb;
        color: #034ea2;
        font-weight: 900;
    }

    .dash-widget-row {
        display: grid;
        grid-template-columns: repeat(4, 1fr);
        gap: 14px;
        margin: 24px 0;
    }

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

    .dash-widget-icon {
        width: 38px;
        height: 38px;
        border-radius: 13px;
        display: grid;
        place-items: center;
        background: #eff6ff;
        color: #034ea2;
        margin-bottom: 12px;
    }

    .dash-widget-value {
        font-size: 1.45rem;
        font-weight: 900;
        color: #1f2937;
    }

    .dash-widget-label {
        color: #7b8190;
        font-weight: 750;
        font-size: .82rem;
    }

    .dash-lower-grid {
        display: grid;
        grid-template-columns: 1.2fr .8fr;
        gap: 20px;
        margin-top: 24px;
    }

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

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

    .mini-list-title {
        font-weight: 900;
        margin: 0;
        color: #263247;
        font-size: 1rem;
    }

    .mini-list-body {
        padding: 8px 18px 18px;
    }

    .activity-row {
        display: flex;
        align-items: center;
        justify-content: space-between;
        gap: 12px;
        padding: 13px 0;
        border-bottom: 1px solid #eef2f7;
    }

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

    .activity-title {
        font-weight: 800;
        color: #263247;
    }

    .activity-meta {
        color: #7b8190;
        font-size: .78rem;
        margin-top: 3px;
    }

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

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

    .status-soft-blue {
        background: #dbeafe;
        color: #1d4ed8;
    }

    .empty-simple {
        text-align: center;
        color: #8a8f98;
        padding: 28px 12px;
    }

    @media (max-width: 1250px) {
        .dash-main-grid {
            grid-template-columns: 1fr;
        }

        .calendar-card {
            max-width: 720px;
        }
    }

    @media (max-width: 850px) {
        .dash-greeting-name {
            font-size: 2rem;
        }

        .course-grid,
        .dash-widget-row,
        .dash-lower-grid {
            grid-template-columns: 1fr;
        }

        .calendar-title {
            font-size: 1.3rem;
            min-width: 150px;
        }

        .cal-cell {
            min-height: 54px;
            font-size: .85rem;
        }
    }
    .dash-main-grid{
    display:grid;
    grid-template-columns:minmax(0,1fr) 420px;
    gap:26px;
    align-items:start;
}


.dash-right-col{
    margin-top:-230px;
}

.dash-notice-row{
    display:flex;
    flex-direction:column;
    gap:18px;
    margin:0 0 20px;
}

.dash-notice-card{
    background:#fff;
    border:1px solid #e5e7eb;
    border-radius:18px;
    overflow:hidden;
    box-shadow:0 8px 24px rgba(15,23,42,.06);
    width:100%;
}

.dash-notice-img{
    width:100%;
    height:190px;
    object-fit:cover;
    display:block;
}

.dash-notice-body{
    padding:10px 12px;
}

.dash-notice-kicker{
    color:#034ea2;
    font-size:.72rem;
    font-weight:900;
    text-transform:uppercase;
}

.dash-notice-title{
    margin:6px 0 4px;
    color:#12386f;
    font-weight:900;
    font-size:1rem;
}

.dash-notice-text{
    color:#64748b;
    font-size:.88rem;
    font-weight:600;
    margin:0;
}

@media(max-width:1250px){
    .dash-main-grid{
        grid-template-columns:1fr;
    }

    .dash-right-col{
        margin-top:0;
    }
}
.dash-notice-title-link{
    display:block;
    margin:6px 0 4px;
    color:#12386f;
    font-weight:900;
    font-size:1rem;
    text-decoration:none;
}

.dash-notice-title-link:hover{
    color:#034ea2;
    text-decoration:underline;
}
.student-notice-bottom{
    margin-top:32px;
    padding-top:20px;
    border-top:1px solid #e5e7eb;
}

.student-notice-bottom-title{
    font-size:1rem;
    font-weight:900;
    color:#263247;
    margin:0 0 14px;
}

.student-notice-bottom-grid{
    display:grid;
    grid-template-columns:repeat(4, minmax(260px, 1fr));
    gap:14px;
}

.student-notice-mini-card{
    background:#fff;
    border:1px solid #e5e7eb;
    border-radius:10px;
    overflow:hidden;
    text-decoration:none;
    color:inherit;
    box-shadow:0 6px 16px rgba(15,23,42,.045);
}

.student-notice-mini-img{
    width:100%;
    height:200px;
    object-fit:cover;
    display:block;
}

.student-notice-mini-body{
    padding:10px;
}

.student-notice-mini-title{
    color:#263247;
    font-weight:850;
    font-size:.82rem;
    line-height:1.35;
}

.student-notice-mini-text{
    margin-top:5px;
    color:#7b8190;
    font-size:.72rem;
    line-height:1.35;
}

@media(max-width:900px){
    .student-notice-bottom-grid{
        grid-template-columns:repeat(2, 1fr);
    }
}

@media(max-width:520px){
    .student-notice-bottom-grid{
        grid-template-columns:1fr;
    }
}
</style>

<div class="dash-greeting">
    <div class="dash-greeting-small"><?= stu_dash_h($greeting) ?></div>
    <div class="dash-greeting-name"><?= stu_dash_h($studentName) ?> 👋</div>
</div>

<div class="dash-main-grid">
    <section>
        <h2 class="dash-section-title">My Courses</h2>

        <?php if ($myCourses): ?>
            <div class="course-grid">
                <?php foreach ($myCourses as $course): ?>
                    <?php
                    $courseTitle = (string)($course['course_title'] ?? 'Course');
                    $batchLabel  = (string)($course['batch_label'] ?? '');
                    $startDate   = !empty($course['start_date']) ? date('d/m/Y', strtotime((string)$course['start_date'])) : '';
                    $endDate     = !empty($course['end_date']) ? date('d/m/Y', strtotime((string)$course['end_date'])) : '';
                    ?>
                    <a href="/elms/student/modules.php?course_id=<?= (int)$course['course_id'] ?>" class="course-card-v2">
                        <div>
                            <div class="course-logo-mini">EC</div>
                            <div class="course-title-v2">
                                <?= stu_dash_h($courseTitle) ?>
                            </div>
                        </div>

                        <div>
                            <div class="course-meta-v2">
                                <?php if ($batchLabel !== ''): ?>
                                    Batch: <?= stu_dash_h($batchLabel) ?><br>
                                <?php endif; ?>

                                <?php if ($startDate || $endDate): ?>
                                    <?= stu_dash_h($startDate ?: 'Start') ?> 
                                    <?php if ($endDate): ?>
                                        - <?= stu_dash_h($endDate) ?>
                                    <?php endif; ?>
                                <?php else: ?>
                                    Online Learning
                                <?php endif; ?>
                            </div>

                            <span class="course-open-link">
                                Open Course <i class="bi bi-arrow-right"></i>
                            </span>
                        </div>
                    </a>
                <?php endforeach; ?>
            </div>
        <?php else: ?>
            <div class="student-card">
                <div class="student-card-body empty-simple">
                    <i class="bi bi-journal-x fs-2 d-block mb-2"></i>
                    No enrolled courses found.
                </div>
            </div>
        <?php endif; ?>
    </section>

    <aside class="dash-right-col">
        <?php if ($dashboardNotices): ?>
    <div class="dash-notice-row">
        <?php foreach ($dashboardNotices as $n): ?>
            <div class="dash-notice-card">
                <?php if (!empty($n['image_path'])): ?>
                    <img src="<?= stu_dash_h($n['image_path']) ?>"
                         alt="<?= stu_dash_h($n['title']) ?>"
                         class="dash-notice-img">
                <?php endif; ?>

                <div class="dash-notice-body">


                    <?php if (!empty($n['button_url'])): ?>
    <a href="<?= stu_dash_h($n['button_url']) ?>" class="dash-notice-title-link">
        <?= stu_dash_h($n['title']) ?>
    </a>
<?php else: ?>
    <h3 class="dash-notice-title">
        <?= stu_dash_h($n['title']) ?>
    </h3>
<?php endif; ?>

<?php if (!empty($n['message'])): ?>
    <p class="dash-notice-text">
        <?= stu_dash_h($n['message']) ?>
    </p>
<?php endif; ?>
                </div>
            </div>
        <?php endforeach; ?>
    </div>
<?php endif; ?>

        <div class="calendar-card">
            <div class="calendar-head">
                <button class="cal-nav" type="button" id="calPrev">
    <i class="bi bi-chevron-left"></i>
</button>

<div class="calendar-title" id="calTitle"><?= stu_dash_h($monthName) ?></div>

<button class="cal-nav" type="button" id="calNext">
    <i class="bi bi-chevron-right"></i>
</button>
            </div>

            <div class="cal-grid" id="calGrid">
                <?php foreach (['Sun','Mon','Tue','Wed','Thu','Fri','Sat'] as $day): ?>
                    <div class="cal-cell cal-head-cell"><?= $day ?></div>
                <?php endforeach; ?>

                <?php for ($i = 0; $i < $firstDay; $i++): ?>
                    <div class="cal-cell cal-other"></div>
                <?php endfor; ?>

                <?php for ($d = 1; $d <= $daysInMonth; $d++): ?>
                    <div class="cal-cell <?= $d === $todayDay ? 'cal-today' : '' ?>">
                        <?= $d ?>
                    </div>
                <?php endfor; ?>
            </div>
        </div>
    </aside>
</div>

<div class="dash-widget-row">
    

    <div class="dash-widget">
        <div class="dash-widget-icon"><i class="bi bi-clipboard-check"></i></div>
        <div class="dash-widget-value"><?= (int)$pendingAssessments ?></div>
        <div class="dash-widget-label">Pending Assessments</div>
    </div>

    <div class="dash-widget">
        <div class="dash-widget-icon"><i class="bi bi-award"></i></div>
        <div class="dash-widget-value"><?= (int)$releasedResults ?></div>
        <div class="dash-widget-label">Released Results</div>
    </div>

    
</div>

<div class="dash-lower-grid">
    <div class="mini-list-card">
        <div class="mini-list-head">
            <h3 class="mini-list-title">Recent Assessments</h3>
            <a href="/elms/student/assessments/assessments.php" class="btn btn-sm btn-outline-primary rounded-pill px-3">
                View All
            </a>
        </div>

        <div class="mini-list-body">
            <?php if ($recentAssessments): ?>
                <?php foreach ($recentAssessments as $a): ?>
                    <?php
                    $due = $a['due_date'] ?? '';
                    $isOverdue = $due && strtotime((string)$due) < time();
                    ?>
                    <div class="activity-row">
                        <div>
                            <div class="activity-title"><?= stu_dash_h($a['title'] ?? 'Assessment') ?></div>
                            <div class="activity-meta">
                                <?= stu_dash_h($a['type'] ?? 'Assessment') ?>
                                <?php if ($due): ?>
                                    · Due <?= stu_dash_h(date('d M Y', strtotime((string)$due))) ?>
                                <?php endif; ?>
                            </div>
                        </div>

                        <span class="badge rounded-pill <?= $isOverdue ? 'status-soft-red' : 'status-soft-blue' ?>">
                            <?= $isOverdue ? 'Overdue' : 'Open' ?>
                        </span>
                    </div>
                <?php endforeach; ?>
            <?php else: ?>
                <div class="empty-simple">No recent assessments found.</div>
            <?php endif; ?>
        </div>
    </div>

    <div class="mini-list-card">
        <div class="mini-list-head">
            <h3 class="mini-list-title">Latest Results</h3>
            <a href="/elms/student/results.php" class="btn btn-sm btn-outline-primary rounded-pill px-3">
                View All
            </a>
        </div>
        

        <div class="mini-list-body">
            <?php if ($recentResults): ?>
                <?php foreach ($recentResults as $r): ?>
                    <div class="activity-row">
                        <div>
                            <div class="activity-title"><?= stu_dash_h($r['title'] ?? 'Assessment') ?></div>
                            <div class="activity-meta">
                                <?php if (!empty($r['updated_at'])): ?>
                                    Released <?= stu_dash_h(date('d M Y', strtotime((string)$r['updated_at']))) ?>
                                <?php else: ?>
                                    Released result
                                <?php endif; ?>
                            </div>
                        </div>

                        <span class="badge rounded-pill status-soft-green">
                            <?= stu_dash_h(($r['grade'] ?? '') ?: (($r['final_score'] ?? '') !== '' ? $r['final_score'] : 'View')) ?>
                        </span>
                    </div>
                <?php endforeach; ?>
            <?php else: ?>
                <div class="empty-simple">No released results yet.</div>
            <?php endif; ?>
            
            
        </div>
    </div>
    <?php if ($dashboardNotices): ?>
<div class="student-notice-bottom">
    <h3 class="student-notice-bottom-title">Recommended Courses</h3>

    <div class="student-notice-bottom-grid">
        <?php foreach ($dashboardNotices as $n): ?>
            <?php $noticeUrl = trim((string)($n['button_url'] ?? '')); ?>

            <a href="<?= $noticeUrl !== '' ? stu_dash_h($noticeUrl) : 'javascript:void(0)' ?>"
               class="student-notice-mini-card">
                <?php if (!empty($n['image_path'])): ?>
                    <img src="<?= stu_dash_h($n['image_path']) ?>" alt="" class="student-notice-mini-img">
                <?php endif; ?>

                <div class="student-notice-mini-body">
                    <div class="student-notice-mini-title">
                        <?= stu_dash_h($n['title'] ?? 'Course') ?>
                    </div>

                    <?php if (!empty($n['message'])): ?>
                        <div class="student-notice-mini-text">
                            <?= stu_dash_h($n['message']) ?>
                        </div>
                    <?php endif; ?>
                </div>
            </a>
        <?php endforeach; ?>
    </div>
</div>
<?php endif; ?>
</div>

<script>
document.addEventListener('DOMContentLoaded', function () {
    const calTitle = document.getElementById('calTitle');
    const calGrid = document.getElementById('calGrid');
    const prevBtn = document.getElementById('calPrev');
    const nextBtn = document.getElementById('calNext');

    if (!calTitle || !calGrid || !prevBtn || !nextBtn) return;

    let current = new Date();
    current.setDate(1);

    const today = new Date();

    function renderCalendar() {
        const year = current.getFullYear();
        const month = current.getMonth();

        calTitle.textContent = current.toLocaleString('en-US', {
            month: 'long',
            year: 'numeric'
        });

        const firstDay = new Date(year, month, 1).getDay();
        const daysInMonth = new Date(year, month + 1, 0).getDate();

        let html = '';

        ['Sun','Mon','Tue','Wed','Thu','Fri','Sat'].forEach(day => {
            html += `<div class="cal-cell cal-head-cell">${day}</div>`;
        });

        for (let i = 0; i < firstDay; i++) {
            html += `<div class="cal-cell cal-other"></div>`;
        }

        for (let d = 1; d <= daysInMonth; d++) {
            const isToday =
                d === today.getDate() &&
                month === today.getMonth() &&
                year === today.getFullYear();

            html += `<div class="cal-cell ${isToday ? 'cal-today' : ''}">${d}</div>`;
        }

        calGrid.innerHTML = html;
    }

    prevBtn.addEventListener('click', function () {
        current.setMonth(current.getMonth() - 1);
        renderCalendar();
    });

    nextBtn.addEventListener('click', function () {
        current.setMonth(current.getMonth() + 1);
        renderCalendar();
    });

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