<?php
include('session_validator.php');
?>
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>SRMS Admin - Marks Entry Details</title>
        
        <!-- CSS Files -->
        <link rel="stylesheet" href="css/bootstrap.min.css" media="screen">
        <link rel="stylesheet" href="css/font-awesome.min.css" media="screen">
        <link rel="stylesheet" href="css/animate-css/animate.min.css" media="screen">
        <link rel="stylesheet" href="css/lobipanel/lobipanel.min.css" media="screen">
        <link rel="stylesheet" href="css/select2/select2.min.css">
        <!-- DataTables CSS from CDN -->
        <link rel="stylesheet" href="https://cdn.datatables.net/1.13.6/css/dataTables.bootstrap4.min.css">
        <link rel="stylesheet" href="css/main.css" media="screen">
        <script src="js/modernizr/modernizr.min.js"></script>
        
        <style>
            .panel-title {
                color: #333;
                font-weight: bold;
            }
            .badge {
                font-size: 0.85em;
            }
            .table th {
                background-color: #f8f9fa;
            }
            .section-header {
                background-color: #e9ecef;
                padding: 10px;
                border-radius: 5px;
                margin-bottom: 15px;
            }
            .metric-card {
                border: 1px solid #dee2e6;
                border-radius: 5px;
                padding: 15px;
                margin-bottom: 15px;
                background-color: #f8f9fa;
            }
            .metric-value {
                font-size: 1.5em;
                font-weight: bold;
                color: #007bff;
            }
            .metric-label {
                color: #6c757d;
                font-size: 0.9em;
            }
            .card-header {
                background-color: #f8f9fa !important;
            }
            .student-link {
                cursor: pointer;
                color: #007bff;
                text-decoration: underline;
            }
            .student-link:hover {
                color: #0056b3;
            }
            .student-list-modal .modal-lg {
                max-width: 1000px;
            }
            .student-item {
                padding: 8px 0;
                border-bottom: 1px solid #eee;
            }
            .student-item:last-child {
                border-bottom: none;
            }
            .regd-id {
                font-weight: bold;
                color: #333;
            }
            .student-name {
                color: #555;
            }
            .marks-status {
                font-size: 0.85em;
            }
            .has-marks {
                color: #28a745;
            }
            .no-marks {
                color: #dc3545;
            }
            .missing-marks-badge {
                background-color: #dc3545;
                color: white;
                padding: 5px 10px;
                border-radius: 20px;
                font-size: 0.85em;
                cursor: pointer;
            }
            .missing-marks-badge:hover {
                background-color: #c82333;
            }
            .missing-marks-section {
                display: none;
                margin-top: 15px;
                border: 1px solid #dee2e6;
                border-radius: 5px;
                padding: 15px;
                background-color: #fff;
            }
            .missing-marks-header {
                background-color: #dc3545 !important;
                color: white;
            }
            .missing-row {
                background-color: #fff3cd !important;
            }
            .dataTables_wrapper {
                margin-top: 10px;
            }
            .dataTables_filter input {
                border: 1px solid #ccc;
                border-radius: 4px;
                padding: 4px 8px;
            }
        </style>
    </head>
    <body class="top-navbar-fixed">
        <div class="main-wrapper">
            <!-- ========== TOP NAVBAR ========== -->
            <?php include('includes/topbar.php'); ?> 
            <!-- ========== WRAPPER FOR BOTH SIDEBARS & MAIN CONTENT ========== -->
            <div class="content-wrapper">
                <div class="content-container">
                    <!-- ========== LEFT SIDEBAR ========== -->
                    <?php include('includes/leftbar.php'); ?>  
                    <!-- /.left-sidebar -->

                    <div class="main-page">
                        <div class="container-fluid">
                            <div class="row page-title-div">
                                <div class="col-md-6">
                                    <h2 class="title">Marks Entry Details Report</h2>
                                </div>
                                <div class="col-md-6 text-right">
                                    <button type="button" class="btn btn-danger" id="viewAllMissingMarks">
                                        <i class="fa fa-exclamation-triangle"></i> View All Missing Marks
                                    </button>
                                </div>
                            </div>
                            <!-- /.row -->
                            <div class="row breadcrumb-div">
                                <div class="col-md-6">
                                    <ul class="breadcrumb">
                                        <li><a href="dashboard.php"><i class="fa fa-home"></i> Home</a></li>
                                        <li>Reports</li>
                                        <li class="active">Marks Entry Details</li>
                                    </ul>
                                </div>
                            </div>
                            <!-- /.row -->
                        </div>

                        <div class="container-fluid">
                            <div class="row">
                                <div class="col-md-12">
                                    <div class="panel">
                                        <div class="panel-heading">
                                            <div class="panel-title">
                                                <h5><i class="fa fa-chart-bar"></i> Marks Entry Details for All Classes</h5>
                                            </div>
                                        </div>
                                        <div class="panel-body">
                                            <?php
                                            include("includes/db.php");

                                            // Get current academic year
                                            $currentYearQuery = "SELECT ay_ad FROM academic_years WHERE status = 'active' LIMIT 1";
                                            $currentYearResult = $conn->query($currentYearQuery);
                                            $currentAcademicYear = '';
                                            if ($currentYearResult->num_rows > 0) {
                                                $currentYearRow = $currentYearResult->fetch_assoc();
                                                $currentAcademicYear = $currentYearRow['ay_ad'];
                                            }

                                            // Summary Statistics
                                            $summaryQuery = "SELECT 
                                                COUNT(DISTINCT CONCAT(m.class_id, '-', m.section_id)) as total_classes_sections,
                                                COUNT(DISTINCT m.subject_id) as total_subjects,
                                                COUNT(DISTINCT m.student_id) as total_students,
                                                COUNT(DISTINCT CONCAT(m.class_id, '-', m.section_id, '-', m.subject_id)) as total_subject_entries,
                                                SUM(CASE WHEN m.marks > 0 THEN 1 ELSE 0 END) as total_marks_entered,
                                                COUNT(DISTINCT CASE WHEN m.marks = 0 OR m.marks IS NULL THEN m.student_id END) as total_students_without_marks,
                                                AVG(m.marks) as average_marks
                                            FROM marks m";
                                            
                                            $summaryResult = $conn->query($summaryQuery);
                                            $summary = $summaryResult->fetch_assoc();
                                            ?>
                                            
                                            <!-- Summary Cards -->
                                            <div class="row">
                                                <div class="col-md-2 col-sm-6">
                                                    <div class="metric-card text-center">
                                                        <div class="metric-value"><?php echo $summary['total_classes_sections'] ?? 0; ?></div>
                                                        <div class="metric-label">Class-Sections</div>
                                                    </div>
                                                </div>
                                                <div class="col-md-2 col-sm-6">
                                                    <div class="metric-card text-center">
                                                        <div class="metric-value"><?php echo $summary['total_subjects'] ?? 0; ?></div>
                                                        <div class="metric-label">Subjects</div>
                                                    </div>
                                                </div>
                                                <div class="col-md-2 col-sm-6">
                                                    <div class="metric-card text-center">
                                                        <div class="metric-value"><?php echo $summary['total_students'] ?? 0; ?></div>
                                                        <div class="metric-label">Students</div>
                                                    </div>
                                                </div>
                                                <div class="col-md-2 col-sm-6">
                                                    <div class="metric-card text-center">
                                                        <div class="metric-value"><?php echo $summary['total_marks_entered'] ?? 0; ?></div>
                                                        <div class="metric-label">Marks Entered</div>
                                                    </div>
                                                </div>
                                                <div class="col-md-2 col-sm-6">
                                                    <div class="metric-card text-center" style="background-color: #ffe6e6; border-color: #dc3545;">
                                                        <div class="metric-value" style="color: #dc3545;"><?php echo $summary['total_students_without_marks'] ?? 0; ?></div>
                                                        <div class="metric-label">Missing Marks</div>
                                                    </div>
                                                </div>
                                                <div class="col-md-2 col-sm-6">
                                                    <div class="metric-card text-center">
                                                        <div class="metric-value"><?php echo number_format($summary['average_marks'] ?? 0, 2); ?></div>
                                                        <div class="metric-label">Avg. Marks</div>
                                                    </div>
                                                </div>
                                            </div>

                                            <!-- Academic Year Filter -->
                                            <div class="row mb-4">
                                                <div class="col-md-4">
                                                    <div class="form-group">
                                                        <label for="academic_year_filter">Filter by Academic Year</label>
                                                        <select id="academic_year_filter" class="form-control">
                                                            <option value="">All Academic Years</option>
                                                            <?php
                                                            $yearsQuery = "SELECT DISTINCT academic_year FROM studentsub ORDER BY academic_year DESC";
                                                            $yearsResult = $conn->query($yearsQuery);
                                                            while ($yearRow = $yearsResult->fetch_assoc()) {
                                                                $selected = ($yearRow['academic_year'] == $currentAcademicYear) ? 'selected' : '';
                                                                echo "<option value='" . $yearRow['academic_year'] . "' $selected>" . $yearRow['academic_year'] . "</option>";
                                                            }
                                                            ?>
                                                        </select>
                                                    </div>
                                                </div>
                                                <div class="col-md-8 text-right">
                                                    <button type="button" class="btn btn-outline-danger" id="exportAllMissingMarks">
                                                        <i class="fa fa-download"></i> Export All Missing Marks
                                                    </button>
                                                </div>
                                            </div>

                                            <!-- Report 1: Detailed Marks Submission by Class-Section-Subject -->
                                            <div class="section-header">
                                                <h4><i class="fa fa-list"></i> Detailed Marks Submission Report</h4>
                                                <p class="mb-0">Showing data for academic year: <strong id="currentYearDisplay"><?php echo $currentAcademicYear ?: 'All Years'; ?></strong></p>
                                            </div>
                                            
                                            <?php
                                            // Get all classes with sections from class_section table
                                            $classesQuery = "SELECT DISTINCT 
                                                c.class_id, 
                                                c.class as class_name,
                                                c.class_numeric,
                                                s.section_id,
                                                s.section_name,
                                                cs.id as class_section_id
                                            FROM class_section cs
                                            INNER JOIN classes c ON cs.class_id = c.class_id
                                            INNER JOIN sections s ON cs.section_id = s.section_id
                                            WHERE cs.status = 1
                                            ORDER BY c.class_numeric, s.section_name";
                                            
                                            $classesResult = $conn->query($classesQuery);
                                            
                                            if ($classesResult->num_rows > 0) {
                                                $totalClasses = 0;
                                                
                                                while ($classRow = $classesResult->fetch_assoc()) {
                                                    $totalClasses++;
                                                    $classId = $classRow['class_id'];
                                                    $className = $classRow['class_name'];
                                                    $classNumeric = $classRow['class_numeric'];
                                                    $sectionId = $classRow['section_id'];
                                                    $sectionName = $classRow['section_name'];
                                                    
                                                    echo "<div class='card mb-4 class-section-card' data-class='$classId' data-section='$sectionId'>";
                                                    echo "<div class='card-header d-flex justify-content-between align-items-center'>";
                                                    echo "<h5 class='mb-0'>Class: <strong>Grade $classNumeric ($className)</strong> - Section: <strong>$sectionName</strong></h5>";
                                                    
                                                    // Button to view missing marks for this class-section
                                                    echo "<button type='button' class='btn btn-sm btn-outline-danger view-class-missing-marks' 
                                                          data-class='$classId' 
                                                          data-section='$sectionId'
                                                          data-class-name='Grade $classNumeric ($className)'
                                                          data-section-name='$sectionName'>
                                                        <i class='fa fa-exclamation-circle'></i> View Missing Marks
                                                    </button>";
                                                    echo "</div>";
                                                    echo "<div class='card-body'>";
                                                    
                                                    // Get academic years available for this class-section from studentsub
                                                    $yearsForClassQuery = "SELECT DISTINCT academic_year 
                                                                          FROM studentsub 
                                                                          WHERE class_id = $classId 
                                                                          AND section_id = $sectionId
                                                                          ORDER BY academic_year DESC";
                                                    $yearsForClassResult = $conn->query($yearsForClassQuery);
                                                    
                                                    if ($yearsForClassResult->num_rows > 0) {
                                                        while ($yearRow = $yearsForClassResult->fetch_assoc()) {
                                                            $academicYear = $yearRow['academic_year'];
                                                            
                                                            echo "<div class='mb-4 year-section' data-year='$academicYear'>";
                                                            echo "<h6><span class='badge badge-primary'>Academic Year: $academicYear</span></h6>";
                                                            
                                                            // Get subjects for this class-section and academic year
                                                            $subjectsQuery = "SELECT DISTINCT
                                                                s.id as subject_id,
                                                                s.subject_code,
                                                                s.subject_name,
                                                                s.type as subject_type
                                                            FROM subjects s
                                                            WHERE s.id IN (
                                                                SELECT DISTINCT csm.subject_id
                                                                FROM class_subject_mapping csm
                                                                WHERE csm.class_id = $classId 
                                                                AND csm.section_id = $sectionId
                                                                AND (csm.academic_year = '$academicYear' OR csm.academic_year IS NULL)
                                                            )
                                                            ORDER BY s.subject_code";
                                                            
                                                            $subjectsResult = $conn->query($subjectsQuery);
                                                            
                                                            if ($subjectsResult && $subjectsResult->num_rows > 0) {
                                                                echo "<div class='table-responsive'>";
                                                                echo "<table class='table table-bordered table-sm marks-table'>";
                                                                echo "<thead class='thead-light'>";
                                                                echo "<tr>
                                                                    <th>Subject Code</th>
                                                                    <th>Subject Name</th>
                                                                    <th>Type</th>
                                                                    <th>Total Students</th>
                                                                    <th>With Marks</th>
                                                                    <th>Without Marks</th>
                                                                    <th>Average Marks</th>
                                                                    <th>Highest</th>
                                                                    <th>Lowest</th>
                                                                    <th>Completion</th>
                                                                    <th>Student List</th>
                                                                </tr>";
                                                                echo "</thead>";
                                                                echo "<tbody>";
                                                                
                                                                $classTotalStudents = 0;
                                                                $classMarksEntered = 0;
                                                                $classMarksMissing = 0;
                                                                $classSubjectsWithMissingMarks = 0;
                                                                
                                                                while ($subjectRow = $subjectsResult->fetch_assoc()) {
                                                                    $subjectId = $subjectRow['subject_id'];
                                                                    $subjectCode = $subjectRow['subject_code'];
                                                                    $subjectName = $subjectRow['subject_name'];
                                                                    
                                                                    // Get total students enrolled in this subject for this class-section-year
                                                                    $enrolledStudentsQuery = "SELECT COUNT(DISTINCT ss.student_id) as total_students,
                                                                        GROUP_CONCAT(DISTINCT ss.student_id) as student_ids
                                                                        FROM studentsub ss
                                                                        WHERE ss.class_id = $classId 
                                                                        AND ss.section_id = $sectionId
                                                                        AND ss.academic_year = '$academicYear'
                                                                        AND (
                                                                            ss.sub1 = '$subjectCode' OR 
                                                                            ss.sub2 = '$subjectCode' OR 
                                                                            ss.sub3 = '$subjectCode' OR 
                                                                            ss.sub4 = '$subjectCode' OR 
                                                                            ss.sub5 = '$subjectCode' OR 
                                                                            ss.sub6 = '$subjectCode' OR 
                                                                            ss.sub7 = '$subjectCode'
                                                                        )";
                                                                    
                                                                    $enrolledResult = $conn->query($enrolledStudentsQuery);
                                                                    $enrolledData = $enrolledResult->fetch_assoc();
                                                                    $totalStudents = $enrolledData['total_students'] ?? 0;
                                                                    $studentIds = $enrolledData['student_ids'] ?? '';
                                                                    
                                                                    // Get marks statistics
                                                                    $marksStatsQuery = "SELECT 
                                                                        COUNT(DISTINCT m.student_id) as students_with_marks,
                                                                        COUNT(DISTINCT CASE WHEN m.marks = 0 OR m.marks IS NULL THEN m.student_id END) as students_without_marks,
                                                                        AVG(CASE WHEN m.marks > 0 THEN m.marks END) as average_marks,
                                                                        MAX(m.marks) as highest_marks,
                                                                        MIN(CASE WHEN m.marks > 0 THEN m.marks END) as lowest_marks
                                                                    FROM marks m
                                                                    WHERE m.class_id = $classId 
                                                                    AND m.section_id = $sectionId
                                                                    AND m.subject_id = $subjectId";
                                                                    
                                                                    $marksStatsResult = $conn->query($marksStatsQuery);
                                                                    $marksStats = $marksStatsResult->fetch_assoc();
                                                                    
                                                                    $withMarks = $marksStats['students_with_marks'] ?? 0;
                                                                    $withoutMarks = $marksStats['students_without_marks'] ?? 0;
                                                                    $avgMarks = number_format($marksStats['average_marks'] ?? 0, 2);
                                                                    $highest = $marksStats['highest_marks'] ?? 'N/A';
                                                                    $lowest = $marksStats['lowest_marks'] ?? 'N/A';
                                                                    
                                                                    // Calculate completion percentage
                                                                    $completion = 0;
                                                                    if ($totalStudents > 0) {
                                                                        $completion = round(($withMarks / $totalStudents) * 100);
                                                                    }
                                                                    
                                                                    $classTotalStudents += $totalStudents;
                                                                    $classMarksEntered += $withMarks;
                                                                    $classMarksMissing += $withoutMarks;
                                                                    if ($withoutMarks > 0) {
                                                                        $classSubjectsWithMissingMarks++;
                                                                    }
                                                                    
                                                                    // Determine badge color for completion
                                                                    $completionBadge = '';
                                                                    if ($completion >= 90) {
                                                                        $completionBadge = 'badge-success';
                                                                    } elseif ($completion >= 50) {
                                                                        $completionBadge = 'badge-warning';
                                                                    } else {
                                                                        $completionBadge = 'badge-danger';
                                                                    }
                                                                    
                                                                    // Row class for subjects with missing marks
                                                                    $rowClass = $withoutMarks > 0 ? 'missing-row' : '';
                                                                    
                                                                    echo "<tr class='$rowClass'>";
                                                                    echo "<td>" . htmlspecialchars($subjectCode) . "</td>";
                                                                    echo "<td>" . htmlspecialchars($subjectName) . "</td>";
                                                                    echo "<td><span class='badge badge-info'>" . htmlspecialchars($subjectRow['subject_type']) . "</span></td>";
                                                                    echo "<td class='text-center'>" . $totalStudents . "</td>";
                                                                    echo "<td class='text-center'><span class='badge badge-success'>" . $withMarks . "</span></td>";
                                                                    echo "<td class='text-center'>";
                                                                    if ($withoutMarks > 0) {
                                                                        echo "<span class='badge badge-danger missing-marks-badge' 
                                                                              data-class='$classId' 
                                                                              data-section='$sectionId'
                                                                              data-year='$academicYear'
                                                                              data-subject='$subjectId'
                                                                              data-subject-code='$subjectCode'
                                                                              data-subject-name='" . htmlspecialchars($subjectName) . "'>
                                                                            " . $withoutMarks . "
                                                                        </span>";
                                                                    } else {
                                                                        echo "<span class='badge badge-secondary'>" . $withoutMarks . "</span>";
                                                                    }
                                                                    echo "</td>";
                                                                    echo "<td class='text-center'>" . $avgMarks . "</td>";
                                                                    echo "<td class='text-center'><span class='badge badge-success'>" . $highest . "</span></td>";
                                                                    echo "<td class='text-center'><span class='badge badge-warning'>" . ($lowest === 'N/A' ? 'N/A' : $lowest) . "</span></td>";
                                                                    echo "<td class='text-center'><span class='badge $completionBadge'>" . $completion . "%</span></td>";
                                                                    
                                                                    // Student list link
                                                                    echo "<td class='text-center'>";
                                                                    if ($totalStudents > 0) {
                                                                        echo "<a href='#' class='student-link btn btn-sm btn-outline-primary' 
                                                                              data-class='$classId' 
                                                                              data-section='$sectionId'
                                                                              data-year='$academicYear'
                                                                              data-subject='$subjectId'
                                                                              data-subject-code='$subjectCode'
                                                                              data-subject-name='" . htmlspecialchars($subjectName) . "'
                                                                              data-student-ids='$studentIds'>
                                                                            <i class='fa fa-users'></i> View ($totalStudents)
                                                                        </a>";
                                                                    } else {
                                                                        echo "<span class='text-muted'>No students</span>";
                                                                    }
                                                                    echo "</td>";
                                                                    echo "</tr>";
                                                                }
                                                                
                                                                // Calculate class completion percentage
                                                                $classCompletion = 0;
                                                                if ($classTotalStudents > 0) {
                                                                    $classCompletion = round(($classMarksEntered / $classTotalStudents) * 100);
                                                                }
                                                                
                                                                echo "</tbody>";
                                                                echo "<tfoot class='table-secondary'>";
                                                                echo "<tr>";
                                                                echo "<td colspan='3'><strong>Class Totals for $academicYear:</strong></td>";
                                                                echo "<td class='text-center'><strong>" . $classTotalStudents . "</strong></td>";
                                                                echo "<td class='text-center'><strong>" . $classMarksEntered . "</strong></td>";
                                                                echo "<td class='text-center'><strong>" . $classMarksMissing . "</strong></td>";
                                                                echo "<td colspan='3'></td>";
                                                                echo "<td class='text-center'><strong><span class='badge " . ($classCompletion >= 90 ? 'badge-success' : ($classCompletion >= 50 ? 'badge-warning' : 'badge-danger')) . "'>" . $classCompletion . "%</span></strong></td>";
                                                                echo "<td></td>";
                                                                echo "</tr>";
                                                                echo "</tfoot>";
                                                                echo "</table>";
                                                                echo "</div>"; // End table-responsive
                                                                
                                                                // Hidden section for missing marks details
                                                                if ($classMarksMissing > 0) {
                                                                    echo "<div class='missing-marks-section' id='missing-marks-$classId-$sectionId-$academicYear'>";
                                                                    echo "<h6 class='text-danger'><i class='fa fa-exclamation-triangle'></i> Missing Marks Details for $academicYear</h6>";
                                                                    echo "<p><strong>Subjects with missing marks:</strong> $classSubjectsWithMissingMarks</p>";
                                                                    echo "<p><strong>Total students with missing marks:</strong> $classMarksMissing</p>";
                                                                    echo "<div class='text-right'>";
                                                                    echo "<button type='button' class='btn btn-sm btn-outline-danger mr-2' onclick=\"exportClassMissingMarks($classId, $sectionId, '$academicYear')\">";
                                                                    echo "<i class='fa fa-download'></i> Export Missing Marks";
                                                                    echo "</button>";
                                                                    echo "<button type='button' class='btn btn-sm btn-danger' onclick=\"printClassMissingMarks($classId, $sectionId, '$academicYear')\">";
                                                                    echo "<i class='fa fa-print'></i> Print Report";
                                                                    echo "</button>";
                                                                    echo "</div>";
                                                                    echo "</div>";
                                                                }
                                                            } else {
                                                                echo "<div class='alert alert-info'>No subjects assigned to this class-section for academic year $academicYear.</div>";
                                                            }
                                                            
                                                            echo "</div>"; // End year-section
                                                        }
                                                    } else {
                                                        echo "<div class='alert alert-warning'>No academic year data found for this class-section.</div>";
                                                    }
                                                    
                                                    echo "</div>"; // End card-body
                                                    echo "</div>"; // End card
                                                }
                                                
                                                echo "<div class='alert alert-primary'>Total Classes-Sections with marks data: <strong>$totalClasses</strong></div>";
                                            } else {
                                                echo "<div class='alert alert-warning'>No class-sections found in the system.</div>";
                                            }
                                            ?>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Student List Modal -->
        <div class="modal fade student-list-modal" id="studentListModal" tabindex="-1" role="dialog" aria-labelledby="studentListModalLabel" aria-hidden="true">
            <div class="modal-dialog modal-lg">
                <div class="modal-content">
                    <div class="modal-header bg-primary text-white">
                        <h5 class="modal-title" id="studentListModalLabel">
                            <i class="fa fa-users"></i> Students Enrolled in Subject
                        </h5>
                        <button type="button" class="close text-white" data-dismiss="modal" aria-label="Close">
                            <span aria-hidden="true">&times;</span>
                        </button>
                    </div>
                    <div class="modal-body" id="studentListModalBody">
                        <!-- Student list will be loaded here -->
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                    </div>
                </div>
            </div>
        </div>

        <!-- Missing Marks Modal -->
        <div class="modal fade" id="missingMarksModal" tabindex="-1" role="dialog" aria-labelledby="missingMarksModalLabel" aria-hidden="true">
            <div class="modal-dialog modal-xl">
                <div class="modal-content">
                    <div class="modal-header bg-danger text-white">
                        <h5 class="modal-title" id="missingMarksModalLabel">
                            <i class="fa fa-exclamation-triangle"></i> Missing Marks Report
                        </h5>
                        <button type="button" class="close text-white" data-dismiss="modal" aria-label="Close">
                            <span aria-hidden="true">&times;</span>
                        </button>
                    </div>
                    <div class="modal-body" id="missingMarksModalBody">
                        <!-- Missing marks report will be loaded here -->
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                        <button type="button" class="btn btn-danger" id="exportMissingMarksReport">
                            <i class="fa fa-download"></i> Export Report
                        </button>
                        <button type="button" class="btn btn-primary" id="printMissingMarksReport">
                            <i class="fa fa-print"></i> Print Report
                        </button>
                    </div>
                </div>
            </div>
        </div>

        <!-- JavaScript Files -->
        <script src="js/jquery/jquery-2.2.4.min.js"></script>
        <script src="js/bootstrap/bootstrap.min.js"></script>
        <script src="js/pace/pace.min.js"></script>
        <script src="js/lobipanel/lobipanel.min.js"></script>
        <script src="js/iscroll/iscroll.js"></script>
        <!-- DataTables from CDN -->
        <script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>
        <script src="https://cdn.datatables.net/1.13.6/js/dataTables.bootstrap4.min.js"></script>
        <script src="js/sweetalert2.all.min.js"></script>
        <script src="js/prism/prism.js"></script>
        <script src="js/main.js"></script>
        
        <script>
            $(document).ready(function() {
                // Update current year display
                function updateYearDisplay() {
                    const selectedYear = $('#academic_year_filter').val();
                    if (selectedYear) {
                        $('#currentYearDisplay').text(selectedYear);
                    } else {
                        $('#currentYearDisplay').text('All Years');
                    }
                }
                
                // Initialize year filter
                $('#academic_year_filter').change(function() {
                    const selectedYear = $(this).val();
                    updateYearDisplay();
                    
                    // Show/hide year sections
                    $('.year-section').each(function() {
                        const year = $(this).data('year');
                        if (!selectedYear || year === selectedYear) {
                            $(this).show();
                        } else {
                            $(this).hide();
                        }
                    });
                    
                    // Show/hide class-section cards based on visible year sections
                    $('.class-section-card').each(function() {
                        const card = $(this);
                        const hasVisibleYears = card.find('.year-section:visible').length > 0;
                        if (hasVisibleYears) {
                            card.show();
                        } else {
                            card.hide();
                        }
                    });
                });
                
                // Initialize on page load
                updateYearDisplay();
                $('#academic_year_filter').trigger('change');
                
                // Initialize DataTables for all marks tables
                $('.marks-table').DataTable({
                    "paging": true,
                    "pageLength": 10,
                    "lengthMenu": [[10, 25, 50, -1], [10, 25, 50, "All"]],
                    "searching": true,
                    "ordering": true,
                    "info": true,
                    "autoWidth": false,
                    "responsive": true,
                    "dom": '<"row"<"col-sm-12 col-md-6"l><"col-sm-12 col-md-6"f>>' +
                           '<"row"<"col-sm-12"tr>>' +
                           '<"row"<"col-sm-12 col-md-5"i><"col-sm-12 col-md-7"p>>',
                    "language": {
                        "search": "Filter:",
                        "lengthMenu": "Show _MENU_ entries",
                        "info": "Showing _START_ to _END_ of _TOTAL_ entries",
                        "infoEmpty": "Showing 0 to 0 of 0 entries",
                        "infoFiltered": "(filtered from _MAX_ total entries)"
                    }
                });
                
                // Student list click handler
                $(document).on('click', '.student-link', function(e) {
                    e.preventDefault();
                    
                    const classId = $(this).data('class');
                    const sectionId = $(this).data('section');
                    const subjectId = $(this).data('subject');
                    const academicYear = $(this).data('year');
                    const subjectCode = $(this).data('subject-code');
                    const subjectName = $(this).data('subject-name');
                    const studentIds = $(this).data('student-ids');
                    
                    // Update modal title
                    $('#studentListModalLabel').html(
                        '<i class="fa fa-users"></i> ' + subjectName + ' (' + subjectCode + ')'
                    );
                    
                    // Show loading
                    $('#studentListModalBody').html(`
                        <div class="text-center py-5">
                            <div class="spinner-border text-primary" role="status">
                                <span class="sr-only">Loading...</span>
                            </div>
                            <p class="mt-2">Loading student list...</p>
                        </div>
                    `);
                    
                    // Load student list via AJAX
                    $.ajax({
                        url: 'ajax/get_students_for_subject.php',
                        type: 'POST',
                        data: {
                            class_id: classId,
                            section_id: sectionId,
                            subject_id: subjectId,
                            academic_year: academicYear,
                            subject_code: subjectCode,
                            subject_name: subjectName,
                            student_ids: studentIds
                        },
                        success: function(response) {
                            $('#studentListModalBody').html(response);
                            // Initialize DataTable for student list
                            if ($.fn.DataTable) {
                                $('#studentListTable').DataTable({
                                    "paging": true,
                                    "pageLength": 10,
                                    "searching": true,
                                    "ordering": true,
                                    "info": true,
                                    "autoWidth": false,
                                    "responsive": true,
                                    "order": [[1, 'asc']],
                                    "language": {
                                        "search": "Search students:",
                                        "lengthMenu": "Show _MENU_ students"
                                    }
                                });
                            }
                        },
                        error: function(xhr, status, error) {
                            console.error('AJAX Error:', error);
                            $('#studentListModalBody').html(`
                                <div class="alert alert-danger">
                                    <i class="fa fa-exclamation-triangle"></i> 
                                    Failed to load student list. Error: ${error}
                                    <br><small>Please check if the ajax file exists.</small>
                                </div>
                            `);
                        }
                    });
                    
                    // Show modal
                    $('#studentListModal').modal('show');
                });
                
                // Missing marks badge click handler
                $(document).on('click', '.missing-marks-badge', function(e) {
                    e.preventDefault();
                    e.stopPropagation();
                    
                    const classId = $(this).data('class');
                    const sectionId = $(this).data('section');
                    const academicYear = $(this).data('year');
                    const subjectId = $(this).data('subject');
                    const subjectCode = $(this).data('subject-code');
                    const subjectName = $(this).data('subject-name');
                    
                    // Show loading in missing marks modal
                    $('#missingMarksModalLabel').html(
                        '<i class="fa fa-exclamation-triangle"></i> Missing Marks: ' + subjectName
                    );
                    
                    $('#missingMarksModalBody').html(`
                        <div class="text-center py-5">
                            <div class="spinner-border text-danger" role="status">
                                <span class="sr-only">Loading...</span>
                            </div>
                            <p class="mt-2">Loading missing marks report...</p>
                        </div>
                    `);
                    
                    // Load missing marks report via AJAX
                    $.ajax({
                        url: 'ajax/get_missing_marks_report.php',
                        type: 'POST',
                        data: {
                            class_id: classId,
                            section_id: sectionId,
                            academic_year: academicYear,
                            subject_id: subjectId,
                            subject_code: subjectCode,
                            subject_name: subjectName
                        },
                        success: function(response) {
                            $('#missingMarksModalBody').html(response);
                            
                            // Initialize DataTable if exists
                            if ($.fn.DataTable && $('#missingMarksTable').length) {
                                $('#missingMarksTable').DataTable({
                                    "paging": true,
                                    "pageLength": 10,
                                    "searching": true,
                                    "ordering": true,
                                    "info": true,
                                    "responsive": true
                                });
                            }
                            
                            // Store export data
                            $('#missingMarksModalBody').data('export-data', {
                                class_id: classId,
                                section_id: sectionId,
                                academic_year: academicYear,
                                subject_code: subjectCode,
                                type: 'subject'
                            });
                        },
                        error: function(xhr, status, error) {
                            console.error('AJAX Error:', error);
                            $('#missingMarksModalBody').html(`
                                <div class="alert alert-danger">
                                    <i class="fa fa-exclamation-triangle"></i> 
                                    Failed to load missing marks report. Error: ${error}
                                    <br><small>Please check if the ajax file exists.</small>
                                </div>
                            `);
                        }
                    });
                    
                    // Show missing marks modal
                    $('#missingMarksModal').modal('show');
                });
                
                // View missing marks for specific class-section
                $(document).on('click', '.view-class-missing-marks', function() {
                    const classId = $(this).data('class');
                    const sectionId = $(this).data('section');
                    const className = $(this).data('class-name');
                    const sectionName = $(this).data('section-name');
                    
                    // Show loading in missing marks modal
                    $('#missingMarksModalLabel').html(
                        '<i class="fa fa-exclamation-triangle"></i> Missing Marks: ' + className + ' - ' + sectionName
                    );
                    
                    $('#missingMarksModalBody').html(`
                        <div class="text-center py-5">
                            <div class="spinner-border text-danger" role="status">
                                <span class="sr-only">Loading...</span>
                            </div>
                            <p class="mt-2">Loading class missing marks report...</p>
                        </div>
                    `);
                    
                    // Get selected academic year
                    const academicYear = $('#academic_year_filter').val();
                    
                    // Load class missing marks report via AJAX
                    $.ajax({
                        url: 'ajax/get_class_missing_marks.php',
                        type: 'POST',
                        data: {
                            class_id: classId,
                            section_id: sectionId,
                            academic_year: academicYear
                        },
                        success: function(response) {
                            $('#missingMarksModalBody').html(response);
                            
                            // Initialize DataTable if exists
                            if ($.fn.DataTable && $('#classMissingMarksTable').length) {
                                $('#classMissingMarksTable').DataTable({
                                    "paging": true,
                                    "pageLength": 10,
                                    "searching": true,
                                    "ordering": true,
                                    "info": true,
                                    "responsive": true
                                });
                            }
                            
                            // Store export data
                            $('#missingMarksModalBody').data('export-data', {
                                class_id: classId,
                                section_id: sectionId,
                                academic_year: academicYear,
                                type: 'class'
                            });
                        },
                        error: function(xhr, status, error) {
                            console.error('AJAX Error:', error);
                            $('#missingMarksModalBody').html(`
                                <div class="alert alert-danger">
                                    <i class="fa fa-exclamation-triangle"></i> 
                                    Failed to load missing marks report. Error: ${error}
                                    <br><small>Please check if the ajax file exists.</small>
                                </div>
                            `);
                        }
                    });
                    
                    // Show missing marks modal
                    $('#missingMarksModal').modal('show');
                });
                
                // Export all missing marks
                $('#exportAllMissingMarks').click(function() {
                    const academicYear = $('#academic_year_filter').val();
                    let url = 'export_missing_marks.php';
                    if (academicYear) {
                        url += '?academic_year=' + encodeURIComponent(academicYear);
                    }
                    window.location.href = url;
                });
                
                // View all missing marks
                $('#viewAllMissingMarks').click(function() {
                    const academicYear = $('#academic_year_filter').val();
                    
                    // Show loading in missing marks modal
                    $('#missingMarksModalLabel').html(
                        '<i class="fa fa-exclamation-triangle"></i> All Missing Marks Report'
                    );
                    
                    $('#missingMarksModalBody').html(`
                        <div class="text-center py-5">
                            <div class="spinner-border text-danger" role="status">
                                <span class="sr-only">Loading...</span>
                            </div>
                            <p class="mt-2">Loading all missing marks report...</p>
                        </div>
                    `);
                    
                    // Load all missing marks report via AJAX
                    $.ajax({
                        url: 'ajax/get_all_missing_marks.php',
                        type: 'POST',
                        data: {
                            academic_year: academicYear
                        },
                        success: function(response) {
                            $('#missingMarksModalBody').html(response);
                            
                            // Initialize DataTable if exists
                            if ($.fn.DataTable && $('#allMissingMarksTable').length) {
                                $('#allMissingMarksTable').DataTable({
                                    "paging": true,
                                    "pageLength": 10,
                                    "searching": true,
                                    "ordering": true,
                                    "info": true,
                                    "responsive": true
                                });
                            }
                            
                            // Store export data
                            $('#missingMarksModalBody').data('export-data', {
                                academic_year: academicYear,
                                type: 'all'
                            });
                        },
                        error: function(xhr, status, error) {
                            console.error('AJAX Error:', error);
                            $('#missingMarksModalBody').html(`
                                <div class="alert alert-danger">
                                    <i class="fa fa-exclamation-triangle"></i> 
                                    Failed to load missing marks report. Error: ${error}
                                    <br><small>Please check if the ajax file exists.</small>
                                </div>
                            `);
                        }
                    });
                    
                    // Show missing marks modal
                    $('#missingMarksModal').modal('show');
                });
                
                // Export missing marks report from modal
                $('#exportMissingMarksReport').click(function() {
                    const exportData = $('#missingMarksModalBody').data('export-data');
                    if (!exportData) {
                        Swal.fire('Error', 'No export data available', 'error');
                        return;
                    }
                    
                    let url = 'export_missing_marks.php?';
                    const params = [];
                    
                    if (exportData.class_id) params.push('class_id=' + exportData.class_id);
                    if (exportData.section_id) params.push('section_id=' + exportData.section_id);
                    if (exportData.subject_code) params.push('subject_code=' + encodeURIComponent(exportData.subject_code));
                    if (exportData.academic_year) params.push('academic_year=' + encodeURIComponent(exportData.academic_year));
                    if (exportData.type) params.push('type=' + exportData.type);
                    
                    window.location.href = url + params.join('&');
                });
                
                // Print missing marks report
                $('#printMissingMarksReport').click(function() {
                    const printContent = $('#missingMarksModalBody').html();
                    const originalTitle = $('#missingMarksModalLabel').text();
                    
                    const printWindow = window.open('', '_blank');
                    printWindow.document.write(`
                        <html>
                        <head>
                            <title>${originalTitle}</title>
                            <link rel="stylesheet" href="css/bootstrap.min.css">
                            <style>
                                body { padding: 20px; }
                                h3 { color: #dc3545; margin-bottom: 20px; }
                                table { width: 100%; margin-bottom: 20px; }
                                th { background-color: #f8f9fa; }
                                .badge { font-size: 0.9em; }
                                @media print {
                                    .no-print { display: none; }
                                }
                            </style>
                        </head>
                        <body>
                            <h3>${originalTitle}</h3>
                            ${printContent}
                            <div class="no-print text-center mt-4">
                                <button onclick="window.print()" class="btn btn-primary">Print</button>
                                <button onclick="window.close()" class="btn btn-secondary ml-2">Close</button>
                            </div>
                        </body>
                        </html>
                    `);
                    printWindow.document.close();
                });
                
                // Function to export class missing marks
                window.exportClassMissingMarks = function(classId, sectionId, academicYear) {
                    window.location.href = 'export_missing_marks.php?class_id=' + classId + 
                                           '&section_id=' + sectionId + 
                                           '&academic_year=' + encodeURIComponent(academicYear);
                };
                
                // Function to print class missing marks
                window.printClassMissingMarks = function(classId, sectionId, academicYear) {
                    window.open('print_missing_marks.php?class_id=' + classId + 
                               '&section_id=' + sectionId + 
                               '&academic_year=' + encodeURIComponent(academicYear), 
                               '_blank');
                };
                
                // Check if DataTables is loaded
                if (!$.fn.DataTable) {
                    console.warn('DataTables not loaded. Some features may not work properly.');
                    // Fallback: Add basic search functionality
                    $('.marks-table').each(function() {
                        const $table = $(this);
                        const $input = $('<input type="text" class="form-control form-control-sm mb-2" placeholder="Search...">');
                        $table.before($input);
                        
                        $input.on('keyup', function() {
                            const value = $(this).val().toLowerCase();
                            $table.find('tbody tr').filter(function() {
                                $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1);
                            });
                        });
                    });
                }
            });
        </script>
    </body>
</html>