<?php
session_start(); // Start the session to access session variables

// Prevent caching to ensure fresh exam data
header("Cache-Control: no-cache, no-store, must-revalidate");
header("Pragma: no-cache");
header("Expires: 0");

require_once 'config.php'; // Include the database configuration file. Ensure this path is correct.

// Define role constants if they are not already defined.
if (!defined('ROLE_SUPER_ADMIN')) define('ROLE_SUPER_ADMIN', 0);
if (!defined('ROLE_ADMIN')) define('ROLE_ADMIN', 1);
if (!defined('ROLE_TEACHER')) define('ROLE_TEACHER', 2); // Teachers should be role 2
if (!defined('ROLE_STUDENT')) define('ROLE_STUDENT', 3); // Students should be role 3
if (!defined('ROLE_PARENT')) define('ROLE_PARENT', 4);
if (!defined('ROLE_STAFF')) define('ROLE_STAFF', 5);

// --- Language Handling and Localization Dictionary ---
$available_languages = ['en', 'lug', 'sw']; // English, Luganda, Kiswahili
$default_language = 'en';

// Check if a language is selected via GET parameter; otherwise, use session or default.
if (isset($_GET['lang']) && in_array($_GET['lang'], $available_languages)) {
    $_SESSION['lang'] = $_GET['lang'];
} elseif (!isset($_SESSION['lang'])) {
    $_SESSION['lang'] = $default_language;
}

$current_lang = $_SESSION['lang'];

/**
 * Loads language-specific strings.
 */
function load_language_data($lang) {
    $data = [
        'en' => [
            'dashboard_title_prefix' => 'Dashboard',
            'sidebar_dashboard' => 'Home',
            'sidebar_my_classes' => 'My Network',
            'sidebar_my_students' => 'Students',
            'sidebar_assignments' => 'Assignments',
            'sidebar_grades' => 'Exams & Marks',
            'sidebar_messages' => 'Messaging',
            'sidebar_calendar' => 'Events',
            'sidebar_profile' => 'Me',
            'sidebar_settings' => 'Settings',
            'sidebar_logout' => 'Sign Out',
            'school_name_not_found' => 'School Name Not Found',
            'search_placeholder' => 'Search exams, subjects...',
            'welcome_message_prefix' => 'Welcome',
            'welcome_message_suffix' => '!',
            'logged_in_as' => 'Logged in as:',
            'divine_reports' => 'DIVINE REPORTS',
            'more_menu' => 'More',
            'page_title' => 'Manage Exams & Marks',
            'select_exam' => 'Select Exam Period',
            'select_exam_placeholder' => 'Choose an exam to view subjects...',
            'assigned_subjects_title' => 'Your Assigned Subjects',
            'class_label' => 'CLASS',
            'stream_label' => 'STREAM',
            'subject_label' => 'SUBJECT',
            'options_label' => 'ACTIONS',
            'enter_marks_button' => 'Enter Marks',
            'no_subjects_assigned' => 'No subjects assigned for the selected exam.',
            'no_exams_available' => 'No exams available.',
            'loading' => 'Loading...',
            'error_occurred' => 'An error occurred. Please try again.',
            'marks_entry_title' => 'Enter Marks for',
            'student_name' => 'Student Name',
            'paper' => 'Paper',
            'select_paper' => 'Select Paper',
            'current_mark' => 'Score',
            'new_mark' => 'New Score',
            'save_marks' => 'Save Marks',
            'cancel' => 'Cancel',
            'marks_saved_success' => 'Marks saved successfully!',
            'invalid_mark' => 'Please enter a valid mark (0-100).',
            'multi_paper_validation_error' => '❌ Cannot save: Missing marks for required papers:',
            'paper_selection_required' => '❌ Paper Selection Required\n\nPlease select a specific paper before entering marks for this multi-paper subject.',
            'complete_all_papers_before_save' => '✅ Please complete ALL paper marks before saving this subject.',
            'multi_paper_missing_summary' => '...and %d more entries',
        ],
        'lug' => [
            'dashboard_title_prefix' => 'Diisiboodi',
            'sidebar_dashboard' => 'Diisiboodi',
            'sidebar_my_classes' => 'Ebibiina Byange',
            'sidebar_my_students' => 'Bayizi Bange',
            'sidebar_assignments' => 'Ebitongole',
            'sidebar_grades' => 'Akaadi',
            'sidebar_messages' => 'Obubaka',
            'sidebar_calendar' => 'Kkalenda',
            'sidebar_profile' => 'Purofayiro',
            'sidebar_settings' => 'Enteekateeka',
            'sidebar_logout' => 'Log Out',
            'school_name_not_found' => 'Erinnya ly\'Essomero Terinnaba Kulabika',
            'search_placeholder' => 'Noonya ebikebera/amasomo',
            'welcome_message_prefix' => 'Mpulira Olamusiddwa',
            'welcome_message_suffix' => '!',
            'logged_in_as' => 'Oyinze okukakasa nga:',
            'divine_reports' => 'RIPOTA ZA MUNGU',
            'more_menu' => 'Ebirala',
            'page_title' => 'Kola ku Bikebera n\'Obubonero',
            'select_exam' => 'Londa Ekikebera',
            'select_exam_placeholder' => 'Londa ekikebera okulaba amasomo...',
            'assigned_subjects_title' => 'Amasomo Go mu Budde bw\'Ekikebera Kino',
            'class_label' => 'KIBIINA',
            'stream_label' => 'KIRAGIRA',
            'subject_label' => 'EKISOMO',
            'options_label' => 'ENKULUNGEKO',
            'enter_marks_button' => 'Yingiza Obubonero',
            'no_subjects_assigned' => 'Tewali masomo gakutwaliddwa mu kikebera kino.',
            'no_exams_available' => 'Tewali bikebera.',
            'loading' => 'Kutegeka...',
            'error_occurred' => 'Wabaddewo ensobi. Ddamu okugezaako.',
            'marks_entry_title' => 'Yingiza Obubonero bwa',
            'student_name' => 'Erinnya ly\'Omuyizi',
            'paper' => 'Ekitabo',
            'select_paper' => 'Londa Ekitabo',
            'current_mark' => 'Obubonero Obwo Waliwo',
            'new_mark' => 'Obubonero Obupya',
            'save_marks' => 'Kuuma Obubonero',
            'cancel' => 'Sazaamu',
            'marks_saved_success' => 'Obubonero buwonyiddwa obulungi!',
            'invalid_mark' => 'Yingiza obubonero obukkirizibwa (0-100).',
            'multi_paper_validation_error' => '❌ Siyinza okukuuma: Tewali obubonero ku bitabo ebikyamu:',
            'paper_selection_required' => '❌ Okulonda Ekitabo Kikyamu',
            'complete_all_papers_before_save' => '✅ Ddamu okukola oku kituuko kyonna ku bitabo okulembayo, olwo ng\'oyise okuwonyisa oku kino.',
            'multi_paper_missing_summary' => '...ne %d eddagala naye',
        ],
        'sw' => [
            'dashboard_title_prefix' => 'Dashibodi',
            'sidebar_dashboard' => 'Dashibodi',
            'sidebar_my_classes' => 'Madarasa Yangu',
            'sidebar_my_students' => 'Wanafunzi Wangu',
            'sidebar_assignments' => 'Kazi',
            'sidebar_grades' => 'Alama',
            'sidebar_messages' => 'Ujumbe',
            'sidebar_calendar' => 'Kalenda',
            'sidebar_profile' => 'Wasifu',
            'sidebar_settings' => 'Mipangilio',
            'sidebar_logout' => 'Ondoka',
            'school_name_not_found' => 'Jina la Shule Halikupatikana',
            'search_placeholder' => 'Tafuta mitihani/masomo',
            'welcome_message_prefix' => 'Karibu',
            'welcome_message_suffix' => '!',
            'logged_in_as' => 'Umeingia kama:',
            'divine_reports' => 'RIPOTI ZA MUNGU',
            'more_menu' => 'Zaidi',
            'page_title' => 'Dhibiti Mitihani na Alama',
            'select_exam' => 'Chagua Mtihani',
            'select_exam_placeholder' => 'Chagua mtihani kuona masomo...',
            'assigned_subjects_title' => 'Masomo Yako Yaliyokabidhiwa kwa Kipindi hiki cha Mtihani',
            'class_label' => 'DARASA',
            'stream_label' => 'MKONDO',
            'subject_label' => 'SOMO',
            'options_label' => 'MACHAGUO',
            'enter_marks_button' => 'Weka Alama',
            'no_subjects_assigned' => 'Hakuna masomo yaliyokabidhiwa kwa mtihani huu.',
            'no_exams_available' => 'Hakuna mitihani inayopatikana.',
            'loading' => 'Inapakia...',
            'error_occurred' => 'Hitilafu imetokea. Tafadhali jaribu tena.',
            'marks_entry_title' => 'Weka Alama za',
            'student_name' => 'Jina la Mwanafunzi',
            'paper' => 'Kibali',
            'select_paper' => 'Chagua Kibali',
            'current_mark' => 'Alama ya Sasa',
            'new_mark' => 'Alama Mpya',
            'save_marks' => 'Hifadhi Alama',
            'cancel' => 'Ghairi',
            'marks_saved_success' => 'Alama zimehifadhiwa kwa ufanisi!',
            'invalid_mark' => 'Tafadhali weka alama halali (0-100).',
            'multi_paper_validation_error' => '❌ Haiwezi kuhifadhiwa: Hakuna alama kwa vibali vinavyohitajika:',
            'paper_selection_required' => '❌ Uchaguzi wa Kifulani Unahitajika',
            'complete_all_papers_before_save' => '✅ Tafadhali kamilisha ALAMA ZOTE za vibali kabla ya kuhifadhi somo hili.',
            'multi_paper_missing_summary' => '...na maingizo %d zaidi',
        ]
    ];
    return $data[$lang] ?? $data['en']; // Fallback to English if language not found
}

$_L = load_language_data($current_lang);

function check_role_access($required_role_code) {
    if (!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true || !isset($_SESSION["school_id"])) {
        header("location: login.php");
        exit;
    }

    // Allow admins and super admins to access teacher pages
    $privileged_roles = [ROLE_SUPER_ADMIN, ROLE_ADMIN];
    if ($required_role_code === ROLE_TEACHER && in_array($_SESSION["role"], $privileged_roles)) {
        return; // Allow access
    }

    if ($_SESSION["role"] !== $required_role_code) {
        switch ($_SESSION["role"]) {
            case ROLE_SUPER_ADMIN:
                header("location: super_admin_dashboard.php");
                break;
            case ROLE_ADMIN:
                header("location: admin_dashboard.php");
                break;
            case ROLE_STUDENT:
                header("location: student_dashboard.php");
                break;
            default:
                header("location: login.php");
                break;
        }
        exit;
    }
}

// Check for Teacher role
check_role_access(ROLE_TEACHER);

// Set current page for navigation
$currentPage = 'grades';

// User details
$user_id = $_SESSION["id"];
$username = htmlspecialchars($_SESSION["username"]);
$user_role_code = $_SESSION["role"];
$current_user_school_id = $_SESSION["school_id"];

// Initialize variables
$phone_number = $photo = $status = "";
$school_name = $_L['school_name_not_found'];
$school_logo_path = "images/default_school_logo.png";
$teacher_actual_id = null;
$exams = [];
$subjects = [];

// Database operations
if (isset($conn) && $conn instanceof mysqli) {

    // 1. Fetch user details
    $sql = "SELECT phone_number, photo, status FROM users WHERE id = ? AND school_id = ?";
    if ($stmt = $conn->prepare($sql)) {
        $stmt->bind_param("ii", $user_id, $current_user_school_id);
        if ($stmt->execute()) {
            $stmt->bind_result($phone_number_db, $photo_db, $status_db);
            $stmt->fetch();
            $phone_number = htmlspecialchars($phone_number_db ?? 'N/A');
            $photo = !empty($photo_db) ? htmlspecialchars($photo_db) : 'https://via.placeholder.com/80/cccccc/FFFFFF?text=TR';
            $status = htmlspecialchars($status_db ?? 'N/A');
        }
        $stmt->close();
    }

    // 2. Teacher is identified by user_id directly (no separate teachers table)
    $teacher_actual_id = $user_id;

    // 3. Fetch school details
    $sql_school = "SELECT school_name, logo FROM schools WHERE school_id = ?";
    if ($stmt_school = $conn->prepare($sql_school)) {
        $stmt_school->bind_param("i", $current_user_school_id);
        if ($stmt_school->execute()) {
            $stmt_school->bind_result($school_name_db, $school_logo_db);
            if ($stmt_school->fetch()) {
                $school_name = htmlspecialchars($school_name_db);
                $school_logo_path = !empty($school_logo_db) ? htmlspecialchars($school_logo_db) : 'images/default_school_logo.png';
            }
        }
        $stmt_school->close();
    }

    // 4. Fetch available exams for this school
    // Only show Normal exams (exam_type = 0)
    // exclude all special types (exam_type = 1): Consolidated, Term Summary, Average Assessment
    // Include exam status to check if published
    $sql_exams = "SELECT exam_id, exam_name, exam_type, status, created_at FROM exams 
                  WHERE school_id = ? 
                  AND exam_type = '0'
                  ORDER BY created_at DESC";
    if ($stmt_exams = $conn->prepare($sql_exams)) {
        $stmt_exams->bind_param("i", $current_user_school_id);
        if ($stmt_exams->execute()) {
            $result_exams = $stmt_exams->get_result();
            while ($row = $result_exams->fetch_assoc()) {
                $exams[] = $row;
            }
        }
        $stmt_exams->close();
    }

    // DEBUG: Log what exams were found
    error_log("TEACHER DEBUG: School ID " . $current_user_school_id . " - Found " . count($exams) . " exams");
    foreach ($exams as $exam) {
        error_log("TEACHER DEBUG: Exam " . $exam['exam_id'] . " - " . $exam['exam_name'] . " - Type: " . $exam['exam_type']);
    }

    // DEBUG: Also run a query to see ALL exams in this school
    $debug_all_sql = "SELECT exam_id, exam_name, exam_type FROM exams WHERE school_id = ? ORDER BY created_at DESC";
    $debug_all_result = $conn->prepare($debug_all_sql);
    if ($debug_all_result) {
        $debug_all_result->bind_param("i", $current_user_school_id);
        $debug_all_result->execute();
        $all_exams_result = $debug_all_result->get_result();
        while ($all_exam = $all_exams_result->fetch_assoc()) {
            error_log("TEACHER DEBUG ALL: Exam " . $all_exam['exam_id'] . " - " . $all_exam['exam_name'] . " - Type: " . $all_exam['exam_type']);
        }
        $debug_all_result->close();
    }

} else {
    error_log("Database connection \$conn not available in teacher_exams.php");
    $photo = 'https://via.placeholder.com/80/cccccc/FFFFFF?text=TR';
}

// Determine role name
$role_name = "Unknown";
switch ($user_role_code) {
    case ROLE_SUPER_ADMIN: $role_name = "Super Admin"; break;
    case ROLE_ADMIN:        $role_name = "Admin";       break;
    case ROLE_TEACHER:      $role_name = "Teacher";     break;
    case ROLE_STUDENT:      $role_name = "Student";     break;
    case ROLE_PARENT:       $role_name = "Parent";      break;
    case ROLE_STAFF:        $role_name = "Staff";       break;
}

