<?php
declare(strict_types=1);

/*
|--------------------------------------------------------------------------
| SMI Premium Student Home Gateway + Course Dashboard
|--------------------------------------------------------------------------
| dashboard.php
|--------------------------------------------------------------------------
| Mode 1: dashboard.php = Student Home Gateway
| Mode 2: dashboard.php?course_id=ID = Course Control Center
|--------------------------------------------------------------------------
*/

require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/functions.php';
require_once __DIR__ . '/../includes/student-auth.php';

$pdo = db();

requireStudent();

$student = currentStudent($pdo);

if (!$student) {
    studentLogout();
    redirectTo('login.php');
}

$studentId = (int)($student['id'] ?? 0);

if ($studentId <= 0) {
    studentLogout();
    redirectTo('login.php');
}

/*
|--------------------------------------------------------------------------
| Safe PHP 7 Compatible Helpers
|--------------------------------------------------------------------------
*/

if (!function_exists('smi_starts_with')) {
    function smi_starts_with(string $haystack, string $needle): bool
    {
        return $needle === '' || strpos($haystack, $needle) === 0;
    }
}

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

if (!function_exists('safeCount')) {
    function safeCount(PDO $pdo, string $sql, array $params = []): int
    {
        try {
            $stmt = $pdo->prepare($sql);
            $stmt->execute($params);
            return (int)$stmt->fetchColumn();
        } catch (Throwable $e) {
            return 0;
        }
    }
}

if (!function_exists('safeOne')) {
    function safeOne(PDO $pdo, string $sql, array $params = []): ?array
    {
        try {
            $stmt = $pdo->prepare($sql);
            $stmt->execute($params);
            $row = $stmt->fetch(PDO::FETCH_ASSOC);
            return $row ?: null;
        } catch (Throwable $e) {
            return null;
        }
    }
}

if (!function_exists('safeAll')) {
    function safeAll(PDO $pdo, string $sql, array $params = []): array
    {
        try {
            $stmt = $pdo->prepare($sql);
            $stmt->execute($params);
            return $stmt->fetchAll(PDO::FETCH_ASSOC) ?: [];
        } catch (Throwable $e) {
            return [];
        }
    }
}

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

if (!function_exists('columnExists')) {
    function columnExists(PDO $pdo, string $table, string $column): bool
    {
        try {
            $stmt = $pdo->prepare("
                SELECT COUNT(*)
                FROM information_schema.COLUMNS
                WHERE TABLE_SCHEMA = DATABASE()
                  AND TABLE_NAME = ?
                  AND COLUMN_NAME = ?
            ");
            $stmt->execute([$table, $column]);
            return (int)$stmt->fetchColumn() > 0;
        } catch (Throwable $e) {
            return false;
        }
    }
}

if (!function_exists('safeDate')) {
    function safeDate($date, string $fallback = 'N/A'): string
    {
        if (empty($date) || $date === '0000-00-00' || $date === '0000-00-00 00:00:00') {
            return $fallback;
        }

        $time = strtotime((string)$date);

        return $time ? date('M d, Y', $time) : $fallback;
    }
}

if (!function_exists('safeUcfirst')) {
    function safeUcfirst($value, string $fallback = 'General'): string
    {
        $value = trim((string)($value ?? ''));

        if ($value === '') {
            return $fallback;
        }

        return ucfirst($value);
    }
}

if (!function_exists('safePercent')) {
    function safePercent($value): int
    {
        $value = (int)($value ?? 0);
        return max(0, min(100, $value));
    }
}

if (!function_exists('studentProfileImage')) {
    function studentProfileImage(array $student): string
    {
        $image = trim((string)($student['profile_image'] ?? ''));

        if ($image === '') {
            return '';
        }

        if (smi_starts_with($image, 'http://') || smi_starts_with($image, 'https://')) {
            return $image;
        }

        if (smi_starts_with($image, 'uploads/')) {
            return '../' . ltrim($image, '/');
        }

        return '../uploads/students/' . ltrim($image, '/');
    }
}

/*
|--------------------------------------------------------------------------
| Language
|--------------------------------------------------------------------------
*/

if (isset($_GET['lang'])) {
    $requestedLang = strtolower(trim((string)$_GET['lang']));

    if (in_array($requestedLang, ['en', 'ar'], true)) {
        $_SESSION['student_lang'] = $requestedLang;
    }
}

$lang = (string)($_SESSION['student_lang'] ?? $_SESSION['lang'] ?? 'en');
$lang = in_array($lang, ['en', 'ar'], true) ? $lang : 'en';

$_SESSION['student_lang'] = $lang;

$dir = $lang === 'ar' ? 'rtl' : 'ltr';

/*
|--------------------------------------------------------------------------
| Translations
|--------------------------------------------------------------------------
*/

$translations = [
    'en' => [
        'page_title' => 'SMI Student Gateway',
        'student_gateway' => 'Student Gateway',
        'home_gateway' => 'Student Gateway',
        'course_dashboard' => 'Course Dashboard',
        'subtitle' => 'Your academic identity and learning control center',
        'welcome' => 'Welcome Back',
        'student_code' => 'Student Code',
        'student_card' => 'Student Card',
        'secondary_level' => 'Secondary Level',
        'core_level' => 'Core Level',
        'courses' => 'Courses',
        'current_course' => 'Current Core Course',
        'previous_courses' => 'Archived Courses',
        'no_archived_courses' => 'No archived courses yet.',
        'attendance' => 'Attendance',
        'homework' => 'Homework',
        'exams' => 'Exams',
        'materials' => 'Materials',
        'sessions' => 'Sessions',
        'grades' => 'Grades',
        'reports' => 'Reports',
        'certificates' => 'Certificates',
        'shadowing' => 'Shadowing',
        'obstacles' => 'Obstacles',
        'progress' => 'Progress',
        'notifications' => 'Notifications',
        'profile' => 'Profile',
        'logout' => 'Logout',
        'teacher' => 'Teacher',
        'status' => 'Status',
        'course_code' => 'Course Code',
        'start_date' => 'Start Date',
        'end_date' => 'End Date',
        'course_progress' => 'Course Progress',
        'enter_course_dashboard' => 'Enter Course Dashboard',
        'switch_to_home' => 'Back to Student Home',
        'join_course' => 'Join Course',
        'view_available_courses' => 'View Available Courses',
        'contact_admin' => 'Contact Admin',
        'secondary_periods' => 'Secondary Sessions',
        'go_secondary' => 'Go to Secondary Periods',
        'welcome_cards' => 'Your SMI Journey',
        'identity_card' => 'Academic Identity',
        'identity_desc' => 'Your official student information inside SMI.',
        'core_periods' => 'Core Periods',
        'core_desc' => 'Your structured academic courses, exams, homework, grades, and certificates.',
        'secondary_training' => 'Secondary Sessions',
        'secondary_desc' => 'Daily speaking practice and fluency development sessions.',
        'student_journey' => 'Student Journey',
        'journey_desc' => 'Track your progress from learning to confidence and mastery.',
        'no_current_course' => 'You are not currently enrolled in an active core course.',
        'registration_options' => 'Registration Options',
        'course_center' => 'Course Control Center',
        'course_only_hint' => 'All statistics and links below belong only to this selected course.',
        'academic_snapshot' => 'Academic Snapshot',
        'priority' => 'Your Next Priority',
        'priority_done' => 'You are clear for now. Keep your progress stable.',
        'priority_homework' => 'Submit your nearest pending homework.',
        'priority_exam' => 'Prepare for your next exam.',
        'priority_session' => 'Join your next scheduled session.',
        'quick_actions' => 'Quick Actions',
        'upcoming' => 'Upcoming Activities',
        'timeline' => 'Academic Timeline',
        'attendance_rate' => 'Attendance Rate',
        'pending_homework' => 'Pending Homework',
        'upcoming_exams' => 'Upcoming Exams',
        'available_materials' => 'Available Materials',
        'final_grade' => 'Final Grade',
        'certificates_count' => 'Certificates',
        'next_session' => 'Next Session',
        'next_exam' => 'Next Exam',
        'next_homework' => 'Nearest Homework',
        'no_exam' => 'No upcoming exams for this course yet.',
        'no_homework' => 'Great! You have no pending homework for this course.',
        'no_session' => 'No upcoming sessions for this course yet.',
        'open' => 'Open',
        'home' => 'Home',
        'more' => 'More',
        'motivational_text' => 'Welcome to SMI • Your progress starts today • Build your future step by step • Keep going • We are proud of your journey • Learn with confidence • Every session makes you stronger •',
    ],

    'ar' => [
        'page_title' => 'بوابة الطالب - SMI',
        'student_gateway' => 'بوابة الطالب',
        'home_gateway' => 'واجهة الطالب',
        'course_dashboard' => 'لوحة الكورس',
        'subtitle' => 'هويتك الأكاديمية ومركز التحكم ',
        'welcome' => 'مرحبًا بعودتك',
        'student_code' => 'كود الطالب',
        'student_card' => 'رقم بطاقة الطالب',
        'secondary_level' => 'مستوى الفترات الثانوية',
        'core_level' => 'مستوى الفترات الأساسية',
        'courses' => 'الكورسات',
        'current_course' => 'الكورس الأساسي الحالي',
        'previous_courses' => 'الكورسات السابقة المؤرشفة',
        'no_archived_courses' => 'لا توجد كورسات مؤرشفة حتى الآن.',
        'attendance' => 'الحضور',
        'homework' => 'الواجبات',
        'exams' => 'الاختبارات',
        'materials' => 'المواد',
        'sessions' => 'الحصص',
        'grades' => 'الدرجات',
        'reports' => 'التقارير',
        'certificates' => 'الشهادات',
        'shadowing' => 'الشادوينج',
        'obstacles' => 'العوائق',
        'progress' => 'التقدم',
        'notifications' => 'الإشعارات',
        'profile' => 'الملف الشخصي',
        'logout' => 'الخروج',
        'teacher' => 'المعلم',
        'status' => 'الحالة',
        'course_code' => 'كود الكورس',
        'start_date' => 'تاريخ البداية',
        'end_date' => 'تاريخ النهاية',
        'course_progress' => 'تقدم الكورس',
        'enter_course_dashboard' => 'دخول لوحة الكورس',
        'switch_to_home' => 'العودة للواجهة الرئيسية',
        'join_course' => 'الانضمام لكورس',
        'view_available_courses' => 'عرض الكورسات المتاحة',
        'contact_admin' => 'التواصل مع الإدارة',
        'secondary_periods' => 'التدريبات الثانوية',
        'go_secondary' => 'الانتقال للفترات الثانوية',
        'welcome_cards' => 'رحلتك داخل SMI',
        'identity_card' => 'هويتك الأكاديمية',
        'identity_desc' => 'بياناتك الرسمية كطالب داخل منصة SMI.',
        'core_periods' => 'الفترات الأساسية',
        'core_desc' => 'كورساتك الأكاديمية، الاختبارات، الواجبات، الدرجات، والشهادات.',
        'secondary_training' => 'التدريبات الثانوية',
        'secondary_desc' => 'تدريبات يومية للمحادثة وتطوير الطلاقة والثقة.',
        'student_journey' => 'رحلة الطالب',
        'journey_desc' => 'تابع تقدمك من التعلم إلى الثقة والإتقان.',
        'no_current_course' => 'أنت غير مسجل حاليًا في كورس أساسي نشط.',
        'registration_options' => 'خيارات التسجيل',
        'course_center' => 'مركز التحكم بالكورس',
        'course_only_hint' => 'كل الإحصائيات والروابط بالأسفل خاصة بهذا الكورس فقط.',
        'academic_snapshot' => 'لمحة أكاديمية',
        'priority' => 'أولويتك الآن',
        'priority_done' => 'أمورك مستقرة الآن. حافظ على تقدمك.',
        'priority_homework' => 'قم بتسليم أقرب واجب معلق.',
        'priority_exam' => 'استعد للاختبار القادم.',
        'priority_session' => 'استعد لحضور الحصة القادمة.',
        'quick_actions' => 'الإجراءات السريعة',
        'upcoming' => 'الأنشطة القادمة',
        'timeline' => 'المسار الأكاديمي',
        'attendance_rate' => 'نسبة الحضور',
        'pending_homework' => 'واجبات معلقة',
        'upcoming_exams' => 'اختبارات قادمة',
        'available_materials' => 'المواد المتاحة',
        'final_grade' => 'الدرجة النهائية',
        'certificates_count' => 'الشهادات',
        'next_session' => 'الحصة القادمة',
        'next_exam' => 'الاختبار القادم',
        'next_homework' => 'أقرب واجب',
        'no_exam' => 'لا توجد اختبارات قادمة لهذا الكورس حتى الآن.',
        'no_homework' => 'ممتاز! لا توجد واجبات معلقة لهذا الكورس.',
        'no_session' => 'لا توجد حصص قادمة لهذا الكورس حتى الآن.',
        'open' => 'فتح',
        'home' => 'الرئيسية',
        'more' => 'المزيد',
        'motivational_text' => 'مرحبًا بك في SMI • تقدمك يبدأ اليوم • أنت تبني مستقبلك خطوة بخطوة • استمر ولا تتوقف • نحن فخورون برحلتك • تعلّم بثقة • كل حصة تجعلك أقوى •',
    ],
];

$tr = $translations[$lang];

/*
|--------------------------------------------------------------------------
| Student Basic Data
|--------------------------------------------------------------------------
*/

$studentName = (string)($student['full_name'] ?? 'Student');
$studentCode = (string)($student['student_code'] ?? 'N/A');

$studentCardNumber = (string)(
    $student['student_card_number']
    ?? $student['student_card']
    ?? $student['card_number']
    ?? 'N/A'
);

$secondaryLevel = safeUcfirst(
    $student['final_level']
    ?? $student['secondary_level']
    ?? $student['level']
    ?? 'General'
);

$profileImage = studentProfileImage($student);

/*
|--------------------------------------------------------------------------
| Enrollment Status Groups
|--------------------------------------------------------------------------
*/

$activeStatuses = [
    'active',
    'approved',
    'enrolled',
];

$archivedStatuses = [
    'completed',
    'archived',
    'finished',
    'inactive',
];

/*
|--------------------------------------------------------------------------
| Important URLs
|--------------------------------------------------------------------------
*/

$secondaryUrl = '../smi-secondary-training/student/dashboard.php';
$joinCourseUrl = 'join-course.php';
$availableCoursesUrl = 'join-course.php';
$contactAdminUrl = 'notifications.php';




/*
|--------------------------------------------------------------------------
| Course Helper Functions
|--------------------------------------------------------------------------
*/

if (!function_exists('isStudentEnrolledInCourse')) {

    function isStudentEnrolledInCourse(
        PDO $pdo,
        int $studentId,
        int $courseId,
        array $statuses
    ): bool {

        if (
            $studentId <= 0 ||
            $courseId <= 0 ||
            !tableExists($pdo, 'core_course_students')
        ) {
            return false;
        }

        $placeholders = implode(
            ',',
            array_fill(0, count($statuses), '?')
        );

        $params = array_merge(
            [$studentId, $courseId],
            $statuses
        );

        return safeCount(
            $pdo,
            "
            SELECT COUNT(*)
            FROM core_course_students
            WHERE student_id = ?
              AND course_id = ?
              AND status IN ($placeholders)
            ",
            $params
        ) > 0;
    }
}

if (!function_exists('getTeacherName')) {

    function getTeacherName(PDO $pdo, ?int $teacherId): string
    {
        if (
            !$teacherId ||
            $teacherId <= 0 ||
            !tableExists($pdo, 'core_teachers')
        ) {
            return 'N/A';
        }

        $nameColumn = null;

        if (columnExists($pdo, 'core_teachers', 'full_name')) {
            $nameColumn = 'full_name';
        }

        elseif (columnExists($pdo, 'core_teachers', 'name')) {
            $nameColumn = 'name';
        }

        if (!$nameColumn) {
            return 'N/A';
        }

        $row = safeOne(
            $pdo,
            "
            SELECT {$nameColumn} AS teacher_name
            FROM core_teachers
            WHERE id = ?
            LIMIT 1
            ",
            [$teacherId]
        );

        return (string)($row['teacher_name'] ?? 'N/A');
    }
}

if (!function_exists('calculateProgress')) {

    function calculateProgress(
        ?string $startDate,
        ?string $endDate
    ): int {

        if (
            empty($startDate) ||
            empty($endDate)
        ) {
            return 0;
        }

        $start = strtotime($startDate);
        $end = strtotime($endDate);
        $now = time();

        if (
            !$start ||
            !$end ||
            $end <= $start
        ) {
            return 0;
        }

        if ($now <= $start) {
            return 0;
        }

        if ($now >= $end) {
            return 100;
        }

        return safePercent(
            (int)round(
                (($now - $start) / ($end - $start)) * 100
            )
        );
    }
}

/*
|--------------------------------------------------------------------------
| Get Student Courses
|--------------------------------------------------------------------------
*/

if (!function_exists('getStudentCourses')) {

    function getStudentCourses(
        PDO $pdo,
        int $studentId,
        array $statuses
    ): array {

        if (
            $studentId <= 0 ||
            !tableExists($pdo, 'core_course_students') ||
            !tableExists($pdo, 'core_courses')
        ) {
            return [];
        }

        $columns = [
            'c.id',
            'c.title',
        ];

        $optionalColumns = [
            'course_code',
            'code',
            'level',
            'teacher_id',
            'start_date',
            'end_date',
            'status',
            'description',
            'created_at',
        ];

        foreach ($optionalColumns as $column) {

            if (columnExists($pdo, 'core_courses', $column)) {
                $columns[] = "c.$column";
            }
        }

        $columns[] = 'cs.status AS enrollment_status';

        if (columnExists($pdo, 'core_course_students', 'joined_at')) {
            $columns[] = 'cs.joined_at';
        }

        $select = implode(",\n", $columns);

        $placeholders = implode(
            ',',
            array_fill(0, count($statuses), '?')
        );

        $rows = safeAll(
            $pdo,
            "
            SELECT
                $select
            FROM core_course_students cs
            INNER JOIN core_courses c
                ON c.id = cs.course_id
            WHERE cs.student_id = ?
              AND cs.status IN ($placeholders)
            ORDER BY cs.id DESC
            ",
            array_merge([$studentId], $statuses)
        );

        foreach ($rows as &$course) {

            $course['teacher_name'] = getTeacherName(
                $pdo,
                (int)($course['teacher_id'] ?? 0)
            );

            $course['display_code'] = (string)(
                $course['course_code']
                ?? $course['code']
                ?? ('COURSE-' . (int)($course['id'] ?? 0))
            );

            $course['progress_percent'] = calculateProgress(
                $course['start_date'] ?? null,
                $course['end_date'] ?? null
            );
        }

        unset($course);

        return $rows;
    }
}

/*
|--------------------------------------------------------------------------
| Load Courses
|--------------------------------------------------------------------------
*/

$activeCourses = getStudentCourses(
    $pdo,
    $studentId,
    $activeStatuses
);

$archivedCourses = getStudentCourses(
    $pdo,
    $studentId,
    $archivedStatuses
);

/*
|--------------------------------------------------------------------------
| Current Active Course
|--------------------------------------------------------------------------
*/

$currentCourse = null;

if (!empty($activeCourses)) {
    $currentCourse = $activeCourses[0];
}

/*
|--------------------------------------------------------------------------
| Core Level From Latest Course
|--------------------------------------------------------------------------
*/

$coreLevel = 'General';

if ($currentCourse) {

    $coreLevel = safeUcfirst(
        $currentCourse['level']
        ?? 'General'
    );
}

/*
|--------------------------------------------------------------------------
| Dashboard Mode
|--------------------------------------------------------------------------
| Mode 1 = Home Gateway
| Mode 2 = Course Dashboard
|--------------------------------------------------------------------------
*/

$selectedCourseId = 0;
$selectedCourse = null;

if (isset($_GET['course_id'])) {

    $requestedCourseId = (int)$_GET['course_id'];

    if (
        $requestedCourseId > 0 &&
        isStudentEnrolledInCourse(
            $pdo,
            $studentId,
            $requestedCourseId,
            $activeStatuses
        )
    ) {

        $selectedCourseId = $requestedCourseId;

        foreach ($activeCourses as $course) {

            if (
                (int)($course['id'] ?? 0)
                ===
                $selectedCourseId
            ) {

                $selectedCourse = $course;
                break;
            }
        }
    }
}

/*
|--------------------------------------------------------------------------
| Home Gateway Stats
|--------------------------------------------------------------------------
*/

$totalCourses = count($activeCourses);
$totalArchivedCourses = count($archivedCourses);

$totalAttendance = 0;
$totalHomework = 0;
$totalExams = 0;
$totalCertificates = 0;

if (tableExists($pdo, 'core_attendance')) {

    $totalAttendance = safeCount(
        $pdo,
        "
        SELECT COUNT(*)
        FROM core_attendance
        WHERE student_id = ?
          AND status IN ('present','late')
        ",
        [$studentId]
    );
}

if (tableExists($pdo, 'core_homework_submissions')) {

    $totalHomework = safeCount(
        $pdo,
        "
        SELECT COUNT(*)
        FROM core_homework_submissions
        WHERE student_id = ?
        ",
        [$studentId]
    );
}

if (tableExists($pdo, 'core_exam_attempts')) {

    $totalExams = safeCount(
        $pdo,
        "
        SELECT COUNT(*)
        FROM core_exam_attempts
        WHERE student_id = ?
        ",
        [$studentId]
    );
}

if (tableExists($pdo, 'core_certificates')) {

    $totalCertificates = safeCount(
        $pdo,
        "
        SELECT COUNT(*)
        FROM core_certificates
        WHERE student_id = ?
        ",
        [$studentId]
    );
}

/*
|--------------------------------------------------------------------------
| Motivational Messages
|--------------------------------------------------------------------------
*/

$motivationalMessages = [

    [
        'ar' => 'كل خطوة صغيرة اليوم تبني مستقبلك الكبير غدًا.',
        'en' => 'Every small step today builds your greater future tomorrow.'
    ],

    [
        'ar' => 'الاستمرارية أهم من السرعة.',
        'en' => 'Consistency is more important than speed.'
    ],

    [
        'ar' => 'أنت لا تتعلم الإنجليزية فقط، بل تبني نسخة أقوى من نفسك.',
        'en' => 'You are not only learning English, you are building a stronger version of yourself.'
    ],

    [
        'ar' => 'الثقة تبدأ من المحاولة.',
        'en' => 'Confidence begins with trying.'
    ],

    [
        'ar' => 'كل حصة تقربك من مستوى جديد.',
        'en' => 'Every session brings you closer to a new level.'
    ],
];

$randomMotivation = $motivationalMessages[
    array_rand($motivationalMessages)
];




/*
|--------------------------------------------------------------------------
| Course Dashboard Default Values
|--------------------------------------------------------------------------
*/

$courseStats = [
    'attendance_rate' => 0,
    'pending_homework' => 0,
    'upcoming_exams' => 0,
    'materials' => 0,
    'final_grade' => '--',
    'certificates' => 0,
];

$nextSession = null;
$nextExam = null;
$nextHomework = null;

$priorityType = 'done';
$priorityText = $tr['priority_done'];
$priorityLink = $selectedCourseId > 0
    ? 'dashboard.php?course_id=' . (int)$selectedCourseId
    : 'dashboard.php';

/*
|--------------------------------------------------------------------------
| Load Selected Course Data
|--------------------------------------------------------------------------
*/

if ($selectedCourseId > 0 && $selectedCourse) {

    /*
    |--------------------------------------------------------------------------
    | Attendance Rate
    |--------------------------------------------------------------------------
    */

    $attendanceTotal = 0;
    $attendancePresent = 0;

    if (tableExists($pdo, 'core_attendance')) {

        if (columnExists($pdo, 'core_attendance', 'course_id')) {

            $attendanceTotal = safeCount(
                $pdo,
                "
                SELECT COUNT(*)
                FROM core_attendance
                WHERE student_id = ?
                  AND course_id = ?
                ",
                [
                    $studentId,
                    $selectedCourseId
                ]
            );

            $attendancePresent = safeCount(
                $pdo,
                "
                SELECT COUNT(*)
                FROM core_attendance
                WHERE student_id = ?
                  AND course_id = ?
                  AND status IN ('present','late')
                ",
                [
                    $studentId,
                    $selectedCourseId
                ]
            );

        } elseif (
            columnExists($pdo, 'core_attendance', 'attendance_session_id') &&
            tableExists($pdo, 'core_attendance_sessions') &&
            columnExists($pdo, 'core_attendance_sessions', 'course_id')
        ) {

            $attendanceTotal = safeCount(
                $pdo,
                "
                SELECT COUNT(*)
                FROM core_attendance a
                INNER JOIN core_attendance_sessions s
                    ON s.id = a.attendance_session_id
                WHERE a.student_id = ?
                  AND s.course_id = ?
                ",
                [
                    $studentId,
                    $selectedCourseId
                ]
            );

            $attendancePresent = safeCount(
                $pdo,
                "
                SELECT COUNT(*)
                FROM core_attendance a
                INNER JOIN core_attendance_sessions s
                    ON s.id = a.attendance_session_id
                WHERE a.student_id = ?
                  AND s.course_id = ?
                  AND a.status IN ('present','late')
                ",
                [
                    $studentId,
                    $selectedCourseId
                ]
            );
        }
    }

    $courseStats['attendance_rate'] = $attendanceTotal > 0
        ? safePercent((int)round(($attendancePresent / $attendanceTotal) * 100))
        : 0;

    /*
    |--------------------------------------------------------------------------
    | Pending Homework
    |--------------------------------------------------------------------------
    */

    if (
        tableExists($pdo, 'core_homework') &&
        columnExists($pdo, 'core_homework', 'course_id')
    ) {
        $pendingSql = "
            SELECT COUNT(*)
            FROM core_homework h
            WHERE h.course_id = ?
        ";

        $pendingParams = [
            $selectedCourseId
        ];

        if (
            tableExists($pdo, 'core_homework_submissions') &&
            columnExists($pdo, 'core_homework_submissions', 'homework_id')
        ) {
            $pendingSql .= "
                AND h.id NOT IN (
                    SELECT homework_id
                    FROM core_homework_submissions
                    WHERE student_id = ?
                )
            ";

            $pendingParams[] = $studentId;
        }

        $courseStats['pending_homework'] = safeCount(
            $pdo,
            $pendingSql,
            $pendingParams
        );
    }

    /*
    |--------------------------------------------------------------------------
    | Upcoming Exams Count
    |--------------------------------------------------------------------------
    */

    if (
        tableExists($pdo, 'core_exams') &&
        columnExists($pdo, 'core_exams', 'course_id')
    ) {
        $examSql = "
            SELECT COUNT(*)
            FROM core_exams
            WHERE course_id = ?
        ";

        $examParams = [
            $selectedCourseId
        ];

        if (columnExists($pdo, 'core_exams', 'exam_date')) {
            $examSql .= "
                AND (
                    exam_date >= CURDATE()
                    OR exam_date IS NULL
                )
            ";
        }

        if (columnExists($pdo, 'core_exams', 'status')) {
            $examSql .= "
                AND status IN ('published','active','open','scheduled')
            ";
        }

        $courseStats['upcoming_exams'] = safeCount(
            $pdo,
            $examSql,
            $examParams
        );
    }

    /*
    |--------------------------------------------------------------------------
    | Materials Count
    |--------------------------------------------------------------------------
    */

    if (
        tableExists($pdo, 'core_materials') &&
        columnExists($pdo, 'core_materials', 'course_id')
    ) {
        $courseStats['materials'] = safeCount(
            $pdo,
            "
            SELECT COUNT(*)
            FROM core_materials
            WHERE course_id = ?
            ",
            [$selectedCourseId]
        );
    }

    /*
    |--------------------------------------------------------------------------
    | Final Grade
    |--------------------------------------------------------------------------
    */

    if (
        tableExists($pdo, 'core_final_grades') &&
        columnExists($pdo, 'core_final_grades', 'course_id')
    ) {
        $gradeRow = safeOne(
            $pdo,
            "
            SELECT *
            FROM core_final_grades
            WHERE student_id = ?
              AND course_id = ?
            ORDER BY id DESC
            LIMIT 1
            ",
            [
                $studentId,
                $selectedCourseId
            ]
        );

        if ($gradeRow) {
            $courseStats['final_grade'] = (string)(
                $gradeRow['letter_grade']
                ?? $gradeRow['grade']
                ?? $gradeRow['final_grade']
                ?? '--'
            );
        }
    }

    /*
    |--------------------------------------------------------------------------
    | Certificates Count
    |--------------------------------------------------------------------------
    */

    if (
        tableExists($pdo, 'core_certificates') &&
        columnExists($pdo, 'core_certificates', 'course_id')
    ) {
        $courseStats['certificates'] = safeCount(
            $pdo,
            "
            SELECT COUNT(*)
            FROM core_certificates
            WHERE student_id = ?
              AND course_id = ?
            ",
            [
                $studentId,
                $selectedCourseId
            ]
        );
    }

    /*
    |--------------------------------------------------------------------------
    | Next Session
    |--------------------------------------------------------------------------
    */

    if (
        tableExists($pdo, 'core_sessions') &&
        columnExists($pdo, 'core_sessions', 'course_id')
    ) {
        $sessionSql = "
            SELECT *
            FROM core_sessions
            WHERE course_id = ?
        ";

        $sessionParams = [
            $selectedCourseId
        ];

        if (columnExists($pdo, 'core_sessions', 'session_date')) {
            $sessionSql .= "
                AND (
                    session_date >= CURDATE()
                    OR session_date IS NULL
                )
            ";
        }

        $sessionSql .= "
            ORDER BY
                " . (
                    columnExists($pdo, 'core_sessions', 'session_date')
                    ? "session_date ASC,"
                    : ""
                ) . "
                id ASC
            LIMIT 1
        ";

        $nextSession = safeOne(
            $pdo,
            $sessionSql,
            $sessionParams
        );
    }

    /*
    |--------------------------------------------------------------------------
    | Next Exam
    |--------------------------------------------------------------------------
    */

    if (
        tableExists($pdo, 'core_exams') &&
        columnExists($pdo, 'core_exams', 'course_id')
    ) {
        $nextExamSql = "
            SELECT *
            FROM core_exams
            WHERE course_id = ?
        ";

        $nextExamParams = [
            $selectedCourseId
        ];

        if (columnExists($pdo, 'core_exams', 'exam_date')) {
            $nextExamSql .= "
                AND (
                    exam_date >= CURDATE()
                    OR exam_date IS NULL
                )
            ";
        }

        if (columnExists($pdo, 'core_exams', 'status')) {
            $nextExamSql .= "
                AND status IN ('published','active','open','scheduled')
            ";
        }

        $nextExamSql .= "
            ORDER BY
                " . (
                    columnExists($pdo, 'core_exams', 'exam_date')
                    ? "exam_date ASC,"
                    : ""
                ) . "
                id ASC
            LIMIT 1
        ";

        $nextExam = safeOne(
            $pdo,
            $nextExamSql,
            $nextExamParams
        );
    }

    /*
    |--------------------------------------------------------------------------
    | Next Homework
    |--------------------------------------------------------------------------
    */

    if (
        tableExists($pdo, 'core_homework') &&
        columnExists($pdo, 'core_homework', 'course_id')
    ) {
        $homeworkSql = "
            SELECT *
            FROM core_homework h
            WHERE h.course_id = ?
        ";

        $homeworkParams = [
            $selectedCourseId
        ];

        if (columnExists($pdo, 'core_homework', 'due_date')) {
            $homeworkSql .= "
                AND (
                    h.due_date >= CURDATE()
                    OR h.due_date IS NULL
                )
            ";
        }

        if (
            tableExists($pdo, 'core_homework_submissions') &&
            columnExists($pdo, 'core_homework_submissions', 'homework_id')
        ) {
            $homeworkSql .= "
                AND h.id NOT IN (
                    SELECT homework_id
                    FROM core_homework_submissions
                    WHERE student_id = ?
                )
            ";

            $homeworkParams[] = $studentId;
        }

        $homeworkSql .= "
            ORDER BY
                " . (
                    columnExists($pdo, 'core_homework', 'due_date')
                    ? "h.due_date ASC,"
                    : ""
                ) . "
                h.id ASC
            LIMIT 1
        ";

        $nextHomework = safeOne(
            $pdo,
            $homeworkSql,
            $homeworkParams
        );
    }

    /*
    |--------------------------------------------------------------------------
    | Priority Logic
    |--------------------------------------------------------------------------
    */

    if ($nextHomework) {
        $priorityType = 'homework';
        $priorityText = $tr['priority_homework'];
        $priorityLink = 'homework.php?course_id=' . (int)$selectedCourseId;
    } elseif ($nextExam) {
        $priorityType = 'exam';
        $priorityText = $tr['priority_exam'];
        $priorityLink = 'exams.php?course_id=' . (int)$selectedCourseId;
    } elseif ($nextSession) {
        $priorityType = 'session';
        $priorityText = $tr['priority_session'];
        $priorityLink = 'sessions.php?course_id=' . (int)$selectedCourseId;
    } else {
        $priorityType = 'done';
        $priorityText = $tr['priority_done'];
        $priorityLink = 'dashboard.php?course_id=' . (int)$selectedCourseId;
    }
}