?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo $_L['page_title']; ?> - <?php echo $school_name; ?></title>
    <link rel="stylesheet" href="style.css">
    <link rel="icon" href="<?php echo $school_logo_path; ?>" type="image/png">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
    
    <style>
        :root {
            --li-blue: #0a66c2;
            --li-blue-hover: #004182;
            --li-bg: #f3f2ef;
            --li-white: #ffffff;
            --li-text-dark: #191919;
            --li-text-gray: #666666;
            --li-border: #e0e0e0;
            --li-card-border: #dce6f1;
            --li-input-bg: #eef3f8;
            --li-font: -apple-system, system-ui, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", "Fira Sans", Ubuntu, Oxygen, "Oxygen Sans", Cantarell, "Droid Sans", "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Lucida Grande", Helvetica, Arial, sans-serif;
        }

        body {
            background-color: var(--li-bg);
            font-family: var(--li-font);
            color: var(--li-text-dark);
        }

        /* Header */
        .header {
            background: var(--li-white);
            border-bottom: 1px solid var(--li-border);
            height: 60px;
            box-shadow: none;
            position: sticky;
            top: 0;
            z-index: 100;
            display: flex;
            align-items: center;
            padding: 0 20px;
        }

        .school-info h1 {
            color: var(--li-blue);
            font-weight: 700;
            font-size: 1.2rem;
        }

        .search-bar {
            background: var(--li-input-bg);
            border-radius: 4px;
            padding: 0 10px;
            height: 34px;
            display: flex;
            align-items: center;
            border: none;
            max-width: 280px;
        }
        
        .search-bar input {
            background: transparent;
            border: none;
            color: var(--li-text-dark);
            font-size: 14px;
        }
        
        .search-bar i {
            color: var(--li-text-gray);
        }

        /* Sidebar */
        .sidebar {
            background: var(--li-white);
            border-right: 1px solid var(--li-border);
            box-shadow: none;
        }

        .sidebar .logo {
            border-bottom: 1px solid var(--li-border);
            padding: 15px;
        }

        .sidebar nav ul li a {
            color: var(--li-text-gray);
            font-weight: 600;
            font-size: 0.95rem;
            padding: 12px 20px;
            border-left: 3px solid transparent;
            display: flex;
            align-items: center;
            gap: 12px;
        }

        .sidebar nav ul li.active a, 
        .sidebar nav ul li a:hover {
            color: var(--li-text-dark);
            background-color: transparent;
            border-left-color: var(--li-text-dark);
        }
        
        .sidebar nav ul li.active a {
            color: var(--li-text-dark);
            border-left-color: var(--li-blue);
        }

        .sidebar nav ul li a i {
            width: 20px;
            text-align: center;
            font-size: 1.1rem;
        }

        /* Main Content Cards */
        .exams-container {
            background: var(--li-white);
            border-radius: 8px;
            border: 1px solid var(--li-border);
            box-shadow: 0 0 0 1px rgba(0,0,0,0.04);
            padding: 24px;
            margin-bottom: 24px;
        }

        .page-header h1 {
            font-size: 1.5rem;
            font-weight: 600;
            color: var(--li-text-dark);
        }

        /* Form Elements */
        select, input[type="text"], input[type="date"], textarea, input[type="number"] {
            background-color: var(--li-white);
            border: 1px solid var(--li-text-gray);
            border-radius: 4px;
            padding: 8px 12px;
            font-size: 14px;
            color: var(--li-text-dark);
            transition: border-color 0.2s;
        }

        select:focus, input:focus, textarea:focus {
            border-color: var(--li-blue);
            outline: 1px solid var(--li-blue);
        }

        /* Buttons (LinkedIn Pills) */
        .enter-marks-btn, .btn-primary, .activity-btn-primary, .activity-btn-success {
            background: var(--li-blue);
            color: white;
            border-radius: 24px; /* Pill shape */
            padding: 6px 16px;
            font-weight: 600;
            border: 1px solid transparent;
            box-shadow: none;
            transition: background-color 0.15s ease;
        }

        .enter-marks-btn:hover, .btn-primary:hover, .activity-btn-primary:hover {
            background: var(--li-blue-hover);
            transform: none;
            box-shadow: none;
            text-decoration: underline;
        }

        .btn-secondary, .activity-btn-danger, .activity-btn-warning {
            border-radius: 24px;
            padding: 6px 16px;
            font-weight: 600;
            background: white;
            border: 1px solid var(--li-text-gray);
            color: var(--li-text-gray);
            box-shadow: none;
        }
        
        .activity-btn-danger {
            color: #cc1016;
            border-color: #cc1016;
        }
        
        .activity-btn-danger:hover {
            background-color: #ffeceb;
            box-shadow: inset 0 0 0 1px #cc1016;
        }

        .enter-marks-btn:disabled {
            background: #e0e0e0;
            color: #8c8c8c;
            border: none;
        }

        /* Mode Selector */
        .mode-selector label {
            border-radius: 24px !important;
            border: 1px solid var(--li-text-gray) !important;
            padding: 8px 16px !important;
        }
        
        .mode-selector label:has(input:checked) {
            background-color: #eef3f8 !important;
            border-color: var(--li-blue) !important;
            color: var(--li-blue) !important;
        }
        
        .mode-selector label:has(input:checked) span {
            color: var(--li-blue) !important;
        }
        
        .mode-selector label:has(input:checked) i {
            color: var(--li-blue) !important;
        }

        /* Tables */
        .subjects-table {
            border: 1px solid var(--li-border);
            border-radius: 8px;
            box-shadow: none;
        }

        .subjects-table th {
            background-color: var(--li-white);
            color: var(--li-text-gray);
            font-weight: 600;
            border-bottom: 1px solid var(--li-border);
            font-size: 13px;
            text-transform: uppercase;
        }

        .subjects-table td {
            border-bottom: 1px solid var(--li-border);
            color: var(--li-text-dark);
            font-size: 14px;
        }

        .subjects-table tr:hover {
            background-color: #f9fafb;
        }

        /* Status Badges (Pills) */
        .activity-status-badge {
            border-radius: 4px;
            padding: 4px 8px;
            font-weight: 600;
            font-size: 12px;
        }

        .activity-status-published {
            background-color: #e6f6ec;
            color: #057642; /* LinkedIn Green */
        }

        .activity-status-draft {
            background-color: var(--li-border);
            color: var(--li-text-dark);
        }
        
        .activity-status-active {
            background-color: #dce6f1;
            color: var(--li-blue);
        }

        /* Cards for Activities */
        .activity-card {
            border: 1px solid var(--li-border);
            border-radius: 8px;
            background: white;
            box-shadow: none;
            padding: 16px;
        }
        
        .activity-card:hover {
            box-shadow: 0 0 0 1px rgba(0,0,0,0.1);
            background-color: #fafafa;
        }

        /* Modals */
        .modal-content, .form-modal-content {
            border-radius: 8px;
            box-shadow: 0 4px 12px rgba(0,0,0,0.15);
            border: none;
        }

        .modal-header, .form-modal-header {
            background: var(--li-white);
            border-bottom: 1px solid var(--li-border);
            color: var(--li-text-dark);
            border-radius: 8px 8px 0 0;
            padding: 16px 24px;
        }
        
        .modal-header h3, .form-modal-header h3 {
            font-size: 1.25rem;
            color: var(--li-text-dark);
        }
        
        .close, .form-modal-close {
            color: var(--li-text-gray);
            background: transparent;
        }
        
        .close:hover, .form-modal-close:hover {
            background: #f3f2ef;
            border-radius: 50%;
            color: var(--li-text-dark);
        }

        /* Notifications */
        .notification.success {
            background: #057642; /* Green */
            color: white;
            border-left: none;
            border-radius: 4px;
        }
        
        .notification.error {
            background: #cc1016; /* Red */
            color: white;
            border-left: none;
            border-radius: 4px;
        }

        /* User Profile */
        .user-profile .user-name {
            color: var(--li-text-dark);
            font-size: 14px;
        }
        
        .user-profile .user-email {
            color: var(--li-text-gray);
            font-size: 12px;
        }
        
        .user-profile img {
            border: none;
        }

        /* Overrides for specific elements to remove gradients */
        .btn-info, .activity-btn-warning {
            background: transparent;
            border: 1px solid var(--li-text-gray);
            color: var(--li-text-gray);
        }
        
        .locked-class-row {
            background-color: #fff8f8;
            border-left: 4px solid #cc1016;
        }
        
        .locked-class-badge {
            background: #cc1016;
            color: white;
            border: none;
        }
    </style>