/*
|--------------------------------------------------------------------------
| Course Action Cards
|--------------------------------------------------------------------------
*/

$courseActions = [];

if ($selectedCourseId > 0 && $selectedCourse) {
    $courseActions = [
        ['icon' => '✅', 'label' => $tr['attendance'], 'url' => 'attendance.php?course_id=' . (int)$selectedCourseId, 'desc' => 'Course attendance record'],
        ['icon' => '📘', 'label' => $tr['homework'], 'url' => 'homework.php?course_id=' . (int)$selectedCourseId, 'desc' => 'Assignments and submissions'],
        ['icon' => '📝', 'label' => $tr['exams'], 'url' => 'exams.php?course_id=' . (int)$selectedCourseId, 'desc' => 'Tests and results'],
        ['icon' => '📂', 'label' => $tr['materials'], 'url' => 'materials.php?course_id=' . (int)$selectedCourseId, 'desc' => 'Books and files'],
        ['icon' => '🎥', 'label' => $tr['sessions'], 'url' => 'sessions.php?course_id=' . (int)$selectedCourseId, 'desc' => 'Live lessons and links'],
        ['icon' => '🏆', 'label' => $tr['grades'], 'url' => 'grades.php?course_id=' . (int)$selectedCourseId, 'desc' => 'Scores and final grades'],
        ['icon' => '📈', 'label' => $tr['progress'], 'url' => 'progress.php?course_id=' . (int)$selectedCourseId, 'desc' => 'Academic progress'],
        ['icon' => '📄', 'label' => $tr['reports'], 'url' => 'reports.php?course_id=' . (int)$selectedCourseId, 'desc' => 'Course reports'],
        ['icon' => '🎓', 'label' => $tr['certificates'], 'url' => 'certificates.php?course_id=' . (int)$selectedCourseId, 'desc' => 'Course certificates'],
        ['icon' => '🎧', 'label' => $tr['shadowing'], 'url' => 'shadowing.php?course_id=' . (int)$selectedCourseId, 'desc' => 'Shadowing practice'],
        ['icon' => '🧩', 'label' => $tr['obstacles'], 'url' => 'obstacles.php?course_id=' . (int)$selectedCourseId, 'desc' => 'Obstacle tasks'],
    ];
}

?>


<!DOCTYPE html>
<html lang="<?php echo e($lang); ?>" dir="<?php echo e($dir); ?>">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title><?php echo e($tr['page_title']); ?></title>

<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800;900&family=Tajawal:wght@400;500;700;800;900&display=swap" rel="stylesheet">

<style>
:root{
    --blue:#2563eb;
    --blue-dark:#1d4ed8;
    --indigo:#4338ca;
    --purple:#6d28d9;
    --violet:#4c1d95;
    --green:#059669;
    --orange:#d97706;
    --red:#dc2626;
    --bg:#f6f8fc;
    --card:#ffffff;
    --text:#0f172a;
    --muted:#64748b;
    --line:#e2e8f0;
    --soft:#eff6ff;
    --shadow:0 18px 45px rgba(15,23,42,.08);
    --shadow-lg:0 28px 70px rgba(37,99,235,.25);
}

*{
    box-sizing:border-box;
    margin:0;
    padding:0;
}

body{
    min-height:100vh;
    font-family:<?php echo $lang === 'ar' ? "'Tajawal'" : "'Inter'"; ?>,sans-serif;
    background:
        radial-gradient(circle at top left,rgba(37,99,235,.12),transparent 34%),
        radial-gradient(circle at top right,rgba(109,40,217,.10),transparent 34%),
        linear-gradient(135deg,#fbfdff,#eef3fb);
    color:var(--text);
    padding-bottom:110px;
}

a{
    color:inherit;
    text-decoration:none;
}

.app-shell{
    width:100%;
    max-width:1180px;
    margin:auto;
    padding:18px;
}

.topbar{
    position:sticky;
    top:0;
    z-index:50;
    display:flex;
    align-items:center;
    justify-content:space-between;
    gap:14px;
    padding:12px 0;
    background:rgba(246,248,252,.88);
    backdrop-filter:blur(18px);
}

.brand{
    display:flex;
    align-items:center;
    gap:12px;
    min-width:0;
}

.logo{
    width:60px;
    height:60px;
    border-radius:22px;
    background:linear-gradient(135deg,var(--blue),var(--purple));
    color:#fff;
    display:flex;
    align-items:center;
    justify-content:center;
    font-weight:900;
    box-shadow:0 14px 35px rgba(37,99,235,.28);
    flex-shrink:0;
}

.brand h1{
    font-size:19px;
    font-weight:900;
    letter-spacing:-.3px;
}

.brand p{
    color:var(--muted);
    font-size:12px;
    font-weight:800;
    margin-top:4px;
}

.lang-switch{
    display:flex;
    gap:7px;
    flex-shrink:0;
}

.lang-switch a{
    background:#fff;
    border:1px solid var(--line);
    border-radius:999px;
    padding:9px 12px;
    font-size:12px;
    font-weight:900;
    box-shadow:0 8px 20px rgba(15,23,42,.05);
}

.hero{
    margin-top:14px;
    background:
        radial-gradient(circle at 10% 10%,rgba(255,255,255,.24),transparent 28%),
        radial-gradient(circle at 90% 18%,rgba(14,165,233,.18),transparent 30%),
        linear-gradient(135deg,#1e3a8a,#2563eb,#4c1d95);
    color:#fff;
    border-radius:34px;
    padding:26px;
    box-shadow:var(--shadow-lg);
    position:relative;
    overflow:hidden;
}

.hero::after{
    content:"SMI";
    position:absolute;
    right:25px;
    bottom:-22px;
    color:rgba(255,255,255,.08);
    font-size:96px;
    font-weight:900;
    letter-spacing:-4px;
}

html[dir="rtl"] .hero::after{
    right:auto;
    left:25px;
}

.hero-content{
    position:relative;
    z-index:2;
}

.hero-top{
    display:flex;
    justify-content:space-between;
    align-items:flex-start;
    gap:16px;
}

.hero small{
    color:#dbeafe;
    font-size:12px;
    font-weight:900;
}

.hero h2{
    font-size:32px;
    margin-top:8px;
    font-weight:900;
    line-height:1.15;
}

.avatar{
    width:74px;
    height:74px;
    border-radius:26px;
    background:rgba(255,255,255,.16);
    border:1px solid rgba(255,255,255,.26);
    display:flex;
    align-items:center;
    justify-content:center;
    overflow:hidden;
    font-size:32px;
    font-weight:900;
    flex-shrink:0;
}

.avatar img{
    width:100%;
    height:100%;
    object-fit:cover;
}

.hero-grid{
    display:grid;
    grid-template-columns:repeat(4,1fr);
    gap:10px;
    margin-top:20px;
}

.hero-item{
    background:rgba(255,255,255,.14);
    border:1px solid rgba(255,255,255,.22);
    border-radius:20px;
    padding:14px;
    backdrop-filter:blur(12px);
}

.hero-item span{
    display:block;
    color:#dbeafe;
    font-size:11px;
    font-weight:900;
    margin-bottom:6px;
}

.hero-item strong{
    font-size:15px;
    font-weight:900;
}

.marquee{
    width:100%;
    overflow:hidden;
    margin:18px 0 4px;
    background:linear-gradient(135deg,#fff,#eff6ff);
    border:1px solid #dbeafe;
    border-radius:22px;
    box-shadow:0 14px 35px rgba(30,64,175,.08);
}

.marquee-track{
    white-space:nowrap;
    width:max-content;
    padding:13px 0;
    padding-left:100%;
    animation:marqueeMove 48s linear infinite;
    color:#1d4ed8;
    font-size:13px;
    font-weight:900;
}

@keyframes marqueeMove{
    from{transform:translateX(0);}
    to{transform:translateX(-100%);}
}

.section-title{
    display:flex;
    align-items:flex-end;
    justify-content:space-between;
    gap:12px;
    margin:26px 2px 13px;
}

.section-title h3{
    font-size:22px;
    font-weight:900;
    letter-spacing:-.4px;
}

.section-title p{
    margin-top:4px;
    color:var(--muted);
    font-size:13px;
    font-weight:750;
}

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

.course-card,
.course-hero,
.priority-card,
.stat-card,
.upcoming-card,
.module-card,
.timeline-card,
.empty,
.welcome-card{
    background:rgba(255,255,255,.96);
    border:1px solid rgba(226,232,240,.95);
    box-shadow:var(--shadow);
    backdrop-filter:blur(18px);
}

.course-card,
.welcome-card{
    border-radius:28px;
    padding:20px;
}

.course-card h4,
.welcome-card h4{
    font-size:20px;
    font-weight:900;
    margin:12px 0 10px;
    line-height:1.25;
}

.welcome-card p{
    color:var(--muted);
    font-size:13px;
    line-height:1.8;
    font-weight:750;
}

.welcome-icon{
    width:52px;
    height:52px;
    border-radius:19px;
    background:#eff6ff;
    display:flex;
    align-items:center;
    justify-content:center;
    font-size:25px;
}

.badge{
    display:inline-flex;
    align-items:center;
    gap:6px;
    padding:7px 11px;
    border-radius:999px;
    background:#eff6ff;
    color:#1d4ed8;
    font-size:11px;
    font-weight:900;
    margin:2px;
}

.badge.green{
    background:#ecfdf5;
    color:#047857;
}

.badge.purple{
    background:#f5f3ff;
    color:#5b21b6;
}

.meta{
    display:grid;
    gap:8px;
    color:var(--muted);
    font-size:13px;
    font-weight:800;
    margin:13px 0;
    line-height:1.5;
}

.progress-wrap{
    margin-top:14px;
}

.progress-label{
    display:flex;
    justify-content:space-between;
    color:var(--muted);
    font-size:12px;
    font-weight:900;
    margin-bottom:7px;
}

.progress-bar{
    height:9px;
    background:#e2e8f0;
    border-radius:999px;
    overflow:hidden;
}

.progress-fill{
    height:100%;
    background:linear-gradient(90deg,var(--blue),var(--purple));
    border-radius:999px;
}

.btn{
    display:inline-flex;
    justify-content:center;
    align-items:center;
    gap:8px;
    width:100%;
    border:none;
    border-radius:17px;
    padding:13px 16px;
    background:linear-gradient(135deg,var(--blue),var(--indigo));
    color:#fff;
    font-weight:900;
    margin-top:14px;
    box-shadow:0 14px 30px rgba(37,99,235,.24);
}

.btn-light{
    background:#eff6ff;
    color:#1d4ed8;
    box-shadow:none;
    border:1px solid #bfdbfe;
}

.btn-grid{
    display:grid;
    grid-template-columns:repeat(3,1fr);
    gap:10px;
}

.stats-grid{
    display:grid;
    grid-template-columns:repeat(6,1fr);
    gap:12px;
}

.stat-card{
    border-radius:25px;
    padding:17px;
    min-height:122px;
    overflow:hidden;
    position:relative;
}

.stat-card::after{
    content:"";
    width:90px;
    height:90px;
    border-radius:50%;
    background:#eff6ff;
    position:absolute;
    right:-36px;
    top:-36px;
}

html[dir="rtl"] .stat-card::after{
    right:auto;
    left:-36px;
}

.stat-icon{
    position:relative;
    z-index:2;
    width:43px;
    height:43px;
    border-radius:16px;
    background:#f8fafc;
    border:1px solid #edf2f7;
    display:flex;
    align-items:center;
    justify-content:center;
    font-size:21px;
    margin-bottom:13px;
}

.stat-card strong{
    position:relative;
    z-index:2;
    display:block;
    color:var(--blue);
    font-size:25px;
    font-weight:900;
    line-height:1.15;
}

.stat-card span{
    position:relative;
    z-index:2;
    color:var(--muted);
    font-size:12px;
    font-weight:850;
}

.course-hero{
    border-radius:30px;
    padding:22px;
    margin-top:18px;
}

.course-hero-head{
    display:flex;
    align-items:flex-start;
    justify-content:space-between;
    gap:16px;
}

.course-hero h3{
    font-size:27px;
    font-weight:900;
    margin:10px 0;
    line-height:1.25;
}

.progress-ring{
    width:96px;
    height:96px;
    border-radius:50%;
    background:
        conic-gradient(var(--blue) <?php echo $selectedCourse ? (int)($selectedCourse['progress_percent'] ?? 0) : 0; ?>%, #e2e8f0 0);
    display:flex;
    align-items:center;
    justify-content:center;
    flex-shrink:0;
    box-shadow:inset 0 0 0 10px #fff;
}

.progress-ring-inner{
    width:70px;
    height:70px;
    border-radius:50%;
    background:#fff;
    display:flex;
    flex-direction:column;
    align-items:center;
    justify-content:center;
    font-weight:900;
    color:var(--blue);
    font-size:18px;
}

.progress-ring-inner small{
    font-size:10px;
    color:var(--muted);
    font-weight:900;
}

.priority-card{
    border-radius:28px;
    padding:20px;
    margin-top:16px;
    display:flex;
    align-items:center;
    justify-content:space-between;
    gap:16px;
    background:
        radial-gradient(circle at top left,rgba(37,99,235,.10),transparent 28%),
        #fff;
}

.priority-card h4{
    font-size:18px;
    font-weight:900;
    margin-bottom:6px;
}

.priority-card p{
    color:var(--muted);
    font-size:13px;
    font-weight:750;
    line-height:1.7;
}

.priority-icon{
    width:58px;
    height:58px;
    border-radius:20px;
    background:linear-gradient(135deg,#eff6ff,#f5f3ff);
    display:flex;
    align-items:center;
    justify-content:center;
    font-size:28px;
    flex-shrink:0;
}

.upcoming-grid{
    display:grid;
    grid-template-columns:repeat(3,1fr);
    gap:13px;
}

.upcoming-card{
    border-radius:25px;
    padding:18px;
}

.upcoming-card h4{
    font-size:15px;
    font-weight:900;
    margin-bottom:9px;
}

.upcoming-card p{
    color:var(--muted);
    font-size:13px;
    line-height:1.7;
    font-weight:750;
}

.module-grid{
    display:grid;
    grid-template-columns:repeat(4,1fr);
    gap:12px;
}

.module-card{
    border-radius:24px;
    padding:17px;
    transition:.22s;
}

.module-card:hover{
    transform:translateY(-3px);
    box-shadow:0 20px 45px rgba(15,23,42,.10);
}

.module-card .module-icon{
    width:46px;
    height:46px;
    border-radius:17px;
    background:#eff6ff;
    display:flex;
    align-items:center;
    justify-content:center;
    font-size:22px;
    margin-bottom:12px;
}

.module-card b{
    display:block;
    font-size:14px;
    font-weight:900;
    margin-bottom:5px;
}

.module-card small{
    color:var(--muted);
    font-size:11px;
    line-height:1.45;
    font-weight:750;
}

.timeline-card{
    border-radius:28px;
    padding:20px;
}

.timeline{
    display:grid;
    gap:13px;
}

.timeline-item{
    display:flex;
    gap:12px;
    align-items:flex-start;
}

.timeline-dot{
    width:36px;
    height:36px;
    border-radius:14px;
    background:#eff6ff;
    display:flex;
    align-items:center;
    justify-content:center;
    flex-shrink:0;
}

.timeline-item b{
    display:block;
    font-size:14px;
    font-weight:900;
    margin-bottom:3px;
}

.timeline-item p{
    color:var(--muted);
    font-size:12px;
    font-weight:750;
    line-height:1.6;
}

.empty{
    border-style:dashed;
    border-radius:26px;
    padding:26px;
    text-align:center;
    color:var(--muted);
    font-weight:800;
    line-height:1.8;
}

.bottom-nav{
    position:fixed;
    left:50%;
    bottom:14px;
    transform:translateX(-50%);
    width:calc(100% - 28px);
    max-width:580px;
    background:rgba(255,255,255,.94);
    border:1px solid var(--line);
    border-radius:26px;
    padding:8px;
    display:grid;
    grid-template-columns:repeat(5,1fr);
    gap:6px;
    box-shadow:0 20px 55px rgba(15,23,42,.18);
    backdrop-filter:blur(18px);
    z-index:100;
}

.bottom-nav a{
    display:flex;
    flex-direction:column;
    align-items:center;
    justify-content:center;
    gap:4px;
    padding:10px 4px;
    border-radius:18px;
    color:#64748b;
    font-size:11px;
    font-weight:900;
}

.bottom-nav a.active{
    background:#eff6ff;
    color:var(--blue);
}

.bottom-nav span{
    font-size:18px;
}

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

    .module-grid{
        grid-template-columns:repeat(3,1fr);
    }
}

@media(max-width:820px){
    .course-grid,
    .welcome-grid,
    .upcoming-grid{
        grid-template-columns:1fr;
    }

    .hero-grid{
        grid-template-columns:repeat(2,1fr);
    }

    .course-hero-head{
        flex-direction:column;
    }

    .btn-grid{
        grid-template-columns:1fr;
    }
}

@media(max-width:560px){
    body{
        padding-bottom:108px;
    }

    .app-shell{
        padding:12px;
    }

    .topbar{
        align-items:flex-start;
    }

    .brand h1{
        font-size:16px;
    }

    .brand p{
        font-size:11px;
    }

    .logo{
        width:52px;
        height:52px;
        border-radius:18px;
    }

    .hero{
        border-radius:28px;
        padding:21px;
    }

    .hero h2{
        font-size:25px;
    }

    .avatar{
        width:60px;
        height:60px;
        border-radius:21px;
    }

    .hero-grid,
    .stats-grid,
    .module-grid{
        grid-template-columns:repeat(2,1fr);
        gap:10px;
    }

    .section-title h3{
        font-size:19px;
    }
}
</style>
</head>


<body>

<div class="app-shell">

    <header class="topbar">
        <div class="brand">
            <div class="logo">SMI</div>
            <div>
                <h1>
                    <?php echo e($selectedCourse ? $tr['course_dashboard'] : $tr['home_gateway']); ?>
                </h1>
                <p><?php echo e($tr['subtitle']); ?></p>
            </div>
        </div>

        <div class="lang-switch">
            <a href="dashboard.php?lang=en<?php echo $selectedCourseId ? '&course_id=' . (int)$selectedCourseId : ''; ?>">EN</a>
            <a href="dashboard.php?lang=ar<?php echo $selectedCourseId ? '&course_id=' . (int)$selectedCourseId : ''; ?>">AR</a>
        </div>
    </header>

    <section class="hero">
        <div class="hero-content">

            <div class="hero-top">
                <div>
                    <small><?php echo e($tr['welcome']); ?></small>
                    <h2><?php echo e($studentName); ?></h2>
                </div>

                <div class="avatar">
                    <?php if ($profileImage !== ''): ?>
                        <img src="<?php echo e($profileImage); ?>" alt="Profile">
                    <?php else: ?>
                        <?php echo e(strtoupper(substr($studentName, 0, 1))); ?>
                    <?php endif; ?>
                </div>
            </div>

            <div class="hero-grid">
                <div class="hero-item">
                    <span><?php echo e($tr['student_code']); ?></span>
                    <strong><?php echo e($studentCode); ?></strong>
                </div>

                <div class="hero-item">
                    <span><?php echo e($tr['student_card']); ?></span>
                    <strong><?php echo e($studentCardNumber); ?></strong>
                </div>

                <div class="hero-item">
                    <span><?php echo e($tr['secondary_level']); ?></span>
                    <strong><?php echo e($secondaryLevel); ?></strong>
                </div>

                <div class="hero-item">
                    <span><?php echo e($tr['core_level']); ?></span>
                    <strong><?php echo e($coreLevel); ?></strong>
                </div>
            </div>

        </div>
    </section>

    <div class="marquee">
        <div class="marquee-track">
            <?php echo e($tr['motivational_text']); ?>
            <?php echo e($randomMotivation['en']); ?>
            •
            <?php echo e($randomMotivation['ar']); ?>
            • SMI •
        </div>
    </div>

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

        <div class="section-title">
            <div>
                <h3><?php echo e($tr['welcome_cards']); ?></h3>
                <p><?php echo e($tr['subtitle']); ?></p>
            </div>
        </div>

        <section class="welcome-grid">
            <article class="welcome-card">
                <div class="welcome-icon">🪪</div>
                <h4><?php echo e($tr['identity_card']); ?></h4>
                <p><?php echo e($tr['identity_desc']); ?></p>
            </article>

            <article class="welcome-card">
                <div class="welcome-icon">📚</div>
                <h4><?php echo e($tr['core_periods']); ?></h4>
                <p><?php echo e($tr['core_desc']); ?></p>
            </article>

            <article class="welcome-card">
                <div class="welcome-icon">🎙️</div>
                <h4><?php echo e($tr['secondary_training']); ?></h4>
                <p><?php echo e($tr['secondary_desc']); ?></p>
                <a class="btn btn-light" href="<?php echo e($secondaryUrl); ?>">
                    <?php echo e($tr['go_secondary']); ?>
                </a>
            </article>

            <article class="welcome-card">
                <div class="welcome-icon">🚀</div>
                <h4><?php echo e($tr['student_journey']); ?></h4>
                <p><?php echo e($tr['journey_desc']); ?></p>
            </article>
        </section>

        <div class="section-title">
            <div>
                <h3><?php echo e($tr['current_course']); ?></h3>
                <p><?php echo e($tr['course_only_hint']); ?></p>
            </div>
        </div>

        <?php if ($currentCourse): ?>

            <section class="course-grid">
                <article class="course-card">
                    <span class="badge green"><?php echo e(safeUcfirst($currentCourse['enrollment_status'] ?? 'Active')); ?></span>
                    <span class="badge purple"><?php echo e($tr['current_course']); ?></span>

                    <h4><?php echo e($currentCourse['title'] ?? 'Course'); ?></h4>

                    <div class="meta">
                        <div><?php echo e($tr['course_code']); ?>: <?php echo e($currentCourse['display_code'] ?? 'N/A'); ?></div>
                        <div><?php echo e($tr['teacher']); ?>: <?php echo e($currentCourse['teacher_name'] ?? 'N/A'); ?></div>
                        <div><?php echo e($tr['core_level']); ?>: <?php echo e(safeUcfirst($currentCourse['level'] ?? 'General')); ?></div>
                        <div><?php echo e($tr['start_date']); ?>: <?php echo e(safeDate($currentCourse['start_date'] ?? null)); ?></div>
                        <div><?php echo e($tr['end_date']); ?>: <?php echo e(safeDate($currentCourse['end_date'] ?? null)); ?></div>
                    </div>

                    <div class="progress-wrap">
                        <div class="progress-label">
                            <span><?php echo e($tr['course_progress']); ?></span>
                            <span><?php echo (int)($currentCourse['progress_percent'] ?? 0); ?>%</span>
                        </div>

                        <div class="progress-bar">
                            <div class="progress-fill" style="width:<?php echo (int)($currentCourse['progress_percent'] ?? 0); ?>%"></div>
                        </div>
                    </div>

                    <a class="btn" href="dashboard.php?course_id=<?php echo (int)$currentCourse['id']; ?>">
                        <?php echo e($tr['enter_course_dashboard']); ?>
                    </a>
                </article>
            </section>

        <?php else: ?>

            <section class="empty">
                <p><?php echo e($tr['no_current_course']); ?></p>

                <div class="btn-grid">
                    <a class="btn" href="<?php echo e($joinCourseUrl); ?>">
                        <?php echo e($tr['join_course']); ?>
                    </a>

                    <a class="btn btn-light" href="<?php echo e($availableCoursesUrl); ?>">
                        <?php echo e($tr['view_available_courses']); ?>
                    </a>

                    <a class="btn btn-light" href="<?php echo e($contactAdminUrl); ?>">
                        <?php echo e($tr['contact_admin']); ?>
                    </a>
                </div>
            </section>

        <?php endif; ?>

        <div class="section-title">
            <div>
                <h3><?php echo e($tr['academic_snapshot']); ?></h3>
                <p><?php echo e($tr['subtitle']); ?></p>
            </div>
        </div>

        <section class="stats-grid">
            <div class="stat-card">
                <div class="stat-icon">📚</div>
                <strong><?php echo (int)$totalCourses; ?></strong>
                <span><?php echo e($tr['courses']); ?></span>
            </div>

            <div class="stat-card">
                <div class="stat-icon">✅</div>
                <strong><?php echo (int)$totalAttendance; ?></strong>
                <span><?php echo e($tr['attendance']); ?></span>
            </div>

            <div class="stat-card">
                <div class="stat-icon">📘</div>
                <strong><?php echo (int)$totalHomework; ?></strong>
                <span><?php echo e($tr['homework']); ?></span>
            </div>

            <div class="stat-card">
                <div class="stat-icon">📝</div>
                <strong><?php echo (int)$totalExams; ?></strong>
                <span><?php echo e($tr['exams']); ?></span>
            </div>

            <div class="stat-card">
                <div class="stat-icon">🎓</div>
                <strong><?php echo (int)$totalCertificates; ?></strong>
                <span><?php echo e($tr['certificates']); ?></span>
            </div>

            <div class="stat-card">
                <div class="stat-icon">🗂️</div>
                <strong><?php echo (int)$totalArchivedCourses; ?></strong>
                <span><?php echo e($tr['previous_courses']); ?></span>
            </div>
        </section>

        <div class="section-title">
            <div>
                <h3><?php echo e($tr['previous_courses']); ?></h3>
                <p><?php echo e($tr['no_archived_courses']); ?></p>
            </div>
        </div>

        <?php if ($archivedCourses): ?>

            <section class="course-grid">
                <?php foreach ($archivedCourses as $course): ?>
                    <article class="course-card">
                        <span class="badge"><?php echo e(safeUcfirst($course['enrollment_status'] ?? 'Archived')); ?></span>

                        <h4><?php echo e($course['title'] ?? 'Course'); ?></h4>

                        <div class="meta">
                            <div><?php echo e($tr['course_code']); ?>: <?php echo e($course['display_code'] ?? 'N/A'); ?></div>
                            <div><?php echo e($tr['teacher']); ?>: <?php echo e($course['teacher_name'] ?? 'N/A'); ?></div>
                            <div><?php echo e($tr['core_level']); ?>: <?php echo e(safeUcfirst($course['level'] ?? 'General')); ?></div>
                            <div><?php echo e($tr['start_date']); ?>: <?php echo e(safeDate($course['start_date'] ?? null)); ?></div>
                            <div><?php echo e($tr['end_date']); ?>: <?php echo e(safeDate($course['end_date'] ?? null)); ?></div>
                        </div>
                    </article>
                <?php endforeach; ?>
            </section>

        <?php else: ?>

            <div class="empty">
                <?php echo e($tr['no_archived_courses']); ?>
            </div>

        <?php endif; ?>

    <?php else: ?>

        <section class="course-hero">
            <div class="course-hero-head">
                <div>
                    <span class="badge green"><?php echo e($tr['course_center']); ?></span>
                    <span class="badge purple"><?php echo e($selectedCourse['display_code'] ?? 'N/A'); ?></span>

                    <h3><?php echo e($selectedCourse['title'] ?? 'Course'); ?></h3>

                    <div class="meta">
                        <div><?php echo e($tr['teacher']); ?>: <?php echo e($selectedCourse['teacher_name'] ?? 'N/A'); ?></div>
                        <div><?php echo e($tr['core_level']); ?>: <?php echo e(safeUcfirst($selectedCourse['level'] ?? 'General')); ?></div>
                        <div><?php echo e($tr['start_date']); ?>: <?php echo e(safeDate($selectedCourse['start_date'] ?? null)); ?></div>
                        <div><?php echo e($tr['end_date']); ?>: <?php echo e(safeDate($selectedCourse['end_date'] ?? null)); ?></div>
                    </div>

                    <a class="btn btn-light" href="dashboard.php">
                        <?php echo e($tr['switch_to_home']); ?>
                    </a>
                </div>

                <div class="progress-ring">
                    <div class="progress-ring-inner">
                        <?php echo (int)($selectedCourse['progress_percent'] ?? 0); ?>%
                        <small><?php echo e($tr['progress']); ?></small>
                    </div>
                </div>
            </div>
        </section>

        <section class="priority-card">
            <div>
                <h4><?php echo e($tr['priority']); ?></h4>
                <p><?php echo e($priorityText); ?></p>

                <a class="btn" href="<?php echo e($priorityLink); ?>">
                    <?php echo e($tr['open']); ?>
                </a>
            </div>

            <div class="priority-icon">
                <?php
                echo $priorityType === 'homework'
                    ? '📘'
                    : (
                        $priorityType === 'exam'
                            ? '📝'
                            : (
                                $priorityType === 'session'
                                    ? '🎥'
                                    : '✅'
                            )
                    );
                ?>
            </div>
        </section>

        <div class="section-title">
            <div>
                <h3><?php echo e($tr['academic_snapshot']); ?></h3>
                <p><?php echo e($tr['course_only_hint']); ?></p>
            </div>
        </div>

        <section class="stats-grid">
            <div class="stat-card">
                <div class="stat-icon">✅</div>
                <strong><?php echo (int)$courseStats['attendance_rate']; ?>%</strong>
                <span><?php echo e($tr['attendance_rate']); ?></span>
            </div>

            <div class="stat-card">
                <div class="stat-icon">📘</div>
                <strong><?php echo (int)$courseStats['pending_homework']; ?></strong>
                <span><?php echo e($tr['pending_homework']); ?></span>
            </div>

            <div class="stat-card">
                <div class="stat-icon">📝</div>
                <strong><?php echo (int)$courseStats['upcoming_exams']; ?></strong>
                <span><?php echo e($tr['upcoming_exams']); ?></span>
            </div>

            <div class="stat-card">
                <div class="stat-icon">📂</div>
                <strong><?php echo (int)$courseStats['materials']; ?></strong>
                <span><?php echo e($tr['available_materials']); ?></span>
            </div>

            <div class="stat-card">
                <div class="stat-icon">🏆</div>
                <strong><?php echo e($courseStats['final_grade']); ?></strong>
                <span><?php echo e($tr['final_grade']); ?></span>
            </div>

            <div class="stat-card">
                <div class="stat-icon">🎓</div>
                <strong><?php echo (int)$courseStats['certificates']; ?></strong>
                <span><?php echo e($tr['certificates_count']); ?></span>
            </div>
        </section>

        <div class="section-title">
            <div>
                <h3><?php echo e($tr['upcoming']); ?></h3>
                <p><?php echo e($tr['course_only_hint']); ?></p>
            </div>
        </div>

        <section class="upcoming-grid">
            <div class="upcoming-card">
                <h4>🎥 <?php echo e($tr['next_session']); ?></h4>
                <p>
                    <?php
                    echo $nextSession
                        ? e(($nextSession['title'] ?? 'Session') . ' - ' . safeDate($nextSession['session_date'] ?? null))
                        : e($tr['no_session']);
                    ?>
                </p>
            </div>

            <div class="upcoming-card">
                <h4>📝 <?php echo e($tr['next_exam']); ?></h4>
                <p>
                    <?php
                    echo $nextExam
                        ? e(($nextExam['title'] ?? 'Exam') . ' - ' . safeDate($nextExam['exam_date'] ?? null))
                        : e($tr['no_exam']);
                    ?>
                </p>
            </div>

            <div class="upcoming-card">
                <h4>📘 <?php echo e($tr['next_homework']); ?></h4>
                <p>
                    <?php
                    echo $nextHomework
                        ? e(($nextHomework['title'] ?? 'Homework') . ' - ' . safeDate($nextHomework['due_date'] ?? null))
                        : e($tr['no_homework']);
                    ?>
                </p>
            </div>
        </section>

        <div class="section-title">
            <div>
                <h3><?php echo e($tr['quick_actions']); ?></h3>
                <p><?php echo e($tr['course_only_hint']); ?></p>
            </div>
        </div>

        <section class="module-grid">
            <?php foreach ($courseActions as $action): ?>
                <a class="module-card" href="<?php echo e($action['url']); ?>">
                    <div class="module-icon"><?php echo e($action['icon']); ?></div>
                    <b><?php echo e($action['label']); ?></b>
                    <small><?php echo e($action['desc']); ?></small>
                </a>
            <?php endforeach; ?>
        </section>

        <div class="section-title">
            <div>
                <h3><?php echo e($tr['timeline']); ?></h3>
                <p><?php echo e($tr['course_only_hint']); ?></p>
            </div>
        </div>

        <section class="timeline-card">
            <div class="timeline">
                <div class="timeline-item">
                    <div class="timeline-dot">🎥</div>
                    <div>
                        <b><?php echo e($tr['next_session']); ?></b>
                        <p><?php echo $nextSession ? e(safeDate($nextSession['session_date'] ?? null)) : e($tr['no_session']); ?></p>
                    </div>
                </div>

                <div class="timeline-item">
                    <div class="timeline-dot">📘</div>
                    <div>
                        <b><?php echo e($tr['next_homework']); ?></b>
                        <p><?php echo $nextHomework ? e(safeDate($nextHomework['due_date'] ?? null)) : e($tr['no_homework']); ?></p>
                    </div>
                </div>

                <div class="timeline-item">
                    <div class="timeline-dot">📝</div>
                    <div>
                        <b><?php echo e($tr['next_exam']); ?></b>
                        <p><?php echo $nextExam ? e(safeDate($nextExam['exam_date'] ?? null)) : e($tr['no_exam']); ?></p>
                    </div>
                </div>

                <div class="timeline-item">
                    <div class="timeline-dot">🎓</div>
                    <div>
                        <b><?php echo e($tr['certificates']); ?></b>
                        <p><?php echo (int)$courseStats['certificates']; ?> <?php echo e($tr['certificates_count']); ?></p>
                    </div>
                </div>
            </div>
        </section>

    <?php endif; ?>

</div>

<nav class="bottom-nav">
    <?php if ($selectedCourseId > 0 && $selectedCourse): ?>

        <a class="active" href="dashboard.php?course_id=<?php echo (int)$selectedCourseId; ?>">
            <span>🏠</span>
            <?php echo e($tr['home']); ?>
        </a>

        <a href="attendance.php?course_id=<?php echo (int)$selectedCourseId; ?>">
            <span>✅</span>
            <?php echo e($tr['attendance']); ?>
        </a>

        <a href="homework.php?course_id=<?php echo (int)$selectedCourseId; ?>">
            <span>📘</span>
            <?php echo e($tr['homework']); ?>
        </a>

        <a href="exams.php?course_id=<?php echo (int)$selectedCourseId; ?>">
            <span>📝</span>
            <?php echo e($tr['exams']); ?>
        </a>

        <a href="materials.php?course_id=<?php echo (int)$selectedCourseId; ?>">
            <span>☰</span>
            <?php echo e($tr['more']); ?>
        </a>

    <?php else: ?>

        <a class="active" href="dashboard.php">
            <span>🏠</span>
            <?php echo e($tr['home']); ?>
        </a>

        <a href="<?php echo e($secondaryUrl); ?>">
            <span>🎙️</span>
            <?php echo e($tr['secondary_periods']); ?>
        </a>

        <a href="<?php echo e($joinCourseUrl); ?>">
            <span>➕</span>
            <?php echo e($tr['join_course']); ?>
        </a>

        <a href="profile.php">
            <span>👤</span>
            <?php echo e($tr['profile']); ?>
        </a>

        <a href="../logout.php">
            <span>↗</span>
            <?php echo e($tr['logout']); ?>
        </a>

    <?php endif; ?>
</nav>

</body>
</html>