</head>
<body>
    <div class="dashboard-container" id="dashboardContainer">
        <aside class="sidebar" id="sidebar">
            <div class="logo">
                <img src="images/logo.png" alt="divine Logo" style="height: 40px; width: auto;">
                <br> <h8 style="color: var(--li-blue); font-weight: bold;">DIVINE REPORTS</h8></br>
            </div>
            <nav>
                <ul>
                    <li><a href="teacher_dashboard.php" id="dashboardLink"><i class="fas fa-home"></i> <?php echo $_L['sidebar_dashboard']; ?></a></li>
                    <li><a href="teacher_my_classes.php" id="myClassesLink"><i class="fas fa-users"></i> <?php echo $_L['sidebar_my_classes']; ?></a></li>
                    <li><a href="teacher_my_students.php" id="myStudentsLink"><i class="fas fa-user-graduate"></i> <?php echo $_L['sidebar_my_students']; ?></a></li>
                    <li class="hide-on-mobile"><a href="create_assignment.php" id="assignmentsLink"><i class="fas fa-tasks"></i> <?php echo $_L['sidebar_assignments']; ?></a></li>
                    <li class="active"><a href="teacher_exams.php" id="gradesLink"><i class="fas fa-chart-bar"></i> <?php echo $_L['sidebar_grades']; ?></a></li>
                    <li class="hide-on-mobile"><a href="teacher_messages.php" id="messagesLink"><i class="fas fa-comment-dots"></i> <?php echo $_L['sidebar_messages']; ?></a></li>
                    <li class="hide-on-mobile"><a href="teacher_calendar.php" id="calendarLink"><i class="far fa-calendar-alt"></i> <?php echo $_L['sidebar_calendar']; ?></a></li>
                    <li class="hide-on-mobile"><a href="teacher_profile.php" id="profileLink"><i class="fas fa-user-circle"></i> <?php echo $_L['sidebar_profile']; ?></a></li>
                    <li class="hide-on-mobile"><a href="teacher_settings.php" id="settingsLink"><i class="fas fa-cog"></i> <?php echo $_L['sidebar_settings']; ?></a></li>
                    <li class="hide-on-mobile"><a href="logout.php" id="logoutLinkSidebar"><i class="fas fa-sign-out-alt"></i> <?php echo $_L['sidebar_logout']; ?></a></li>
                </ul>
            </nav>
        </aside>

        <div class="main-content">
            <header class="header">
                <button class="menu-toggle" id="menuToggle" style="color: var(--li-text-gray);">
                    <i class="fas fa-bars"></i>
                </button>
                <div class="school-info">
                    <img src="<?php echo $school_logo_path; ?>" alt="<?php echo $school_name; ?> Logo" style="height: 30px; width: auto; margin-right: 10px;">
                    <h1><?php echo $school_name; ?></h1>
                </div>
                <div class="header-right">
                    <div class="language-select">
                        <select id="languageSelector" onchange="changeLanguage(this.value)" style="border: none; background: transparent; font-weight: 600;">
                           <option value="en" <?php if ($current_lang === 'en') echo 'selected'; ?>>🇬🇧 English</option>
                           <option value="lug" <?php if ($current_lang === 'lug') echo 'selected'; ?>>🇺🇬 Luganda</option>
                           <option value="sw" <?php if ($current_lang === 'sw') echo 'selected'; ?>>🇹🇿 Kiswahili</option>
                        </select>
                    </div>
                    <div class="search-bar">
                        <i class="fas fa-search"></i>
                        <input type="text" placeholder="<?php echo $_L['search_placeholder']; ?>">
                    </div>
                    <div class="notifications">
                        <i class="fas fa-bell" style="color: var(--li-text-gray);"></i>
                        <span class="badge" style="background: #cc1016;">3</span>
                    </div>
                    <div class="user-profile">
                        <img src="<?php echo $photo; ?>" alt="User Photo">
                        <div>
                            <div class="user-name"><?php echo $username; ?></div>
                            <div class="user-email"><?php echo $_L['logged_in_as']; ?> <?php echo $role_name; ?></div>
                        </div>
                        <i class="fas fa-caret-down" style="color: var(--li-text-gray);"></i>
                    </div>
                </div>
            </header>

            <div class="dashboard-content" style="padding: 24px; max-width: 1200px; margin: 0 auto;">
                <div class="exams-container">
                    <div class="page-header">
                        <h1><?php echo $_L['page_title']; ?></h1>
                    </div>

                    <div class="mode-selector" style="margin-bottom: 24px;">
                        <label style="display: block; font-weight: 600; color: var(--li-text-gray); margin-bottom: 12px; font-size: 12px; text-transform: uppercase;">
                            <i class="fas fa-list-ul"></i> Select Mode:
                        </label>
                        <div style="display: flex; gap: 12px; flex-wrap: wrap;">
                            <label style="display: flex; align-items: center; cursor: pointer; padding: 8px 16px; border: 1px solid #ccc; border-radius: 16px; background: white; transition: all 0.2s;">
                                <input type="radio" name="mode" value="exam" checked onchange="switchMode(this.value)" style="margin-right: 8px;">
                                <span style="font-weight: 600; font-size: 14px;">
                                    <i class="fas fa-clipboard-check" style="margin-right: 6px;"></i>
                                    Enter Marks for Exam
                                </span>
                            </label>
                            <label style="display: flex; align-items: center; cursor: pointer; padding: 8px 16px; border: 1px solid #ccc; border-radius: 16px; background: white; transition: all 0.2s;">
                                <input type="radio" name="mode" value="integration" onchange="switchMode(this.value)" style="margin-right: 8px;">
                                <span style="font-weight: 600; font-size: 14px;">
                                    <i class="fas fa-project-diagram" style="margin-right: 6px;"></i>
                                    Integration Activities
                                </span>
                            </label>
                        </div>
                    </div>

                    <div id="examModeSection">
                        <div class="exam-selector">
                            <label for="examSelect" style="color: var(--li-text-dark); font-weight: 600;"><?php echo $_L['select_exam']; ?></label>
                            <select id="examSelect" onchange="loadSubjects()">
                                <option value=""><?php echo $_L['select_exam_placeholder']; ?></option>
                                <?php foreach ($exams as $exam): ?>
                                    <option value="<?php echo $exam['exam_id']; ?>">
                                        <?php echo htmlspecialchars($exam['exam_name']) . ' - ' . date('M j, Y', strtotime($exam['created_at'])); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>

                        <div id="examPublishingControls" class="exam-publishing-controls" style="display: none; background: #eef3f8; border: none; padding: 20px; border-radius: 8px; margin-top: 20px;">
                            <div class="publishing-status-card" style="border: 1px solid var(--li-card-border); box-shadow: none; background: white; padding: 20px; border-radius: 8px;">
                                <div class="status-header" style="display: flex; align-items: center; margin-bottom: 16px;">
                                    <i class="fas fa-shield-alt" style="color: var(--li-blue); margin-right: 8px;"></i>
                                    <span class="status-title" style="font-weight: 600; font-size: 1.1rem;">Exam Publishing Status</span>
                                </div>
                                <div class="status-content">
                                    <div class="status-row" style="display: flex; justify-content: space-between; padding: 8px 0; border-bottom: 1px solid #f1f5f9;">
                                        <span class="status-label" style="color: #666;">Current Status:</span>
                                        <span id="currentExamStatus" class="status-value" style="font-weight: 600;">Draft</span>
                                    </div>
                                    <div class="status-row" style="display: flex; justify-content: space-between; padding: 8px 0; border-bottom: 1px solid #f1f5f9;">
                                        <span class="status-label" style="color: #666;">Submitted:</span>
                                        <span id="examSubmissionStatus" class="status-value" style="font-weight: 600;">Not submitted</span>
                                    </div>
                                    <div class="action-buttons" style="margin-top: 16px; display: flex; gap: 10px;">
                                        <div id="examPublishingButton"></div>
                                        <button type="button" class="btn btn-secondary" onclick="showReviewStatusModal()" title="View review details">
                                            <i class="fas fa-info-circle"></i> Status Details
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="subjects-section" id="subjectsSection" style="display: none; margin-top: 24px;">
                            <h2 style="font-size: 1.1rem; color: var(--li-text-dark); margin-bottom: 15px; font-weight: 600;"><?php echo $_L['assigned_subjects_title']; ?></h2>
                            <div id="subjectsContent">
                                <div class="loading-message" style="text-align: center; padding: 40px; color: var(--li-text-gray);">
                                    <span class="loading-spinner" style="border-top-color: var(--li-blue);"></span>
                                    <?php echo $_L['loading']; ?>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div id="integrationModeSection" style="display: none;">
                        <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
                            <h2 style="margin: 0; font-size: 1.25rem; font-weight: 600;">
                                <i class="fas fa-project-diagram" style="margin-right: 8px; color: #10b981;"></i>
                                Integration Activities
                            </h2>
                            <button class="btn-primary" onclick="openCreateActivityModal()" style="display: flex; align-items: center; gap: 8px;">
                                <i class="fas fa-plus-circle"></i>
                                Create New Activity
                            </button>
                        </div>
                        
                        <div id="activitiesContent">
                            <div class="loading-message" style="text-align: center; padding: 40px; color: var(--li-text-gray);">
                                <span class="loading-spinner" style="border-top-color: var(--li-blue);"></span>
                                Loading activities...
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div id="mobile-footer-nav" style="border-top: 1px solid var(--li-border);">
        <ul>
            <li>
                <a href="teacher_dashboard.php" data-section="dashboard">
                    <i class="fas fa-th-large"></i>
                    <span><?php echo $_L['sidebar_dashboard']; ?></span>
                </a>
            </li>
            <li>
                <a href="teacher_my_classes.php" data-section="my-classes">
                    <i class="fas fa-chalkboard"></i>
                    <span><?php echo $_L['sidebar_my_classes']; ?></span>
                </a>
            </li>
            <li>
                <a href="teacher_my_students.php" data-section="my-students">
                    <i class="fas fa-user-graduate"></i>
                    <span><?php echo $_L['sidebar_my_students']; ?></span>
                </a>
            </li>
            <li>
                <a href="#" id="moreMenuButton" data-section="more">
                    <i class="fas fa-ellipsis-h"></i>
                    <span><?php echo $_L['more_menu']; ?></span>
                </a>
            </li>
        </ul>
    </div>

    <div id="more-menu-modal">
        <div id="more-menu-modal-header">
            <h3><?php echo $_L['more_menu']; ?></h3>
            <button id="more-menu-close-btn"><i class="fas fa-times"></i></button>
        </div>
        <ul id="more-menu-list">
            <li><a href="create_assignment.php" id="modalAssignmentsLink"><i class="fas fa-file-alt"></i> <?php echo $_L['sidebar_assignments']; ?></a></li>
            <li><a href="teacher_exams.php" id="modalGradesLink" class="active"><i class="fas fa-award"></i> <?php echo $_L['sidebar_grades']; ?></a></li>
            <li><a href="teacher_messages.php" id="modalMessagesLink"><i class="fas fa-envelope"></i> <?php echo $_L['sidebar_messages']; ?></a></li>
            <li><a href="teacher_calendar.php" id="modalCalendarLink"><i class="far fa-calendar-alt"></i> <?php echo $_L['sidebar_calendar']; ?></a></li>
            <li><a href="teacher_profile.php" id="modalProfileLink"><i class="fas fa-user-circle"></i> <?php echo $_L['sidebar_profile']; ?></a></li>
            <li><a href="teacher_settings.php" id="modalSettingsLink"><i class="fas fa-cog"></i> <?php echo $_L['sidebar_settings']; ?></a></li>
            <li class="logout"><a href="logout.php" id="modalLogoutLink"><i class="fas fa-sign-out-alt"></i> <?php echo $_L['sidebar_logout']; ?></a></li>
        </ul>
    </div>

    <div id="marksModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h3 id="modalTitle"><?php echo $_L['marks_entry_title']; ?></h3>
                <button class="close" onclick="closeMarksModal()">&times;</button>
            </div>
            <div class="modal-body">
                <div id="paperSelectionSection" style="display: none; margin-bottom: 20px; padding: 15px; background-color: #f3f2ef; border-radius: 8px; border: 1px solid #e0e0e0;">
                    <label for="paperSelect" style="display: block; margin-bottom: 8px; font-weight: 600; color: #191919;">
                        <i class="fas fa-file-alt" style="margin-right: 8px;"></i>
                        <?php echo $_L['select_paper'] ?? 'Select Paper'; ?>:
                    </label>
                    <select id="paperSelect" onchange="loadStudentsForSelectedPaper()" style="width: 100%; padding: 10px; border: 1px solid #ced4da; border-radius: 6px; background-color: white; font-size: 14px;">
                        <option value="">Choose paper to enter marks for...</option>
                    </select>
                    <small style="color: #6c757d; font-size: 12px; margin-top: 5px; display: block; font-style: italic;">
                        Select a specific paper to enter marks for all students
                    </small>
                </div>
                
                <div id="studentsTableContainer">
                    </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn-secondary" onclick="closeMarksModal()"><?php echo $_L['cancel']; ?></button>
                <button type="button" class="btn-primary" onclick="saveMarks()"><?php echo $_L['save_marks']; ?></button>
            </div>
        </div>
    </div>

    <div id="createActivityModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h3>
                    <i class="fas fa-plus-circle" style="margin-right: 8px; color: #10b981;"></i>
                    Create Integration Activity
                </h3>
                <button class="close" onclick="closeCreateActivityModal()">&times;</button>
            </div>
            <div class="modal-body">
                <form id="createActivityForm" style="display: grid; gap: 20px;">
                    <div>
                        <label style="display: block; font-weight: 500; color: #374151; margin-bottom: 8px;">
                            <i class="fas fa-chalkboard"></i> Class & Stream *
                        </label>
                        <select id="activityStreamSelect" required style="width: 100%;">
                            <option value="">Select Class & Stream...</option>
                        </select>
                    </div>

                    <div>
                        <label style="display: block; font-weight: 500; color: #374151; margin-bottom: 8px;">
                            <i class="fas fa-book"></i> Subject *
                        </label>
                        <select id="activitySubjectSelect" required style="width: 100%;">
                            <option value="">Select Subject...</option>
                        </select>
                    </div>

                    <div>
                        <label style="display: block; font-weight: 500; color: #374151; margin-bottom: 8px;">
                            <i class="fas fa-lightbulb"></i> Topic *
                        </label>
                        <select id="activityTopicSelect" required onchange="loadCompetencies()" style="width: 100%;">
                            <option value="">Select Topic...</option>
                        </select>
                    </div>

                    <div>
                        <label style="display: block; font-weight: 500; color: #374151; margin-bottom: 8px;">
                            <i class="fas fa-star"></i> Competency *
                        </label>
                        <select id="activityCompetencySelect" required style="width: 100%;">
                            <option value="">Select Competency...</option>
                        </select>
                    </div>

                    <div>
                        <label style="display: block; font-weight: 500; color: #374151; margin-bottom: 8px;">
                            <i class="fas fa-heading"></i> Title *
                        </label>
                        <input type="text" id="activityTitle" required placeholder="Enter activity title..." style="width: 100%;">
                    </div>

                    <div>
                        <label style="display: block; font-weight: 500; color: #374151; margin-bottom: 8px;">
                            <i class="fas fa-align-left"></i> Description
                        </label>
                        <textarea id="activityDescription" rows="4" placeholder="Enter activity description..." style="width: 100%;"></textarea>
                    </div>

                    <div>
                        <label style="display: block; font-weight: 500; color: #374151; margin-bottom: 8px;">
                            <i class="fas fa-calendar-alt"></i> Due Date *
                        </label>
                        <input type="date" id="activityDueDate" required style="width: 100%;">
                    </div>

                    <div>
                        <label style="display: block; font-weight: 500; color: #374151; margin-bottom: 8px;">
                            <i class="fas fa-info-circle"></i> Initial Status
                        </label>
                        <div style="display: flex; align-items: center; padding: 12px; background-color: #f3f4f6; border-radius: 8px; border: 1px solid #d1d5db;">
                            <span class="activity-status-badge activity-status-draft" style="margin: 0;">
                                Draft
                            </span>
                            <span style="margin-left: 12px; color: #6b7280; font-size: 0.875rem;">
                                Status will change to "Captured" when you save marks
                            </span>
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn-secondary" onclick="closeCreateActivityModal()">Cancel</button>
                <button type="button" class="btn-primary" onclick="createActivity()">
                    <i class="fas fa-save" style="margin-right: 6px;"></i>
                    Create Activity
                </button>
            </div>
        </div>
    </div>

    <div id="activityMarksModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h3 id="activityModalTitle">Enter Marks for Activity</h3>
                <button class="close" onclick="closeActivityMarksModal()">&times;</button>
            </div>
            <div class="modal-body">
                <div id="activityStudentsTableContainer">
                    </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn-secondary" onclick="closeActivityMarksModal()">Cancel</button>
                <button type="button" class="btn-primary" onclick="saveActivityMarks()">
                    <i class="fas fa-save" style="margin-right: 6px;"></i>
                    Save Marks
                </button>
            </div>
        </div>
    </div>

    <div id="publishAfterSaveModal" class="form-modal">
        <div class="form-modal-content">
            <div class="form-modal-header" style="background: white; border-bottom: 1px solid #e0e0e0; color: #191919;">
                <h3><i class="fas fa-check-circle" style="color: #0a66c2;"></i> Publish Subject Marks</h3>
                <button class="form-modal-close" onclick="hidePublishAfterSaveModal()" style="color: #666;">&times;</button>
            </div>
            <div class="form-modal-body">
                <div class="info-box" style="background: #eef3f8; border: 1px solid #0a66c2; border-radius: 8px; padding: 16px; margin-bottom: 16px;">
                    <i class="fas fa-info-circle" style="color: #0a66c2;"></i>
                    <strong>Marks saved successfully!</strong>
                </div>
                <p>Would you like to publish this subject now? Once published:</p>
                <ul>
                    <li><i class="fas fa-lock" style="color: #cc1016;"></i> Further editing will be blocked</li>
                    <li><i class="fas fa-shield-alt" style="color: #057642;"></i> Only administrators can unpublish</li>
                    <li><i class="fas fa-eye" style="color: #0a66c2;"></i> Marks will be visible to students</li>
                </ul>
                <p><strong>Subject:</strong> <span id="publishSubjectName"></span></p>
                <p><strong>Class:</strong> <span id="publishClassName"></span></p>
            </div>
            <div class="form-modal-footer">
                <button type="button" class="btn btn-secondary" onclick="hidePublishAfterSaveModal()">
                    <i class="fas fa-times"></i> Save for Later
                </button>
                <button type="button" class="btn btn-primary" onclick="confirmPublishCurrentSubject()">
                    <i class="fas fa-check"></i> Yes, Publish Now
                </button>
            </div>
        </div>
    </div>

    <div id="unpublishModal" class="form-modal">
        <div class="form-modal-content">
            <div class="form-modal-header" style="background: white; color: #191919;">
                <h3><i class="fas fa-lock-open" style="color: #fbbf24;"></i> Unpublish Subject Marks</h3>
                <button class="form-modal-close" onclick="hideUnpublishModal()" style="color: #666;">&times;</button>
            </div>
            <div class="form-modal-body">
                <div class="warning-box" style="background: #fef3c7; border: 1px solid #f59e0b; border-radius: 8px; padding: 16px; margin: 16px 0;">
                    <i class="fas fa-exclamation-triangle" style="color: #f59e0b;"></i>
                    <strong>Admin Action Required</strong>
                </div>
                <p>Are you sure you want to unpublish this subject?</p>
                <p><strong>Subject:</strong> <span id="unpublishSubjectName"></span></p>
                <p><strong>Class:</strong> <span id="unpublishClassName"></span></p>
                <p><strong>Effects of Unpublishing:</strong></p>
                <ul>
                    <li><i class="fas fa-unlock" style="color: #10b981;"></i> Teachers can edit marks again</li>
                    <li><i class="fas fa-edit" style="color: #3b82f6;"></i> New entries can be made</li>
                    <li><i class="fas fa-redo" style="color: #f59e0b;"></i> Status will return to "Captured"</li>
                </ul>
            </div>
            <div class="form-modal-footer">
                <button type="button" class="btn btn-secondary" onclick="hideUnpublishModal()">
                    <i class="fas fa-times"></i> Cancel
                </button>
                <button type="button" class="btn btn-primary" style="background: #cc1016;" onclick="executeUnpublishSubject()">
                    <i class="fas fa-lock-open"></i> Yes, Unpublish
                </button>
            </div>
        </div>
    </div>

    <div id="alreadyPublishedModal" class="form-modal">
        <div class="form-modal-content">
            <div class="form-modal-header" style="background: white; color: #cc1016;">
                <h3><i class="fas fa-lock"></i> Subject Already Published</h3>
                <button class="form-modal-close" onclick="hideAlreadyPublishedModal()" style="color: #666;">&times;</button>
            </div>
            <div class="form-modal-body">
                <div class="warning-box" style="background: #fef3c7; border: 1px solid #f59e0b; border-radius: 8px; padding: 16px; margin: 16px 0;">
                    <i class="fas fa-lock"></i>
                    <strong>Editing Blocked</strong>
                </div>
                <p>This subject is already published and cannot be edited.</p>
                <p><strong>Subject:</strong> <span id="publishedSubjectName"></span></p>
                <p><strong>Class:</strong> <span id="publishedClassName"></span></p>
                <p><strong>Next Steps:</strong></p>
                <ul>
                    <li>Contact an administrator to unpublish</li>
                    <li>Only admins can override published status</li>
                    <li>Unpublishing will allow further edits</li>
                </ul>
            </div>
            <div class="form-modal-footer">
                <button type="button" class="btn btn-secondary" onclick="hideAlreadyPublishedModal()">
                    <i class="fas fa-check"></i> OK, I Understand
                </button>
            </div>
        </div>
    </div>

    <div id="examPublishedModal" class="form-modal">
        <div class="form-modal-content">
            <div class="form-modal-header" style="background: white; color: #cc1016;">
                <h3><i class="fas fa-lock"></i> Exam Published - Access Blocked</h3>
                <button class="form-modal-close" onclick="hideExamPublishedModal()" style="color: #666;">&times;</button>
            </div>
            <div class="form-modal-body">
                <div class="warning-box" style="background: #fef3c7; border: 1px solid #f59e0b; border-radius: 8px; padding: 16px; margin: 16px 0;">
                    <i class="fas fa-shield-alt"></i>
                    <strong>Entire Exam is Published</strong>
                </div>
                <p id="examPublishedMessage">This exam has been published by administration.</p>
                <p><strong>Exam:</strong> <span id="publishedExamName"></span></p>
                <p><strong>Published Date:</strong> <span id="publishedExamDate"></span></p>
                <p><strong>What This Means:</strong></p>
                <ul>
                    <li><i class="fas fa-lock" style="color: #ef4444;"></i> All subjects in this exam are locked for editing</li>
                    <li><i class="fas fa-ban" style="color: #dc2626;"></i> Marks entry is temporarily disabled</li>
                    <li><i class="fas fa-shield-alt" style="color: #16a34a;"></i> Only administrators can unpublish the exam</li>
                    <li><i class="fas fa-info-circle" style="color: #3b82f6;"></i> Contact your admin for any required changes</li>
                </ul>
            </div>
            <div class="form-modal-footer">
                <button type="button" class="btn btn-secondary" onclick="hideExamPublishedModal()">
                    <i class="fas fa-check"></i> I Understand
                </button>
            </div>
        </div>
    </div>

    <div id="reviewStatusModal" class="form-modal">
        <div class="form-modal-content">
            <div class="form-modal-header" style="background: white; color: var(--li-blue);">
                <h3><i class="fas fa-clipboard-check"></i> Exam Review Status</h3>
                <button class="form-modal-close" onclick="hideReviewStatusModal()" style="color: #666;">&times;</button>
            </div>
            <div class="form-modal-body">
                <div class="info-box" style="background: #eef3f8; border: 1px solid #0a66c2; border-radius: 8px; padding: 16px; margin-bottom: 16px;">
                    <i class="fas fa-info-circle" style="color: #0a66c2;"></i>
                    <strong>Current Review Status</strong>
                </div>
                
                <div class="status-details">
                    <div class="status-item" style="display: flex; justify-content: space-between; align-items: flex-start; padding: 8px 0; border-bottom: 1px solid #e2e8f0;">
                        <span class="status-label" style="font-weight: 500; color: #475569;">Status:</span>
                        <span id="reviewStatusText" class="status-value" style="font-weight: 600;">Draft</span>
                    </div>
                    <div class="status-item" style="display: flex; justify-content: space-between; align-items: flex-start; padding: 8px 0; border-bottom: 1px solid #e2e8f0;">
                        <span class="status-label" style="font-weight: 500; color: #475569;">Submitted:</span>
                        <span id="submittedAtText" class="status-value" style="font-weight: 600;">Not submitted</span>
                    </div>
                    <div class="status-item" style="display: flex; justify-content: space-between; align-items: flex-start; padding: 8px 0; border-bottom: 1px solid #e2e8f0;">
                        <span class="status-label" style="font-weight: 500; color: #475569;">Admin Notes:</span>
                        <div id="adminNotesText" class="admin-notes" style="font-style: italic; color: #6b7280;">No notes from admin</div>
                    </div>
                </div>

                <div class="workflow-info" style="margin-top: 20px; padding: 16px; background: #f0f9ff; border-radius: 8px; border: 1px solid #0ea5e9;">
                    <h4 style="margin: 0 0 12px 0; color: #0369a1; display: flex; align-items: center; gap: 8px;"><i class="fas fa-route"></i> Review Workflow</h4>
                    <div class="workflow-steps" style="display: flex; flex-direction: column; gap: 8px;">
                        <div class="step" style="display: flex; align-items: center; gap: 12px;">
                            <i class="fas fa-edit step-icon"></i>
                            <span class="step-text">1. Draft - You can edit freely</span>
                        </div>
                        <div class="step" style="display: flex; align-items: center; gap: 12px;">
                            <i class="fas fa-paper-plane step-icon"></i>
                            <span class="step-text">2. Submit for Review - Locks for editing</span>
                        </div>
                        <div class="step" style="display: flex; align-items: center; gap: 12px;">
                            <i class="fas fa-search step-icon"></i>
                            <span class="step-text">3. Admin Review - 24-48 hours</span>
                        </div>
                        <div class="step" style="display: flex; align-items: center; gap: 12px;">
                            <i class="fas fa-check-circle step-icon"></i>
                            <span class="step-text">4. Published - Available to students</span>
                        </div>
                    </div>
                </div>
            </div>
            <div class="form-modal-footer">
                <button type="button" class="btn btn-secondary" onclick="hideReviewStatusModal()">
                    <i class="fas fa-check"></i> Got it
                </button>
            </div>
        </div>
    </div>

    <div class="saving-overlay" id="savingOverlay">
        <div class="saving-content">
            <div class="saving-spinner"></div>
            <div class="saving-text">Saving marks...</div>
        </div>
    </div>

    <div class="overlay" id="overlay"></div>

    <script>
        // Global variables
        const currentUserId = <?php echo $user_id; ?>;
        const currentSchoolId = <?php echo $current_user_school_id; ?>;
        const currentUserRole = <?php echo $user_role_code; ?>;
        const currentLang = "<?php echo $current_lang; ?>";
        let currentExamId = null;
        // Subject-level status is now managed individually for each subject
        let currentSubjectData = null;

        // Language data for JavaScript
        const langData = {
            'en': {
                'loading': '<?php echo addslashes($_L['loading']); ?>',
                'error_occurred': '<?php echo addslashes($_L['error_occurred']); ?>',
                'no_subjects_assigned': '<?php echo addslashes($_L['no_subjects_assigned']); ?>',
                'marks_saved_success': '<?php echo addslashes($_L['marks_saved_success']); ?>',
                'invalid_mark': '<?php echo addslashes($_L['invalid_mark']); ?>',
                'multi_paper_validation_error': '<?php echo addslashes($_L['multi_paper_validation_error']); ?>',
                'paper_selection_required': '<?php echo addslashes($_L['paper_selection_required']); ?>',
                'complete_all_papers_before_save': '<?php echo addslashes($_L['complete_all_papers_before_save']); ?>',
                'multi_paper_missing_summary': '<?php echo addslashes($_L['multi_paper_missing_summary']); ?>',
                'class_label': '<?php echo addslashes($_L['class_label']); ?>',
                'stream_label': '<?php echo addslashes($_L['stream_label']); ?>',
                'subject_label': '<?php echo addslashes($_L['subject_label']); ?>',
                'options_label': '<?php echo addslashes($_L['options_label']); ?>',
                'enter_marks_button': '<?php echo addslashes($_L['enter_marks_button']); ?>',
                'student_name': '<?php echo addslashes($_L['student_name']); ?>',
                'current_mark': '<?php echo addslashes($_L['current_mark']); ?>',
                'new_mark': '<?php echo addslashes($_L['new_mark']); ?>',
                'marks_entry_title': '<?php echo addslashes($_L['marks_entry_title']); ?>'
            },
            'lug': {
                'loading': 'Kutegeka...',
                'error_occurred': 'Wabaddewo ensobi. Ddamu okugezaako.',
                'no_subjects_assigned': 'Tewali masomo gakutwaliddwa mu kikebera kino.',
                'marks_saved_success': 'Obubonero buwonyiddwa obulungi!',
                'invalid_mark': 'Yingiza obubonero obukkirizibwa (0-100).',
                'class_label': 'KIBIINA',
                'stream_label': 'KIRAGIRA',
                'subject_label': 'EKISOMO',
                'options_label': 'ENKULUNGEKO',
                'enter_marks_button': 'Yingiza Obubonero',
                'student_name': 'Erinnya ly\'Omuyizi',
                'paper': 'Ekitabo',
                'current_mark': 'Obubonero Obwo Waliwo',
                'new_mark': 'Obubonero Obupya',
                'marks_entry_title': 'Yingiza Obubonero bwa'
            },
            'sw': {
                'loading': 'Inapakia...',
                'error_occurred': 'Hitilafu imetokea. Tafadhali jaribu tena.',
                'no_subjects_assigned': 'Hakuna masomo yaliyokabidhiwa kwa mtihani huu.',
                'marks_saved_success': 'Alama zimehifadhiwa kwa ufanisi!',
                'invalid_mark': 'Tafadhali weka alama halali (0-100).',
                'class_label': 'DARASA',
                'stream_label': 'MKONDO',
                'subject_label': 'SOMO',
                'options_label': 'MACHAGUO',
                'enter_marks_button': 'Weka Alama',
                'student_name': 'Jina la Mwanafunzi',
                'paper': 'Kibali',
                'current_mark': 'Alama ya Sasa',
                'new_mark': 'Alama Mpya',
                'marks_entry_title': 'Weka Alama za'
            }
        };

        const _ = langData[currentLang] || langData['en'];

        // =========================== //
        // NOTIFICATION SYSTEM FUNCTIONS //
        // =========================== //
        
        // Notification System
        function showNotification(message, type = 'success') {
            // Remove existing notifications
            const existingNotifications = document.querySelectorAll('.notification');
            existingNotifications.forEach(notification => {
                notification.remove();
            });

            // Create notification element
            const notification = document.createElement('div');
            notification.className = `notification ${type}`;
            
            // Set icon based on type
            let icon = '';
            switch(type) {
                case 'success':
                    icon = '<i class="fas fa-check-circle"></i>';
                    break;
                case 'error':
                    icon = '<i class="fas fa-exclamation-circle"></i>';
                    break;
                case 'warning':
                    icon = '<i class="fas fa-exclamation-triangle"></i>';
                    break;
                default:
                    icon = '<i class="fas fa-info-circle"></i>';
            }
            
            notification.innerHTML = `
                ${icon}
                <div class="message">${message}</div>
                <button class="close-btn" onclick="closeNotification(this)">&times;</button>
            `;
            
            // Add to page
            document.body.appendChild(notification);
            
            // Show notification
            setTimeout(() => {
                notification.classList.add('show');
            }, 100);
            
            // Auto hide after 5 seconds
            setTimeout(() => {
                closeNotification(notification.querySelector('.close-btn'));
            }, 5000);
        }

        function closeNotification(closeBtn) {
            const notification = closeBtn.closest('.notification');
            notification.classList.remove('show');
            setTimeout(() => {
                if (notification && notification.parentNode) {
                    notification.remove();
                }
            }, 300);
        }

        // =========================== //
        // SUCCESS MODAL SYSTEM //
        // =========================== //
        
        // Professional Success Modal with Green Checkmark
        function showSuccessModal(message) {
            // Remove any existing modal
            const existingModal = document.getElementById('successModal');
            if (existingModal) {
                existingModal.remove();
            }

            // Create modal overlay
            const modalOverlay = document.createElement('div');
            modalOverlay.id = 'successModal';
            modalOverlay.className = 'success-modal-overlay';

            // Create modal content
            modalOverlay.innerHTML = `
                <div class="success-modal">
                    <div class="success-icon">
                        <svg width="60" height="60" viewBox="0 0 60 60" fill="none" xmlns="http://www.w3.org/2000/svg">
                            <circle cx="30" cy="30" r="30" fill="#10B981"/>
                            <path d="M18 30L26 38L42 22" stroke="white" stroke-width="4" stroke-linecap="round" stroke-linejoin="round"/>
                        </svg>
                    </div>
                    <h3 class="success-title">Success!</h3>
                    <p class="success-message">${message}</p>
                    <button class="success-btn" onclick="closeSuccessModal()">OK</button>
                </div>
            `;

            // Add to page
            document.body.appendChild(modalOverlay);

            // Show modal with animation
            setTimeout(() => {
                modalOverlay.classList.add('show');
            }, 100);

            // Auto close after 3 seconds
            setTimeout(() => {
                closeSuccessModal();
            }, 3000);

            // Add click outside to close
            modalOverlay.addEventListener('click', function(e) {
                if (e.target === modalOverlay) {
                    closeSuccessModal();
                }
            });

            // Add Escape key to close
            document.addEventListener('keydown', function(e) {
                if (e.key === 'Escape') {
                    closeSuccessModal();
                }
            });
        }

        function closeSuccessModal() {
            const modal = document.getElementById('successModal');
            if (modal) {
                modal.classList.remove('show');
                setTimeout(() => {
                    if (modal && modal.parentNode) {
                        modal.remove();
                    }
                }, 300);
            }
        }

        // =========================== //
        // WARNING MODAL SYSTEM //
        // =========================== //
        
        // Professional Warning Modal with Orange Exclamation
        function showWarningModal(message) {
            // Remove any existing modal
            const existingModal = document.getElementById('warningModal');
            if (existingModal) {
                existingModal.remove();
            }

            // Create modal overlay
            const modalOverlay = document.createElement('div');
            modalOverlay.id = 'warningModal';
            modalOverlay.className = 'warning-modal-overlay';

            // Create modal content
            modalOverlay.innerHTML = `
                <div class="warning-modal">
                    <div class="warning-icon">
                        <svg width="60" height="60" viewBox="0 0 60 60" fill="none" xmlns="http://www.w3.org/2000/svg">
                            <circle cx="30" cy="30" r="30" fill="#F59E0B"/>
                            <path d="M30 15C26.134 15 23 18.134 23 22V32C23 35.866 26.134 39 30 39C33.866 39 37 35.866 37 32V22C37 18.134 33.866 15 30 15Z" fill="white"/>
                            <path d="M30 25C29.448 25 29 25.448 29 26V34C29 34.552 29.448 35 30 35C30.552 35 31 34.552 31 34V26C31 25.448 30.552 25 30 25Z" fill="#F59E0B"/>
                            <circle cx="30" cy="18" r="2" fill="#F59E0B"/>
                        </svg>
                    </div>
                    <h3 class="warning-title">Attention Required</h3>
                    <p class="warning-message">${message}</p>
                    <button class="warning-btn" onclick="closeWarningModal()">OK</button>
                </div>
            `;

            // Add to page
            document.body.appendChild(modalOverlay);

            // Show modal with animation
            setTimeout(() => {
                modalOverlay.classList.add('show');
            }, 100);

            // Don't auto-close warning modals - user must acknowledge
            // Add click outside to close
            modalOverlay.addEventListener('click', function(e) {
                if (e.target === modalOverlay) {
                    closeWarningModal();
                }
            });
        }

        function closeWarningModal() {
            const modal = document.getElementById('warningModal');
            if (modal) {
                modal.classList.remove('show');
                setTimeout(() => {
                    if (modal && modal.parentNode) {
                        modal.remove();
                    }
                }, 300);
            }
        }

        function showSavingOverlay(show = true) {
            const overlay = document.getElementById('savingOverlay');
            if (show) {
                overlay.classList.add('show');
            } else {
                overlay.classList.remove('show');
            }
        }

        document.addEventListener('DOMContentLoaded', function() {
            const menuToggle = document.getElementById('menuToggle');
            const sidebar = document.getElementById('sidebar');
            const dashboardContainer = document.getElementById('dashboardContainer');
            const overlay = document.getElementById('overlay');

            if(menuToggle) {
                menuToggle.addEventListener('click', function() {
                    sidebar.classList.toggle('active');
                    dashboardContainer.classList.toggle('sidebar-open');
                    overlay.classList.toggle('active');
                });
            }

            if(overlay) {
                overlay.addEventListener('click', function() {
                    sidebar.classList.remove('active');
                    dashboardContainer.classList.remove('sidebar-open');
                    overlay.classList.remove('active');
                    toggleMoreMenu(false);
                });
            }

            // Mobile menu functionality
            const moreMenuButton = document.getElementById('moreMenuButton');
            const moreMenuModal = document.getElementById('more-menu-modal');
            const moreMenuCloseBtn = document.getElementById('more-menu-close-btn');

            if (moreMenuButton) {
                moreMenuButton.addEventListener('click', (e) => {
                    e.preventDefault();
                    toggleMoreMenu(true);
                });
            }

            if (moreMenuCloseBtn) {
                moreMenuCloseBtn.addEventListener('click', () => {
                    toggleMoreMenu(false);
                });
            }
        });

        function toggleMoreMenu(show) {
            const moreMenuModal = document.getElementById('more-menu-modal');
            const overlay = document.getElementById('overlay');
            
            if (show) {
                moreMenuModal.classList.add('show');
                overlay.classList.add('show');
                document.body.style.overflow = 'hidden';
            } else {
                moreMenuModal.classList.remove('show');
                overlay.classList.remove('show');
                document.body.style.overflow = '';
            }
        }

        function changeLanguage(selectedLang) {
            window.location.href = '?lang=' + selectedLang;
        }

        // Enhanced loadSubjects function
        function loadSubjects() {
            const examId = document.getElementById('examSelect').value;
            const subjectsSection = document.getElementById('subjectsSection');
            const subjectsContent = document.getElementById('subjectsContent');

            if (!examId) {
                subjectsSection.style.display = 'none';
                return;
            }

            currentExamId = examId;
            subjectsSection.style.display = 'block';
            
            // Show loading with better styling
            subjectsContent.innerHTML = `
                <div class="loading-message">
                    <div class="loading-spinner"></div>
                    <strong>${_.loading}</strong>
                    <div style="font-size: 0.875rem; color: #6b7280; margin-top: 4px;">
                        Fetching your assigned subjects...
                    </div>
                </div>
            `;

            // NEW: Class-level locking - fetch subjects directly with individual class status
            // Skip whole-exam checking, let each class be checked individually
            
            updateExamPublishingControls(examId);
            fetchSubjectsClassLevel(); // Use the new class-level function
        }
        
        // Helper function to fetch subjects (separated for reuse)
        function fetchSubjects() {
            const examId = currentExamId;
            const subjectsContent = document.getElementById('subjectsContent');
            
            // Clear cached data before fetching new subjects
            clearCachedData();
            
            console.log('Fetching subjects for exam:', examId, 'teacher:', currentUserId, 'school:', currentSchoolId);
            
            fetch('ajax_get_exam_subjects.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: 'exam_id=' + encodeURIComponent(examId) + 
                      '&school_id=' + encodeURIComponent(currentSchoolId) + 
                      '&teacher_id=' + encodeURIComponent(currentUserId) +
                      '&action=get_exam_subjects'
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    displaySubjects(data.subjects);
                } else {
                    subjectsContent.innerHTML = `
                        <div class="empty-message">
                            <i class="fas fa-exclamation-triangle" style="margin-right: 8px; color: #f59e0b;"></i>
                            ${data.message || _.error_occurred}
                        </div>
                    `;
                }
            })
            .catch(error => {
                console.error('Error:', error);
                subjectsContent.innerHTML = `
                    <div class="empty-message">
                        <i class="fas fa-times-circle" style="margin-right: 8px; color: #ef4444;"></i>
                        ${_.error_occurred}
                    </div>
                `;
            });
        }

        // NEW: Class-level subjects fetching function
        function fetchSubjectsClassLevel() {
            const examId = currentExamId;
            const subjectsContent = document.getElementById('subjectsContent');
            
            // Clear cached data before fetching new subjects
            clearCachedData();
            
            console.log('Fetching subjects for exam (class-level):', examId, 'teacher:', currentUserId, 'school:', currentSchoolId);
            
            // Use the new class-level endpoint
            fetch('ajax_get_exam_subjects_class_status.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: 'exam_id=' + encodeURIComponent(examId) + 
                      '&school_id=' + encodeURIComponent(currentSchoolId) + 
                      '&teacher_id=' + encodeURIComponent(currentUserId) +
                      '&action=get_exam_subjects'
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    displaySubjectsClassLevel(data.subjects, data);
                } else {
                    subjectsContent.innerHTML = `
                        <div class="empty-message">
                            <i class="fas fa-exclamation-triangle" style="margin-right: 8px; color: #f59e0b;"></i>
                            ${data.message || _.error_occurred}
                        </div>
                    `;
                }
            })
            .catch(error => {
                console.error('Error fetching subjects:', error);
                subjectsContent.innerHTML = `
                    <div class="empty-message">
                        <i class="fas fa-times-circle" style="margin-right: 8px; color: #ef4444;"></i>
                        ${_.error_occurred}
                    </div>
                `;
            });
        }

        // Clear cached data when switching exams or classes
        function clearCachedData() {
            console.log('Clearing cached data...');
            // Clear any cached student data
            if (window.studentDataCache) {
                delete window.studentDataCache;
            }
            // Clear any cached subject data
            if (window.subjectDataCache) {
                delete window.subjectDataCache;
            }
            console.log('Cached data cleared');
        }

        // Enhanced displaySubjects function
        function displaySubjects(subjects) {
            const subjectsContent = document.getElementById('subjectsContent');
            
            if (!subjects || subjects.length === 0) {
                subjectsContent.innerHTML = `
                    <div class="empty-message">
                        <i class="fas fa-info-circle" style="margin-right: 8px; color: #6b7280;"></i>
                        ${_.no_subjects_assigned}
                    </div>
                `;
                return;
            }

            let tableHTML = `
                <table class="subjects-table">
                    <thead>
                        <tr>
                            <th><i class="fas fa-chalkboard" style="margin-right: 8px;"></i>${_.class_label}</th>
                            <th><i class="fas fa-stream" style="margin-right: 8px;"></i>${_.stream_label}</th>
                            <th><i class="fas fa-book" style="margin-right: 8px;"></i>${_.subject_label}</th>
                            <th><i class="fas fa-flag" style="margin-right: 8px;"></i>Status</th>
                            <th><i class="fas fa-cogs" style="margin-right: 8px;"></i>${_.options_label}</th>
                        </tr>
                    </thead>
                    <tbody>
            `;

            subjects.forEach(subject => {
                const status = subject.subject_status || 'Draft';
                const isPublished = status === 'Published';
                const isDraft = status === 'Draft';
                
                tableHTML += `
                    <tr>
                        <td><strong>${escapeHtml(subject.class_name)}</strong></td>
                        <td><span class="stream-badge">${escapeHtml(subject.stream_name)}</span></td>
                        <td>${escapeHtml(subject.subject_name)}</td>
                        <td>
                            <span class="activity-status-badge activity-status-${status.toLowerCase()}">
                                ${status}
                            </span>
                        </td>
                        <td style="display: flex; gap: 8px; align-items: center;">
                            <button class="enter-marks-btn" 
                                onclick="openMarksModal(${subject.class_id}, ${subject.stream_id}, ${subject.subject_id}, '${escapeHtml(subject.class_name)}', '${escapeHtml(subject.stream_name)}', '${escapeHtml(subject.subject_name)}', '${encodeURIComponent(JSON.stringify(subject))}')"
                                ${isPublished || subject.exam_status === 'Pending Review' || subject.exam_status === 'Published' ? 'disabled title="Cannot edit - ' + (subject.exam_status === 'Pending Review' ? 'Exam is under review by admin' : subject.exam_status === 'Published' ? 'Subject is published and locked' : 'Subject is published') + '"' : ''}>
                                <i class="fas fa-edit" style="margin-right: 6px;"></i>
                                ${_.enter_marks_button}
                            </button>
                            ${currentUserRole == 1 ? `
                                ${isPublished ? `
                                    <button class="activity-btn activity-btn-warning" 
                                        onclick="unpublishSubject(${subject.subject_id})" 
                                        style="background: #fbbf24; color: #78350f; padding: 8px 12px; font-size: 0.875rem;">
                                        <i class="fas fa-lock-open"></i>
                                        Unpublish
                                    </button>
                                ` : `
                                    <button class="activity-btn activity-btn-success" 
                                        onclick="publishSubject(${subject.subject_id})" 
                                        ${isDraft ? 'disabled title="Save marks first to publish"' : ''}
                                        style="background: #10b981; color: white; padding: 8px 12px; font-size: 0.875rem;">
                                        <i class="fas fa-check-circle"></i>
                                        Publish
                                    </button>
                                `}
                            ` : ''}
                        </td>
                    </tr>
                `;
            });

            tableHTML += `
                    </tbody>
                </table>
            `;

            subjectsContent.innerHTML = tableHTML;
        }

        // NEW: Class-level display function that shows individual class status
        function displaySubjectsClassLevel(subjects, data = {}) {
            const subjectsContent = document.getElementById('subjectsContent');
            
            if (!subjects || subjects.length === 0) {
                subjectsContent.innerHTML = `
                    <div class="empty-message">
                        <i class="fas fa-info-circle" style="margin-right: 8px; color: #6b7280;"></i>
                        ${_.no_subjects_assigned}
                    </div>
                `;
                return;
            }

            // Show class-level locking info if available
            const lockingInfo = data.class_level_locking ? 
                `<div style="background: #e0f2fe; border: 1px solid #81d4fa; border-radius: 6px; padding: 12px; margin-bottom: 16px;">
                    <i class="fas fa-info-circle" style="margin-right: 8px; color: #0284c7;"></i>
                    <strong>Class-level locking active:</strong> Each class can be published individually.
                </div>` : '';

            let tableHTML = `
                <table class="subjects-table">
                    <thead>
                        <tr>
                            <th><i class="fas fa-chalkboard" style="margin-right: 8px;"></i>${_.class_label}</th>
                            <th><i class="fas fa-stream" style="margin-right: 8px;"></i>${_.stream_label}</th>
                            <th><i class="fas fa-book" style="margin-right: 8px;"></i>${_.subject_label}</th>
                            <th><i class="fas fa-flag" style="margin-right: 8px;"></i>Class Status</th>
                            <th><i class="fas fa-cogs" style="margin-right: 8px;"></i>${_.options_label}</th>
                        </tr>
                    </thead>
                    <tbody>
            `;

            subjects.forEach(subject => {
                const examStatus = subject.exam_status || 'Draft';
                const isPublished = examStatus === 'Published';
                const isDraft = examStatus === 'Draft';
                
                // Get status display info
                let statusDisplay = '';
                let statusClass = '';
                let disabledText = '';
                let statusIcon = '';
                let statusColor = '';
                
                if (isPublished) {
                    statusDisplay = 'Published & Locked';
                    statusClass = 'published';
                    statusIcon = 'fa-lock';
                    statusColor = '#dc2626';
                    disabledText = 'This class is published and marks entry is LOCKED. Contact admin to unpublish.';
                } else if (isDraft) {
                    statusDisplay = 'Draft';
                    statusClass = 'draft';
                    statusIcon = 'fa-edit';
                    statusColor = '#3b82f6';
                    disabledText = 'This class is still in draft';
                } else {
                    statusDisplay = examStatus;
                    statusClass = examStatus.toLowerCase();
                    statusIcon = examStatus === 'Pending Review' ? 'fa-clock' : 'fa-edit';
                    statusColor = examStatus === 'Pending Review' ? '#f59e0b' : '#3b82f6';
                    disabledText = `Status: ${examStatus}`;
                }
                
                // Use CSS classes for published classes
                const rowClass = isPublished ? 'locked-class-row' : '';
                
                tableHTML += `
                    <tr class="${rowClass}">
                        <td>
                            <strong>${escapeHtml(subject.class_name)}</strong>
                            ${isPublished ? '<div class="locked-warning-text"><i class="fas fa-exclamation-triangle"></i> LOCKED FOR EDITING</div>' : ''}
                        </td>
                        <td><span class="stream-badge">${escapeHtml(subject.stream_name)}</span></td>
                        <td>${escapeHtml(subject.subject_name)}</td>
                        <td>
                            <span class="activity-status-badge ${isPublished ? 'locked-class-badge' : ''}">
                                <i class="fas ${statusIcon}" style="margin-right: 6px;"></i>
                                ${statusDisplay}
                            </span>
                            ${isPublished && subject.published_date ? `
                                <div style="font-size: 0.75rem; color: #991b1b; margin-top: 4px; font-weight: 500;">
                                    <i class="fas fa-calendar"></i> Published: ${new Date(subject.published_date).toLocaleDateString()}
                                </div>
                            ` : ''}
                        </td>
                        <td style="display: flex; gap: 8px; align-items: center;">
                            <button class="enter-marks-btn ${isPublished ? 'locked-enter-btn' : ''}" 
                                onclick="openMarksModal(${subject.class_id}, ${subject.stream_id}, ${subject.subject_id}, '${escapeHtml(subject.class_name)}', '${escapeHtml(subject.stream_name)}', '${escapeHtml(subject.subject_name)}', '${encodeURIComponent(JSON.stringify(subject))}')"
                                ${isPublished ? 'disabled title="' + disabledText + '"' : ''}>
                                <i class="fas ${isPublished ? 'fa-lock' : 'fa-edit'}" style="margin-right: 6px;"></i>
                                ${isPublished ? 'LOCKED' : _.enter_marks_button}
                            </button>
                            ${isPublished ? `
                                <div class="locked-warning-text">
                                    <i class="fas fa-info-circle"></i> Contact Admin
                                </div>
                            ` : ''}
                        </td>
                    </tr>
                `;
            });

            tableHTML += `
                    </tbody>
                </table>
            `;

            subjectsContent.innerHTML = lockingInfo + tableHTML;
        }

        function openMarksModal(classId, streamId, subjectId, className, streamName, subjectName, encodedSubjectData = null) {
            console.log('Opening modal with params:', {classId, streamId, subjectId, className, streamName, subjectName, encodedSubjectData});
            
            // Check if marks entry is blocked due to publishing workflow
            if (encodedSubjectData) {
                try {
                    const subjectData = JSON.parse(decodeURIComponent(encodedSubjectData));
                    if (subjectData.exam_status === 'Pending Review' || subjectData.exam_status === 'Published') {
                        const status = subjectData.exam_status;
                        if (status === 'Published') {
                            showNotification(`🚫 MARKS ENTRY BLOCKED - This class is PUBLISHED and LOCKED for editing. Contact your administrator to unpublish the class if changes are needed.`, 'error');
                        } else if (status === 'Pending Review') {
                            showNotification(`⏳ MARKS ENTRY BLOCKED - This class is under review by administration. No changes can be made during the review process.`, 'error');
                        }
                        return;
                    }
                } catch (e) {
                    console.warn('Error parsing subject data:', e);
                }
            }
            
            // Clear cached student data when opening modal for different class
            clearCachedData();
            
            // Parse encoded subject data
            let subjectData = null;
            if (encodedSubjectData && encodedSubjectData !== 'null') {
                try {
                    subjectData = JSON.parse(decodeURIComponent(encodedSubjectData));
                } catch (e) {
                    console.error('Error parsing subject data:', e);
                    subjectData = null;
                }
            }
            
            currentSubjectData = {
                class_id: classId,
                stream_id: streamId,
                subject_id: subjectId,
                class_name: className,
                stream_name: streamName,
                subject_name: subjectName,
                papers: subjectData?.papers || [],
                has_papers: subjectData?.has_papers || false,
                selected_paper_id: null // Track selected paper
            };

            const modal = document.getElementById('marksModal');
            const modalTitle = document.getElementById('modalTitle');
            const studentsContainer = document.getElementById('studentsTableContainer');
            const paperSelectionSection = document.getElementById('paperSelectionSection');
            const paperSelect = document.getElementById('paperSelect');

            // Show paper selection if subject has papers
            if (currentSubjectData.has_papers && currentSubjectData.papers.length > 0) {
                console.log('Subject has papers, showing paper selection:', currentSubjectData.papers);
                
                // Populate paper selection dropdown
                paperSelect.innerHTML = '<option value="">Choose paper to enter marks for...</option>';
                currentSubjectData.papers.forEach(paper => {
                    const option = document.createElement('option');
                    option.value = paper.paper_id;
                    option.textContent = paper.paper_name;
                    paperSelect.appendChild(option);
                });
                
                // Show paper selection section
                paperSelectionSection.style.display = 'block';
                studentsContainer.innerHTML = `
                    <div class="empty-message">
                        <i class="fas fa-info-circle" style="margin-right: 8px; color: #3b82f6;"></i>
                        Please select a paper above to enter marks for students.
                    </div>
                `;
            } else {
                // No papers - load students directly (traditional single mark entry)
                console.log('Subject has no papers, loading students directly');
                paperSelectionSection.style.display = 'none';
                checkSubjectStatusAndLoadStudents();
            }

            if (!modal) {
                console.error('Modal element not found');
                return;
            }

            modalTitle.textContent = `${langData[currentLang]['marks_entry_title']} ${className} - ${streamName} - ${subjectName}`;
            
            // With class-level locking, we already check class status in the UI
            // Skip the whole-exam check and go directly to subject check
            
            // Admins can always edit, teachers are already blocked by UI if class is published
            checkSubjectStatusAndLoadStudents();
            
            function checkSubjectStatusAndLoadStudents() {
                // Check if individual subject is published (teachers only, admins can edit published subjects)
                if (currentUserRole == 2) { // Teacher role
                    fetch('ajax_get_exam_subjects.php', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/x-www-form-urlencoded',
                        },
                        body: `exam_id=${encodeURIComponent(currentExamId)}&school_id=${encodeURIComponent(currentSchoolId)}&teacher_id=${encodeURIComponent(currentUserId)}&action=get_exam_subjects`
                    })
                    .then(response => response.json())
                    .then(data => {
                        if (data.success) {
                            const subject = data.subjects.find(s => s.subject_id == currentSubjectData.subject_id);
                            if (subject && subject.status === 'Published') {
                                // Instead of alert(), show the HTML modal
                                showAlreadyPublishedModal(currentSubjectData.subject_name, currentSubjectData.class_name + ' - ' + currentSubjectData.stream_name);
                                return;
                            }
                            loadStudentsForMarks();
                        } else {
                            showNotification('Error checking subject status.', 'error');
                        }
                    })
                    .catch(error => {
                        console.error('Error checking status:', error);
                        loadStudentsForMarks(); // Continue anyway
                    });
                } else {
                    loadStudentsForMarks(); // Admins can always edit
                }
            }
            
            function loadStudentsForMarks() {
                // Show loading
                studentsContainer.innerHTML = `
                    <div class="loading-message">
                        <span class="loading-spinner"></span>
                        ${_.loading}
                    </div>
                `;

                modal.style.display = 'block';
                console.log('Modal display set to block');

                // Debug logging for student filtering
                console.log('Loading students for:', {
                    exam_id: currentExamId,
                    class_id: currentSubjectData.class_id,
                    stream_id: currentSubjectData.stream_id,
                    subject_id: currentSubjectData.subject_id,
                    school_id: currentSchoolId,
                    class_name: currentSubjectData.class_name,
                    stream_name: currentSubjectData.stream_name
                });

                // Fetch students for this class/stream
                const requestBody = `exam_id=${encodeURIComponent(currentExamId)}&class_id=${encodeURIComponent(currentSubjectData.class_id)}&stream_id=${encodeURIComponent(currentSubjectData.stream_id)}&subject_id=${encodeURIComponent(currentSubjectData.subject_id)}&school_id=${encodeURIComponent(currentSchoolId)}&action=get_students_for_marks`;
                console.log('Sending AJAX request:', requestBody);
                
                fetch('ajax_get_students_for_marks.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: requestBody
            })
            .then(response => {
                console.log('Response status:', response.status);
                return response.json();
            })
            .then(data => {
                console.log('Response data:', data);
                console.log('Number of students returned:', data.students ? data.students.length : 0);
                if (data.students && data.students.length > 0) {
                    console.log('First few students:', data.students.slice(0, 3));
                }
                if (data.success) {
                    // Store papers data globally for saveMarks function
                    window.currentPapersData = data.papers || [];
                    window.currentHasPapers = data.has_papers || false;
                    
                    displayStudentsTable(data.students, data.papers || [], data.has_papers || false);
                } else {
                    studentsContainer.innerHTML = `
                        <div class="empty-message">
                            ${data.message || _.error_occurred}
                        </div>
                    `;
                }
            })
            .catch(error => {
                console.error('AJAX Error:', error);
                studentsContainer.innerHTML = `
                    <div class="empty-message">
                        ${_.error_occurred}
                    </div>
                `;
            });
            }
        }

        function displayStudentsTable(students, papers = [], hasPapers = false) {
            console.log('Displaying students table with data:', students);
            console.log('Papers data:', papers);
            console.log('Has papers:', hasPapers);
            
            const studentsContainer = document.getElementById('studentsTableContainer');
            
            if (!students || students.length === 0) {
                console.log('No students data found');
                studentsContainer.innerHTML = `
                    <div class="empty-message">
                        No students found for this class/stream.
                    </div>
                `;
                return;
            }

            // Determine current paper information
            const hasPapersBool = hasPapers || (papers && papers.length > 0);
            const currentPaper = hasPapersBool && currentSubjectData.selected_paper_id ? 
                               papers.find(p => p.paper_id == currentSubjectData.selected_paper_id) : null;
            const showPaperName = hasPapersBool && currentPaper ? ` - ${currentPaper.paper_name}` : '';
            
            let tableHTML = `
                <table class="students-table">
                    <thead>
                        <tr>
                            <th>${_.student_name}</th>
                            <th>${hasPapersBool ? (_.current_mark || 'Current Mark') + showPaperName : _.current_mark}</th>
                            <th>${_.new_mark}</th>
                        </tr>
                    </thead>
                    <tbody>
            `;

            students.forEach((student, index) => {
                // Extract just the name part (remove any ID in brackets) and add numbering
                let displayName = student.username;
                // Remove any content in brackets if present (e.g., "John Doe (123)" -> "John Doe")
                displayName = displayName.replace(/\s*\([^)]*\)\s*/g, '');
                // Add numbering prefix
                displayName = `${index + 1}. ${displayName}`;
                
                let currentMark = '';
                if (hasPapersBool && currentPaper) {
                    // Get current mark for the selected paper
                    currentMark = student.paper_marks && student.paper_marks[currentPaper.paper_id] ? 
                                 student.paper_marks[currentPaper.paper_id] : '';
                } else {
                    // Get regular mark (no paper)
                    currentMark = student.current_mark !== null ? student.current_mark : '';
                }
                
                tableHTML += `
                    <tr>
                        <td>${escapeHtml(displayName)}</td>
                        <td>${currentMark || '-'}</td>
                        <td>
                            <input type="number" 
                                   min="0" 
                                   max="100" 
                                   step="0.01" 
                                   value="${currentMark}" 
                                   data-student-id="${student.user_id}"
                                   ${hasPapersBool && currentPaper ? `data-paper-id="${currentPaper.paper_id}"` : ''}
                                   class="mark-input">
                        </td>
                    </tr>
                `;
            });

            tableHTML += `
                    </tbody>
                </table>
            `;

            // Add paper info header if showing specific paper
            if (hasPapersBool && currentPaper) {
                tableHTML = `
                    <div style="margin-bottom: 15px; padding: 10px; background-color: #e3f2fd; border-radius: 6px; border-left: 4px solid #2196f3;">
                        <strong><i class="fas fa-file-alt" style="margin-right: 8px;"></i>Entering marks for:</strong> 
                        <span style="color: #1976d2; font-weight: 600;">${currentPaper.paper_name}</span>
                        <small style="display: block; color: #666; margin-top: 5px;">
                            Enter marks for ${students.length} students in ${currentSubjectData.subject_name}
                        </small>
                    </div>
                ` + tableHTML;
            }

            studentsContainer.innerHTML = tableHTML;
            
            // Re-enable paper selection dropdown after loading
            const paperSelect = document.getElementById('paperSelect');
            if (paperSelect) {
                paperSelect.disabled = false;
                paperSelect.style.opacity = '1';
            }
        }

        function closeMarksModal() {
            document.getElementById('marksModal').style.display = 'none';
            // Clear currentSubjectData only if not in publish flow
            if (document.getElementById('publishAfterSaveModal').style.display === 'none') {
                currentSubjectData = null;
            }
        }

        // Function to close marks modal and clear data when needed
        function closeMarksModalAndClear() {
            document.getElementById('marksModal').style.display = 'none';
            currentSubjectData = null;
        }

        // Function to load students for selected paper
        function loadStudentsForSelectedPaper() {
            const paperSelect = document.getElementById('paperSelect');
            const selectedPaperId = paperSelect.value;
            
            if (!selectedPaperId) {
                console.log('No paper selected');
                return;
            }
            
            // Store selected paper ID
            currentSubjectData.selected_paper_id = parseInt(selectedPaperId);
            console.log('Loading students for paper ID:', currentSubjectData.selected_paper_id);
            
            // Clear paper selection section to prevent re-selection while loading
            paperSelect.disabled = true;
            paperSelect.style.opacity = '0.6';
            
            // Load students for this specific paper
            loadStudentsForMarks();
        }

        // UPDATED saveMarks function with multi-paper support and validation
        function saveMarks() {
            if (!currentSubjectData || !currentExamId) {
                showNotification(_.error_occurred, 'error');
                return;
            }

            const markInputs = document.querySelectorAll('.mark-input');
            const marks = [];
            const hasPapersData = currentSubjectData.has_papers && currentSubjectData.selected_paper_id;

            // VALIDATION: For multi-paper subjects, paper selection is REQUIRED
            if (currentSubjectData.has_papers && currentSubjectData.papers && currentSubjectData.papers.length > 0) {
                if (!currentSubjectData.selected_paper_id) {
                    showWarningModal(
                        _.paper_selection_required
                    );
                    return;
                }
            }

            // VALIDATION: Check if all papers are completed for multi-paper subjects
            if (currentSubjectData.has_papers && currentSubjectData.papers && currentSubjectData.papers.length > 0) {
                const papers = currentSubjectData.papers;
                console.log('Validating multi-paper subject:', papers.length, 'papers found');
                
                // Get all students currently displayed
                const students = Array.from(document.querySelectorAll('.mark-input')).map(input => ({
                    studentId: input.getAttribute('data-student-id'),
                    studentName: input.getAttribute('data-student-name') || 'Student'
                })).reduce((acc, curr) => {
                    if (!acc.find(item => item.studentId === curr.studentId)) {
                        acc.push(curr);
                    }
                    return acc;
                }, []);

                const missingPapers = [];
                
                // Check each student for missing paper marks
                for (let student of students) {
                    for (let paper of papers) {
                        // Look for mark input for this student and paper
                        const markInput = document.querySelector(
                            `.mark-input[data-student-id="${student.studentId}"][data-paper-id="${paper.paper_id}"]`
                        );
                        
                        // If no specific paper input found, check if we're in single paper mode
                        if (!markInput) {
                            // In single paper mode, check if selected paper matches
                            if (hasPapersData && currentSubjectData.selected_paper_id == paper.paper_id) {
                                // Check if mark is entered for this paper
                                const studentMarkInput = document.querySelector(
                                    `.mark-input[data-student-id="${student.studentId}"]`
                                );
                                if (!studentMarkInput || studentMarkInput.value.trim() === '') {
                                    missingPapers.push(`Student: ${student.studentName}, Paper: ${paper.paper_name}`);
                                }
                            } else {
                                // Check if paper is required but not selected
                                if (!hasPapersData) {
                                    missingPapers.push(`Student: ${student.studentName}, Paper: ${paper.paper_name}`);
                                }
                            }
                        }
                    }
                }

                // Show validation error if missing papers found
                if (missingPapers.length > 0) {
                    let errorMessage = `${_.multi_paper_validation_error}\n\n`;
                    errorMessage += missingPapers.slice(0, 10).join('\n'); // Show first 10 missing entries
                    if (missingPapers.length > 10) {
                        errorMessage += `\n${_.multi_paper_missing_summary.replace('%d', missingPapers.length - 10)}`;
                    }
                    errorMessage += `\n\n${_.complete_all_papers_before_save}`;
                    
                    alert(errorMessage);
                    return;
                }
                
                console.log('✅ All required paper marks are complete');
            }

            // Process marks as before
            for (let input of markInputs) {
                const studentId = input.getAttribute('data-student-id');
                const paperId = input.getAttribute('data-paper-id') || (hasPapersData ? currentSubjectData.selected_paper_id : null);
                const mark = parseFloat(input.value);

                if (input.value !== '' && (isNaN(mark) || mark < 0 || mark > 100)) {
                    showWarningModal(_.invalid_mark);
                    input.focus();
                    return;
                }

                if (input.value !== '') {
                    marks.push({
                        student_id: studentId,
                        paper_id: paperId,
                        mark: mark
                    });
                }
            }

            if (marks.length === 0) {
                showWarningModal('Please enter at least one mark before saving.');
                return;
            }

            // Show loading overlay
            showSavingOverlay(true);

            // Save marks via AJAX
            const formData = new FormData();
            formData.append('exam_id', currentExamId);
            formData.append('class_id', currentSubjectData.class_id);
            formData.append('subject_id', currentSubjectData.subject_id);
            formData.append('stream_id', currentSubjectData.stream_id);
            formData.append('school_id', currentSchoolId);
            formData.append('has_papers', hasPapersData ? '1' : '0');
            formData.append('marks', JSON.stringify(marks));

            fetch('ajax_save_marks.php', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                // Hide loading overlay
                showSavingOverlay(false);
                
                if (data.success) {
                    showSuccessModal(data.message || 'Marks saved successfully!');
                    
                    // Show publish button after successful save (don't close modal yet)
                    showPublishButtonAfterSave();
                    
                    // Refresh the subject list to show updated data
                    if (currentExamId) {
                        loadSubjects();
                    }
                } else {
                    showNotification(data.message || _.error_occurred, 'error');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                showSavingOverlay(false);
                showNotification(_.error_occurred, 'error');
            });
        }

        // REPLACED: showPublishButtonAfterSave() - Now uses HTML form modal
        function showPublishButtonAfterSave() {
            if (!currentSubjectData || !currentExamId) return;
            
            // Instead of confirm(), show the beautiful HTML modal
            showPublishAfterSaveModal();
        }
        
        // NEW: confirmPublishCurrentSubject() - Called by "Yes, Publish Now" button
        function confirmPublishCurrentSubject() {
            console.log('confirmPublishCurrentSubject called, currentSubjectData:', currentSubjectData);
            
            if (!currentSubjectData) {
                console.error('currentSubjectData is not set in confirmPublishCurrentSubject');
                return;
            }
            
            // Set the publish subject ID before hiding modals (since hidePublishAfterSaveModal clears currentSubjectData)
            currentPublishSubjectId = currentSubjectData.subject_id;
            console.log('currentPublishSubjectId set to:', currentPublishSubjectId);
            
            // Close the after-save modal and directly publish
            hidePublishAfterSaveModal();
            
            // Directly execute the publish
            executePublishSubject();
        }

        // Function to publish the current subject (DEPRECATED - use confirmPublishCurrentSubject instead)
        function publishCurrentSubject() {
            if (!currentSubjectData) return;
            
            publishSubject(currentSubjectData.subject_id);
        }

        function escapeHtml(text) {
            const map = {
                '&': '&amp;',
                '<': '&lt;',
                '>': '&gt;',
                '"': '&quot;',
                "'": '&#039;'
            };
            return text.replace(/[&<>"']/g, function(m) { return map[m]; });
        }

        // Close modal when clicking outside
        window.onclick = function(event) {
            const modal = document.getElementById('marksModal');
            const activityModal = document.getElementById('activityMarksModal');
            const createModal = document.getElementById('createActivityModal');
            
            if (event.target == modal) {
                closeMarksModal();
            }
            if (event.target == activityModal) {
                closeActivityMarksModal();
            }
            if (event.target == createModal) {
                closeCreateActivityModal();
            }
        }

        // =========================== //
        // INTEGRATION ACTIVITY FUNCTIONS //
        // =========================== //

        let currentActivityData = null;

        // Switch between Exam mode and Integration Activity mode
        function switchMode(mode) {
            const examSection = document.getElementById('examModeSection');
            const integrationSection = document.getElementById('integrationModeSection');
            
            if (mode === 'exam') {
                examSection.style.display = 'block';
                integrationSection.style.display = 'none';
            } else {
                examSection.style.display = 'none';
                integrationSection.style.display = 'block';
                loadIntegrationActivities();
            }
        }

        // Load integration activities
        function loadIntegrationActivities() {
            const activitiesContent = document.getElementById('activitiesContent');
            
            activitiesContent.innerHTML = `
                <div class="loading-message">
                    <div class="loading-spinner"></div>
                    Loading activities...
                </div>
            `;

            fetch('ajax_get_integration_activities.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: 'school_id=' + encodeURIComponent(currentSchoolId) + '&teacher_id=' + encodeURIComponent(currentUserId)
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    displayActivities(data.activities);
                } else {
                    activitiesContent.innerHTML = `
                        <div class="empty-message">
                            <i class="fas fa-info-circle" style="margin-right: 8px;"></i>
                            ${data.message || 'No activities found.'}
                        </div>
                    `;
                }
            })
            .catch(error => {
                console.error('Error:', error);
                activitiesContent.innerHTML = `
                    <div class="empty-message">
                        <i class="fas fa-times-circle" style="margin-right: 8px; color: #ef4444;"></i>
                        Error loading activities.
                    </div>
                `;
            });
        }

        // Display activities as cards
        function displayActivities(activities) {
            const activitiesContent = document.getElementById('activitiesContent');
            
            if (!activities || activities.length === 0) {
                activitiesContent.innerHTML = `
                    <div class="empty-message">
                        <i class="fas fa-folder-open" style="margin-right: 8px; font-size: 2rem; color: #9ca3af;"></i>
                        <p style="margin: 12px 0 0 0; font-size: 1rem;">No integration activities yet. Create your first one!</p>
                    </div>
                `;
                return;
            }

            let html = '<div style="display: grid; gap: 16px;">';
            
            activities.forEach(activity => {
                const dueDate = new Date(activity.due_date);
                const formattedDate = dueDate.toLocaleDateString('en-US', { year: 'numeric', month: 'short', day: 'numeric' });
                
                html += `
                    <div class="activity-card">
                        <div class="activity-header">
                            <div style="flex: 1;">
                                <h3 class="activity-title">${escapeHtml(activity.title)}</h3>
                                <span class="activity-status-badge activity-status-${activity.status.toLowerCase()}">
                                    ${activity.status}
                                </span>
                            </div>
                        </div>
                        
                        <div class="activity-meta">
                            <span class="activity-meta-item">
                                <i class="fas fa-chalkboard"></i>
                                ${escapeHtml(activity.class_name)}
                            </span>
                            <span class="activity-meta-item">
                                <i class="fas fa-stream"></i>
                                ${escapeHtml(activity.stream_name)}
                            </span>
                            <span class="activity-meta-item">
                                <i class="fas fa-book"></i>
                                ${escapeHtml(activity.subject_name)}
                            </span>
                            <span class="activity-meta-item">
                                <i class="fas fa-lightbulb"></i>
                                ${escapeHtml(activity.topic_name)}
                            </span>
                            <span class="activity-meta-item">
                                <i class="fas fa-calendar"></i>
                                Due: ${formattedDate}
                            </span>
                        </div>
                        
                        ${activity.description ? `
                            <div class="activity-description">
                                ${escapeHtml(activity.description)}
                            </div>
                        ` : ''}
                        
                        <div class="activity-actions">
                            <button class="activity-btn activity-btn-primary" 
                                onclick="openActivityMarksModal(${activity.activity_id}, '${escapeHtml(activity.title)}', ${activity.stream_id}, ${activity.subject_id})"
                                ${activity.status === 'Published' ? 'disabled title="Cannot edit - Activity is published"' : ''}>
                                <i class="fas fa-pen"></i>
                                Enter Marks
                            </button>
                            ${currentUserRole == 1 ? `
                                ${activity.status === 'Published' ? `
                                    <button class="activity-btn activity-btn-warning" onclick="unpublishActivity(${activity.activity_id})">
                                        <i class="fas fa-lock-open"></i>
                                        Unpublish
                                    </button>
                                ` : `
                                    <button class="activity-btn activity-btn-success" onclick="publishActivity(${activity.activity_id})" 
                                        ${activity.status === 'Draft' ? 'disabled title="Save marks first to publish"' : ''}>
                                        <i class="fas fa-check-circle"></i>
                                        Publish
                                    </button>
                                `}
                            ` : ''}
                            <button class="activity-btn activity-btn-danger" onclick="deleteActivity(${activity.activity_id})"
                                ${activity.status === 'Published' ? 'disabled title="Cannot delete - Activity is published"' : ''}>
                                <i class="fas fa-trash"></i>
                                Delete
                            </button>
                        </div>
                    </div>
                `;
            });
            
            html += '</div>';
            activitiesContent.innerHTML = html;
        }

        // Open create activity modal
        function openCreateActivityModal() {
            const modal = document.getElementById('createActivityModal');
            modal.style.display = 'block';
            
            // Load streams and subjects for the teacher
            loadStreamsForActivity();
            loadSubjectsForActivity();
            loadTopicsForActivity();
        }

        // Close create activity modal
        function closeCreateActivityModal() {
            const modal = document.getElementById('createActivityModal');
            modal.style.display = 'none';
            document.getElementById('createActivityForm').reset();
        }

        // Load streams that the teacher is assigned to
        function loadStreamsForActivity() {
            const streamSelect = document.getElementById('activityStreamSelect');
            
            fetch('ajax_get_teacher_streams.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: 'school_id=' + encodeURIComponent(currentSchoolId) + '&teacher_id=' + encodeURIComponent(currentUserId)
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    streamSelect.innerHTML = '<option value="">Select Class & Stream...</option>';
                    data.streams.forEach(stream => {
                        streamSelect.innerHTML += `<option value="${stream.stream_id}" data-class-id="${stream.class_id}">${escapeHtml(stream.class_name)} - ${escapeHtml(stream.stream_name)}</option>`;
                    });
                }
            })
            .catch(error => console.error('Error:', error));
        }

        // Load subjects that the teacher teaches
        function loadSubjectsForActivity() {
            const subjectSelect = document.getElementById('activitySubjectSelect');
            
            fetch('ajax_get_teacher_subjects.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: 'school_id=' + encodeURIComponent(currentSchoolId) + '&teacher_id=' + encodeURIComponent(currentUserId)
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    subjectSelect.innerHTML = '<option value="">Select Subject...</option>';
                    data.subjects.forEach(subject => {
                        subjectSelect.innerHTML += `<option value="${subject.subject_id}">${escapeHtml(subject.subject_name)}</option>`;
                    });
                }
            })
            .catch(error => console.error('Error:', error));
        }

        // Load topics
        function loadTopicsForActivity() {
            const topicSelect = document.getElementById('activityTopicSelect');
            
            fetch('ajax_get_topics.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: 'school_id=' + encodeURIComponent(currentSchoolId)
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    topicSelect.innerHTML = '<option value="">Select Topic...</option>';
                    data.topics.forEach(topic => {
                        topicSelect.innerHTML += `<option value="${topic.topic_id}">${escapeHtml(topic.topic_name)}</option>`;
                    });
                }
            })
            .catch(error => console.error('Error:', error));
        }

        // Load competencies based on selected topic
        function loadCompetencies() {
            const topicId = document.getElementById('activityTopicSelect').value;
            const competencySelect = document.getElementById('activityCompetencySelect');
            
            if (!topicId) {
                competencySelect.innerHTML = '<option value="">Select Competency...</option>';
                return;
            }
            
            fetch('ajax_get_competencies.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: 'topic_id=' + encodeURIComponent(topicId) + '&school_id=' + encodeURIComponent(currentSchoolId)
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    competencySelect.innerHTML = '<option value="">Select Competency...</option>';
                    data.competencies.forEach(comp => {
                        competencySelect.innerHTML += `<option value="${comp.competency_id}">${escapeHtml(comp.competency_name)}</option>`;
                    });
                } else {
                    competencySelect.innerHTML = '<option value="">No competencies found</option>';
                }
            })
            .catch(error => console.error('Error:', error));
        }

        // Create integration activity
        function createActivity() {
            const form = document.getElementById('createActivityForm');
            
            if (!form.checkValidity()) {
                form.reportValidity();
                return;
            }
            
            const streamSelect = document.getElementById('activityStreamSelect');
            const selectedOption = streamSelect.options[streamSelect.selectedIndex];
            const classId = selectedOption.getAttribute('data-class-id');
            const streamId = streamSelect.value;
            const subjectId = document.getElementById('activitySubjectSelect').value;
            const topicId = document.getElementById('activityTopicSelect').value;
            const competencyId = document.getElementById('activityCompetencySelect').value;
            const title = document.getElementById('activityTitle').value;
            const description = document.getElementById('activityDescription').value;
            const dueDate = document.getElementById('activityDueDate').value;
            
            showSavingOverlay(true);
            
            const formData = new FormData();
            formData.append('class_id', classId);
            formData.append('stream_id', streamId);
            formData.append('subject_id', subjectId);
            formData.append('topic_id', topicId);
            formData.append('competency_id', competencyId);
            formData.append('title', title);
            formData.append('description', description);
            formData.append('due_date', dueDate);
            formData.append('school_id', currentSchoolId);
            formData.append('teacher_id', currentUserId);
            
            fetch('ajax_create_integration_activity.php', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                showSavingOverlay(false);
                
                if (data.success) {
                    showSuccessModal(data.message || 'Activity created successfully!');
                    closeCreateActivityModal();
                    loadIntegrationActivities();
                } else {
                    showNotification(data.message || 'Error creating activity.', 'error');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                showSavingOverlay(false);
                showNotification('Error creating activity.', 'error');
            });
        }

        // Delete integration activity
        function deleteActivity(activityId) {
            if (!confirm('Are you sure you want to delete this activity? This action cannot be undone.')) {
                return;
            }
            
            showSavingOverlay(true);
            
            const formData = new FormData();
            formData.append('activity_id', activityId);
            formData.append('school_id', currentSchoolId);
            
            fetch('ajax_delete_integration_activity.php', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                showSavingOverlay(false);
                
                if (data.success) {
                    showSuccessModal(data.message || 'Activity deleted successfully!');
                    loadIntegrationActivities();
                } else {
                    showNotification(data.message || 'Error deleting activity.', 'error');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                showSavingOverlay(false);
                showNotification('Error deleting activity.', 'error');
            });
        }

        // Publish activity (Admin only)
        function publishActivity(activityId) {
            if (!confirm('Are you sure you want to publish this activity? Once published, marks entry will be locked until unpublished.')) {
                return;
            }
            
            showSavingOverlay(true);
            
            const formData = new FormData();
            formData.append('activity_id', activityId);
            formData.append('school_id', currentSchoolId);
            
            fetch('ajax_publish_activity.php', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                showSavingOverlay(false);
                
                if (data.success) {
                    showSuccessModal(data.message || 'Activity published successfully!');
                    loadIntegrationActivities();
                } else {
                    showNotification(data.message || 'Error publishing activity.', 'error');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                showSavingOverlay(false);
                showNotification('Error publishing activity.', 'error');
            });
        }

        // Unpublish activity (Admin only)
        function unpublishActivity(activityId) {
            if (!confirm('Are you sure you want to unpublish this activity? This will allow marks to be edited again.')) {
                return;
            }
            
            showSavingOverlay(true);
            
            const formData = new FormData();
            formData.append('activity_id', activityId);
            formData.append('school_id', currentSchoolId);
            
            fetch('ajax_unpublish_activity.php', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                showSavingOverlay(false);
                
                if (data.success) {
                    showSuccessModal(data.message || 'Activity unpublished successfully!');
                    loadIntegrationActivities();
                } else {
                    showNotification(data.message || 'Error unpublishing activity.', 'error');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                showSavingOverlay(false);
                showNotification('Error unpublishing activity.', 'error');
            });
        }

        // REPLACED: publishSubject() - Now directly publishes without confirmation modal
        function publishSubject(subjectId) {
            // Store the subject ID for later use
            currentPublishSubjectId = subjectId;
            console.log('currentPublishSubjectId set to:', currentPublishSubjectId);
            
            // Direct publish without confirmation modal
            executePublishSubject();
        }

        // REPLACED: unpublishSubject() - Now shows HTML modal for admin unpublish
        function unpublishSubject(subjectId) {
            // Find the subject data for the modal
            fetch('ajax_get_exam_subjects.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: 'exam_id=' + encodeURIComponent(currentExamId) + 
                      '&school_id=' + encodeURIComponent(currentSchoolId) + 
                      '&teacher_id=' + encodeURIComponent(currentUserId) +
                      '&action=get_exam_subjects'
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    const subject = data.subjects.find(s => s.subject_id == subjectId);
                    if (subject) {
                        // Store the subject ID for later use
                        currentUnpublishSubjectId = subjectId;
                        showUnpublishModal(subject.subject_name, subject.class_name + ' - ' + subject.stream_name);
                    }
                } else {
                    showNotification('Error loading subject data.', 'error');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                showNotification('Error loading subject data.', 'error');
            });
        }

        // Open activity marks modal
        function openActivityMarksModal(activityId, activityTitle, streamId, subjectId) {
            console.log('Opening activity marks modal:', {activityId, activityTitle, streamId, subjectId});
            
            currentActivityData = {
                activity_id: activityId,
                title: activityTitle,
                stream_id: streamId,
                subject_id: subjectId
            };
            
            const modal = document.getElementById('activityMarksModal');
            const modalTitle = document.getElementById('activityModalTitle');
            const studentsContainer = document.getElementById('activityStudentsTableContainer');
            
            modalTitle.textContent = `Enter Marks: ${activityTitle}`;
            
            studentsContainer.innerHTML = `
                <div class="loading-message">
                    <span class="loading-spinner"></span>
                    Loading students...
                </div>
            `;
            
            modal.style.display = 'block';
            
            // Debug logging
            console.log('Loading students for activity:', {
                activity_id: activityId,
                stream_id: streamId,
                subject_id: subjectId,
                school_id: currentSchoolId
            });
            
            // Fetch students for this stream
            fetch('ajax_get_students_for_activity.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: `activity_id=${encodeURIComponent(activityId)}&stream_id=${encodeURIComponent(streamId)}&subject_id=${encodeURIComponent(subjectId)}&school_id=${encodeURIComponent(currentSchoolId)}&action=get_students_for_activity`
            })
            .then(response => {
                console.log('Activity response status:', response.status);
                return response.json();
            })
            .then(data => {
                console.log('Activity response data:', data);
                console.log('Number of activity students returned:', data.students ? data.students.length : 0);
                if (data.students && data.students.length > 0) {
                    console.log('First few activity students:', data.students.slice(0, 3));
                }
                if (data.success) {
                    displayActivityStudentsTable(data.students);
                } else {
                    studentsContainer.innerHTML = `
                        <div class="empty-message">
                            ${data.message || 'No students found.'}
                        </div>
                    `;
                }
            })
            .catch(error => {
                console.error('Error:', error);
                studentsContainer.innerHTML = `
                    <div class="empty-message">
                        Error loading students.
                    </div>
                `;
            });
        }

        // Display students table for activity marks
        function displayActivityStudentsTable(students) {
            const studentsContainer = document.getElementById('activityStudentsTableContainer');
            
            if (!students || students.length === 0) {
                studentsContainer.innerHTML = `
                    <div class="empty-message">
                        No students found for this stream.
                    </div>
                `;
                return;
            }
            
            let tableHTML = `
                <table class="students-table">
                    <thead>
                        <tr>
                            <th>Student Name</th>
                            <th>Current Mark</th>
                            <th>New Mark</th>
                        </tr>
                    </thead>
                    <tbody>
            `;
            
            students.forEach((student, index) => {
                const currentMark = student.current_mark !== null ? student.current_mark : '';
                // Extract just the name part (remove any ID in brackets if present) and add numbering
                let displayName = student.username;
                // Remove any content in brackets if present (e.g., "John Doe (123)" -> "John Doe")
                displayName = displayName.replace(/\s*\([^)]*\)\s*/g, '');
                // Add numbering prefix
                displayName = `${index + 1}. ${displayName}`;
                
                tableHTML += `
                    <tr>
                        <td>${escapeHtml(displayName)}</td>
                        <td>${currentMark}</td>
                        <td>
                            <input type="number" 
                                   min="0" 
                                   max="100" 
                                   step="0.01" 
                                   value="${currentMark}" 
                                   data-student-id="${student.user_id}"
                                   class="activity-mark-input">
                        </td>
                    </tr>
                `;
            });
            
            tableHTML += `
                    </tbody>
                </table>
            `;
            
            studentsContainer.innerHTML = tableHTML;
        }

        // Close activity marks modal
        function closeActivityMarksModal() {
            document.getElementById('activityMarksModal').style.display = 'none';
            currentActivityData = null;
        }

        /* ==========================================================================
           Modal Management Functions for Professional Publish System
           ========================================================================== */

        // Global variables for modal management
        let currentPublishSubjectId = null;
        let currentUnpublishSubjectId = null;
        let currentExamPublishedStatus = null;

        // Show/Hide Publish After Save Modal
        function showPublishAfterSaveModal() {
            if (!currentSubjectData) {
                console.error('currentSubjectData is not set in showPublishAfterSaveModal');
                return;
            }
            
            // Populate modal content
            document.getElementById('publishSubjectName').textContent = currentSubjectData.subject_name;
            document.getElementById('publishClassName').textContent = currentSubjectData.class_name + ' - ' + currentSubjectData.stream_name;
            
            document.getElementById('publishAfterSaveModal').style.display = 'flex';
            document.body.style.overflow = 'hidden';
        }

        function hidePublishAfterSaveModal() {
            console.log('hidePublishAfterSaveModal called, currentSubjectData:', currentSubjectData);
            document.getElementById('publishAfterSaveModal').style.display = 'none';
            document.body.style.overflow = 'auto';
            
            // Close marks modal and refresh subjects
            closeMarksModal();
            if (currentExamId) {
                loadSubjects();
            }
        }

        // Show/Hide Unpublish Modal
        function showUnpublishModal(subjectName, className) {
            document.getElementById('unpublishSubjectName').textContent = subjectName;
            document.getElementById('unpublishClassName').textContent = className;
            
            document.getElementById('unpublishModal').style.display = 'flex';
            document.body.style.overflow = 'hidden';
        }

        function hideUnpublishModal() {
            document.getElementById('unpublishModal').style.display = 'none';
            document.body.style.overflow = 'auto';
        }

        // Show/Hide Already Published Modal
        function showAlreadyPublishedModal(subjectName, className) {
            document.getElementById('publishedSubjectName').textContent = subjectName;
            document.getElementById('publishedClassName').textContent = className;
            
            document.getElementById('alreadyPublishedModal').style.display = 'flex';
            document.body.style.overflow = 'hidden';
        }

        function hideAlreadyPublishedModal() {
            document.getElementById('alreadyPublishedModal').style.display = 'none';
            document.body.style.overflow = 'auto';
            closeMarksModalAndClear();
        }
        
        // NEW: Show Exam Published Modal
        function showExamPublishedModal(examName) {
            document.getElementById('publishedExamName').textContent = examName;
            
            document.getElementById('examPublishedModal').style.display = 'flex';
            document.body.style.overflow = 'hidden';
        }

        function hideExamPublishedModal() {
            document.getElementById('examPublishedModal').style.display = 'none';
            document.body.style.overflow = 'auto';
            closeMarksModalAndClear();
        }

        // Execute publish action
        function executePublishSubject() {
            console.log('executePublishSubject called, currentPublishSubjectId:', currentPublishSubjectId);
            console.log('currentExamId:', currentExamId, 'currentSchoolId:', currentSchoolId);
            
            if (!currentPublishSubjectId) {
                console.error('currentPublishSubjectId is not set');
                showNotification('Error: Subject ID not found.', 'error');
                return;
            }
            
            showSavingOverlay(true);
            
            const formData = new FormData();
            formData.append('exam_id', currentExamId);
            formData.append('subject_id', currentPublishSubjectId);
            formData.append('school_id', currentSchoolId);
            
            console.log('Sending request to ajax_publish_marks.php with:', {
                exam_id: currentExamId,
                subject_id: currentPublishSubjectId,
                school_id: currentSchoolId
            });
            
            fetch('ajax_publish_marks.php', {
                method: 'POST',
                body: formData
            })
            .then(response => {
                console.log('Response status:', response.status);
                return response.json();
            })
            .then(data => {
                console.log('Response data:', data);
                showSavingOverlay(false);
                
                if (data.success) {
                    showSuccessModal(data.message);
                    
                    // Clear the stored subject ID and data
                    currentPublishSubjectId = null;
                    currentSubjectData = null;
                    
                    // Refresh subjects to show updated status
                    if (currentExamId) {
                        loadSubjects();
                    }
                } else {
                    showNotification(data.message, 'error');
                }
            })
            .catch(error => {
                showSavingOverlay(false);
                console.error('Error:', error);
                showNotification('Error publishing subject: ' + error.message, 'error');
            });
        }

        // Execute unpublish action
        function executeUnpublishSubject() {
            if (!currentUnpublishSubjectId) return;
            
            showSavingOverlay(true);
            
            const formData = new FormData();
            formData.append('exam_id', currentExamId);
            formData.append('subject_id', currentUnpublishSubjectId);
            
            fetch('ajax_admin_override.php', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                showSavingOverlay(false);
                
                if (data.success) {
                    showSuccessModal(data.message);
                    hideUnpublishModal();
                    
                    // Clear the stored subject ID
                    currentUnpublishSubjectId = null;
                    
                    // Refresh subjects to show updated status
                    if (currentExamId) {
                        loadSubjects();
                    }
                } else {
                    showNotification(data.message, 'error');
                }
            })
            .catch(error => {
                showSavingOverlay(false);
                console.error('Error:', error);
                showNotification('Error unpublishing subject.', 'error');
            });
        }

        // ========== NEW: TEACHER PUBLISHING WORKFLOW ==========

        // Submit exam for admin review
        function submitExamForReview() {
            if (!currentExamId) {
                showNotification('Please select an exam first.', 'error');
                return;
            }

            const confirmMessage = `
                Submit this exam for admin review?

                What happens next:
                ✓ Exam will be locked for editing
                ✓ Admin will review and approve
                ✓ You'll receive feedback within 24-48 hours
                ✓ Only after admin approval will students see results

                Are you ready to submit?
            `;

            if (!confirm(confirmMessage)) return;

            showSavingOverlay(true);

            const formData = new FormData();
            formData.append('exam_id', currentExamId);
            formData.append('school_id', currentSchoolId);
            formData.append('action', 'submit_for_review');

            fetch('ajax_teacher_exam_publishing.php', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                showSavingOverlay(false);
                
                if (data.success) {
                    showSuccessModal(data.message);
                    loadSubjects(); // Refresh to show new status
                } else {
                    showNotification(data.message || 'Error submitting exam for review.', 'error');
                }
            })
            .catch(error => {
                showSavingOverlay(false);
                console.error('Error:', error);
                showNotification('Error submitting exam for review.', 'error');
            });
        }

        // Check exam status and show appropriate action button
        function getExamPublishingButton(examStatus, teacherPublished, submittedForReview) {
            if (examStatus === 'Published') {
                return `<button class="btn btn-success" disabled title="Exam is published and locked" style="background: #057642; color: white;">
                    <i class="fas fa-shield-alt"></i> Published ✓
                </button>`;
            }

            if (teacherPublished && submittedForReview) {
                return `<button class="btn btn-warning" disabled title="Submitted for admin review" style="background: #f59e0b; color: white;">
                    <i class="fas fa-clock"></i> Under Review
                </button>`;
            }

            if (!teacherPublished) {
                return `<button class="btn btn-primary" onclick="submitExamForReview()" title="Submit exam for admin approval">
                    <i class="fas fa-paper-plane"></i> Submit for Review
                </button>`;
            }

            return '';
        }

        // Show review status details
        function showReviewStatusModal(reviewStatus, submittedAt, adminNotes) {
            const modal = document.getElementById('reviewStatusModal');
            const statusText = document.getElementById('reviewStatusText');
            const submittedAtText = document.getElementById('submittedAtText');
            const adminNotesText = document.getElementById('adminNotesText');

            statusText.textContent = reviewStatus || 'Draft';
            submittedAtText.textContent = submittedAt ? new Date(submittedAt).toLocaleDateString('en-US', {
                year: 'numeric',
                month: 'long', 
                day: 'numeric',
                hour: '2-digit',
                minute: '2-digit'
            }) : 'Not submitted';

            adminNotesText.textContent = adminNotes || 'No notes from admin';

            modal.style.display = 'flex';
            document.body.style.overflow = 'hidden';
        }

        function hideReviewStatusModal() {
            document.getElementById('reviewStatusModal').style.display = 'none';
            document.body.style.overflow = 'auto';
        }

        // Auto-refresh subjects when exam status changes
        function refreshSubjectsIfExamChanged() {
            if (currentExamId) {
                console.log('🔄 Refreshing subjects due to exam status change...');
                // Use class-level fetching for individual class status
                fetchSubjectsClassLevel();
            }
        }

        // Update exam publishing controls with current status
        function updateExamPublishingControls(examId) {
            fetch('ajax_get_exam_publishing_status.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: 'exam_id=' + encodeURIComponent(examId) + '&school_id=' + encodeURIComponent(currentSchoolId)
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    const controls = document.getElementById('examPublishingControls');
                    const statusText = document.getElementById('currentExamStatus');
                    const submissionStatus = document.getElementById('examSubmissionStatus');
                    const buttonContainer = document.getElementById('examPublishingButton');

                    // Show controls
                    controls.style.display = 'block';

                    // Update status display
                    statusText.textContent = data.exam_status || 'Draft';
                    statusText.className = 'status-value ' + (data.exam_status || 'draft').toLowerCase();

                    if (data.submitted_for_review_at) {
                        submissionStatus.textContent = 'Submitted on ' + new Date(data.submitted_for_review_at).toLocaleDateString('en-US', {
                            year: 'numeric',
                            month: 'long',
                            day: 'numeric'
                        });
                        submissionStatus.className = 'status-value pending';
                    } else {
                        submissionStatus.textContent = 'Not submitted';
                        submissionStatus.className = 'status-value';
                    }

                    // Update button
                    buttonContainer.innerHTML = getExamPublishingButton(
                        data.exam_status,
                        data.teacher_published,
                        data.submitted_for_review_at
                    );
                    
                    // Refresh the subjects table to update button states
                    if (currentExamId) {
                        // loadSubjects(); // Be careful with infinite loops here if loadSubjects calls this function
                    }
                } else {
                    console.error('Failed to load exam publishing status:', data.message);
                    // Hide controls if failed to load
                    document.getElementById('examPublishingControls').style.display = 'none';
                }
            })
            .catch(error => {
                console.error('Error loading exam publishing status:', error);
                document.getElementById('examPublishingControls').style.display = 'none';
            });
        }

        /* ==========================================================================
           Global Event Listeners for Modal Management
           ========================================================================== */

        // Close modals when clicking outside
        window.onclick = function(event) {
            const modals = [
                'publishAfterSaveModal',
                'unpublishModal',
                'alreadyPublishedModal',
                'examPublishedModal',
                'reviewStatusModal'
            ];
            
            // Handle specific modals
            modals.forEach(modalId => {
                const modal = document.getElementById(modalId);
                if (event.target === modal) {
                    modal.style.display = 'none';
                    document.body.style.overflow = 'auto';
                    // Clear currentSubjectData when closing via overlay click
                    if (modalId === 'examPublishedModal') {
                        currentSubjectData = null;
                    }
                }
            });

            // Also handle standard modals via existing handler above
            const marksModal = document.getElementById('marksModal');
            if (event.target == marksModal) {
                closeMarksModal();
            }
        }

        // Close modals with Escape key
        document.addEventListener('keydown', function(event) {
            if (event.key === 'Escape') {
                const modals = [
                    'publishAfterSaveModal',
                    'unpublishModal',
                    'alreadyPublishedModal',
                    'examPublishedModal',
                    'reviewStatusModal',
                    'marksModal',
                    'activityMarksModal',
                    'createActivityModal'
                ];
                
                modals.forEach(modalId => {
                    const modal = document.getElementById(modalId);
                    if (modal && modal.style.display === 'block' || modal && modal.style.display === 'flex') {
                        modal.style.display = 'none';
                        document.body.style.overflow = 'auto';
                        
                        if (modalId === 'marksModal') {
                            // Logic specific to closing marks modal
                            if (document.getElementById('publishAfterSaveModal').style.display === 'none') {
                                currentSubjectData = null;
                            }
                        }
                    }
                });
            }
        });
    </script>
</body>
</html>