<?php
include('session_validator.php');
include("includes/db.php");

// Initialize variables
$classId = '';
$examId = '';
$selected_sections = [];
$group_by = 'student'; // Default grouping
$legclass = '';
$examtype = '';
$examyear = '';
$zero_marks_data = [];
$sections = [];

// Check if form is submitted
if (isset($_GET['class_id']) && isset($_GET['exam_id'])) {
    $classId = $_GET['class_id'];
    $examId = $_GET['exam_id'];
    $selected_sections = $_GET['section_id'] ?? [];
    $group_by = $_GET['group_by'] ?? 'student';

    // Handle single selection or "all" option
    if (is_string($selected_sections)) {
        $selected_sections = [$selected_sections];
    }
    
    // Check if "all" is selected or no sections selected
    if (in_array('all', $selected_sections) || empty($selected_sections)) {
        $selected_sections = 'all';
    }

    // Get exam details
    $examquery = "SELECT * FROM examination_type WHERE id = ?";
    $examstmt = $conn->prepare($examquery);
    $examstmt->bind_param("i", $examId);
    $examstmt->execute();
    $examresult = $examstmt->get_result();
    $examDetails = $examresult->fetch_assoc();
    $examtype = $examDetails['exam_type'] ?? '';
    $examyear = $examDetails['exm_year'] ?? '';
    $examstmt->close();

    // Get class details
    $classquery = "SELECT class_id, class, class_numeric FROM classes WHERE class_id = ?";
    $classstmt = $conn->prepare($classquery);
    $classstmt->bind_param("i", $classId);
    $classstmt->execute();
    $classresult = $classstmt->get_result();
    $classDetails = $classresult->fetch_assoc();
    $legclass = $classDetails['class'] ?? '';
    $class_numeric = $classDetails['class_numeric'] ?? '';
    $classstmt->close();

    // Get sections for this class
    $sectionquery = "SELECT s.section_id, s.section_name 
                    FROM sections s
                    INNER JOIN class_section cs ON s.section_id = cs.section_id
                    WHERE cs.class_id = ? AND s.status = 1
                    ORDER BY s.section_name";
    $sectionstmt = $conn->prepare($sectionquery);
    $sectionstmt->bind_param("i", $classId);
    $sectionstmt->execute();
    $sectionresult = $sectionstmt->get_result();
    while ($row = $sectionresult->fetch_assoc()) {
        $sections[] = $row;
    }
    $sectionstmt->close();

    // Build WHERE clause for sections
    $sectionWhere = "";
    $sectionParams = [];
    $sectionTypes = "";
    
    if ($selected_sections !== 'all' && !empty($selected_sections)) {
        // Create placeholders for multiple sections
        $placeholders = str_repeat('?,', count($selected_sections) - 1) . '?';
        $sectionWhere = " AND m.section_id IN ($placeholders)";
        $sectionParams = $selected_sections;
        $sectionTypes = str_repeat('i', count($selected_sections));
    } else {
        // Get all section IDs for this class
        $allSectionIds = array_column($sections, 'section_id');
        if (!empty($allSectionIds)) {
            $placeholders = str_repeat('?,', count($allSectionIds) - 1) . '?';
            $sectionWhere = " AND m.section_id IN ($placeholders)";
            $sectionParams = $allSectionIds;
            $sectionTypes = str_repeat('i', count($allSectionIds));
        }
    }

    // Query 1: Get all students who have marks <= 0 or absent
    $query1 = "SELECT 
                s.student_id, 
                s.name AS student_name,
                s.symbol_no,
                s.section as student_section,
                sec.section_name,
                sub.subject_code, 
                sub.subject_name, 
                m.marks,
                m.mark_type,
                m.full_marks as exam_full_marks,
                sub.theory_full_marks
              FROM marks m
              INNER JOIN students s ON m.student_id = s.student_id
              INNER JOIN subjects sub ON m.subject_id = sub.id
              LEFT JOIN sections sec ON m.section_id = sec.section_id
              WHERE m.class_id = ? 
                AND m.exam_type = ?
                AND m.mark_type = 'theory'
                AND (m.marks <= 0 OR m.marks IS NULL)";

    // Add section condition if we have sections to filter
    if ($sectionWhere) {
        $query1 .= $sectionWhere;
    }
    
    $query1 .= " ORDER BY sec.section_name, s.name, sub.subject_code";

    // Prepare and execute query 1
    $stmt1 = $conn->prepare($query1);
    
    if (!empty($sectionParams)) {
        $allParams = array_merge([$classId, $examId], $sectionParams);
        $allTypes = "ii" . $sectionTypes;
        $stmt1->bind_param($allTypes, ...$allParams);
    } else {
        $stmt1->bind_param("ii", $classId, $examId);
    }
    
    $stmt1->execute();
    $result1 = $stmt1->get_result();

    // Query 2: Get all students in class who don't have marks data for this exam
    $query2 = "SELECT 
                s.student_id, 
                s.name AS student_name,
                s.symbol_no,
                s.section as student_section,
                sec.section_name
              FROM students s
              INNER JOIN class_section cs ON s.section = cs.section_id
              LEFT JOIN sections sec ON s.section = sec.section_id
              WHERE cs.class_id = ? 
                AND s.status = 1";

    // Add section filter for query 2
    if ($sectionWhere) {
        $query2 .= " AND s.section IN (" . str_repeat('?,', count($sectionParams) - 1) . "?)";
    }
    
    $query2 .= " AND s.student_id NOT IN (
                    SELECT DISTINCT student_id 
                    FROM marks 
                    WHERE class_id = ? 
                    AND exam_type = ?
                    AND mark_type = 'theory'
                )";
    
    $query2 .= " ORDER BY sec.section_name, s.name";

    // Prepare and execute query 2
    $stmt2 = $conn->prepare($query2);
    
    if (!empty($sectionParams)) {
        $allParams2 = array_merge([$classId], $sectionParams, [$classId, $examId]);
        $allTypes2 = "i" . $sectionTypes . "ii";
        $stmt2->bind_param($allTypes2, ...$allParams2);
    } else {
        $stmt2->bind_param("iii", $classId, $classId, $examId);
    }
    
    $stmt2->execute();
    $result2 = $stmt2->get_result();

    // Process results based on grouping
    if ($group_by == 'student') {
        // Group by student
        $zero_marks_data = [];
        
        // Process students with marks <= 0
        while ($row = $result1->fetch_assoc()) {
            $studentId = $row['student_id'];
            $sectionName = $row['section_name'] ?? $row['student_section'];
            
            if (!isset($zero_marks_data[$studentId])) {
                $zero_marks_data[$studentId] = [
                    'student_id' => $studentId,
                    'name' => $row['student_name'],
                    'symbol' => $row['symbol_no'],
                    'section' => $sectionName,
                    'zero_marks_subjects' => [],
                    'total_subjects' => 0,
                    'no_data' => false
                ];
            }
            
            $zero_marks_data[$studentId]['zero_marks_subjects'][] = [
                'subject_code' => $row['subject_code'],
                'subject_name' => $row['subject_name'],
                'marks' => $row['marks'],
                'full_marks' => $row['exam_full_marks'] > 0 ? $row['exam_full_marks'] : $row['theory_full_marks']
            ];
            $zero_marks_data[$studentId]['total_subjects']++;
        }
        
        // Process students with no marks data
        while ($row = $result2->fetch_assoc()) {
            $studentId = $row['student_id'];
            $sectionName = $row['section_name'] ?? $row['student_section'];
            
            $zero_marks_data[$studentId] = [
                'student_id' => $studentId,
                'name' => $row['student_name'],
                'symbol' => $row['symbol_no'],
                'section' => $sectionName,
                'zero_marks_subjects' => [],
                'total_subjects' => 0,
                'no_data' => true
            ];
        }
        
        // Convert to indexed array for display
        $zero_marks_data = array_values($zero_marks_data);
        
    } else {
        // Group by subject
        $zero_marks_data = [];
        
        // Process students with marks <= 0
        while ($row = $result1->fetch_assoc()) {
            $subjectCode = $row['subject_code'];
            $subjectName = $row['subject_name'];
            $key = $subjectCode . '|' . $subjectName;
            
            if (!isset($zero_marks_data[$key])) {
                $zero_marks_data[$key] = [
                    'subject_code' => $subjectCode,
                    'subject_name' => $subjectName,
                    'students' => [],
                    'total_students' => 0,
                    'section_wise' => []
                ];
            }
            
            $sectionName = $row['section_name'] ?? $row['student_section'];
            
            // Add student to subject
            $zero_marks_data[$key]['students'][] = [
                'student_id' => $row['student_id'],
                'name' => $row['student_name'],
                'symbol' => $row['symbol_no'],
                'section' => $sectionName,
                'marks' => $row['marks']
            ];
            $zero_marks_data[$key]['total_students']++;
            
            // Track section-wise count
            if (!isset($zero_marks_data[$key]['section_wise'][$sectionName])) {
                $zero_marks_data[$key]['section_wise'][$sectionName] = 0;
            }
            $zero_marks_data[$key]['section_wise'][$sectionName]++;
        }
        
        // Convert to indexed array for display
        $zero_marks_data = array_values($zero_marks_data);
    }
    
    $stmt1->close();
    $stmt2->close();
}

// Get display section names
$displaySections = [];
if (isset($selected_sections) && $selected_sections === 'all' && !empty($sections)) {
    $displaySections = array_column($sections, 'section_name');
} elseif (isset($selected_sections) && is_array($selected_sections)) {
    foreach ($sections as $section) {
        if (in_array($section['section_id'], $selected_sections)) {
            $displaySections[] = $section['section_name'];
        }
    }
}

// Prepare section display text
if (empty($displaySections)) {
    $sectionDisplayText = "All Sections";
} elseif (count($displaySections) === 1) {
    $sectionDisplayText = $displaySections[0];
} elseif (count($displaySections) <= 3) {
    $sectionDisplayText = implode(", ", $displaySections);
} else {
    $sectionDisplayText = count($displaySections) . " Sections Selected";
}

// Get school information (if available in your database)
$schoolName = "School Name";
$schoolAddress = "School Address";
$schoolPhone = "Phone: (123) 456-7890";
$schoolEmail = "info@school.edu";

// Try to fetch school info from database if you have a settings table
$settingsQuery = "SELECT * FROM schools WHERE id = 1";
$settingsResult = $conn->query($settingsQuery);
if ($settingsResult && $settingsResult->num_rows > 0) {
    $settings = $settingsResult->fetch_assoc();
    $schoolName = $settings['school_name'] ?? $schoolName;
    $schoolAddress = $settings['school_address'] ?? $schoolAddress;
    $schoolPhone = $settings['school_phone'] ?? $schoolPhone;
    $schoolEmail = $settings['school_email'] ?? $schoolEmail;
}
?>

<!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 - Zero Marks/Absent Students Report</title>
    <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/prism/prism.css" media="screen">
    <link rel="stylesheet" href="css/select2/select2.min.css">
    <link rel="stylesheet" href="css/main.css" media="screen">
    <script src="js/modernizr/modernizr.min.js"></script>
    <script src="https://cdn.datatables.net/1.11.5/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.datatables.net/1.11.5/js/dataTables.bootstrap5.min.js"></script>
    <link rel="stylesheet" href="https://cdn.datatables.net/1.11.5/css/dataTables.bootstrap5.min.css">
    <script src="https://cdn.jsdelivr.net/npm/xlsx@0.18.5/dist/xlsx.full.min.js"></script>
    <style>
        /* Print-specific styles */
        @media print {
            @page {
                size: A4 portrait;
                margin: 0.5in;
            }
            
            body {
                font-family: 'Times New Roman', Times, serif;
                font-size: 12pt;
                line-height: 1.4;
                color: #000;
                background: white;
                margin: 0;
                padding: 0;
            }
            
            .no-print, 
            .no-print * {
                display: none !important;
            }
            
            .print-only {
                display: block !important;
            }
            
            .container-fluid {
                width: 100% !important;
                padding: 0 !important;
                margin: 0 !important;
            }
            
            .panel, .panel-heading, .panel-body, .panel-title {
                border: none !important;
                box-shadow: none !important;
                padding: 0 !important;
                margin: 0 !important;
            }
            
            /* School Header */
            .school-header {
                text-align: center;
                border-bottom: 2px solid #000;
                padding-bottom: 10px;
                margin-bottom: 20px;
            }
            
            .school-name {
                font-size: 24pt;
                font-weight: bold;
                text-transform: uppercase;
                letter-spacing: 1px;
                margin-bottom: 5px;
            }
            
            .school-address {
                font-size: 11pt;
                margin-bottom: 3px;
            }
            
            .report-title {
                text-align: center;
                margin: 30px 0 20px 0;
                font-size: 18pt;
                font-weight: bold;
                text-decoration: underline;
                text-transform: uppercase;
            }
            
            .exam-details {
                text-align: center;
                margin-bottom: 25px;
                font-size: 12pt;
                border: 1px solid #000;
                padding: 10px;
                background-color: #f9f9f9;
            }
            
            /* Main report table */
            .report-table {
                width: 100%;
                border-collapse: collapse;
                margin-bottom: 30px;
                page-break-inside: auto;
            }
            
            .report-table th {
                background-color: #f2f2f2 !important;
                color: #000 !important;
                font-weight: bold;
                border: 1px solid #000 !important;
                padding: 8px 5px;
                text-align: center;
                font-size: 11pt;
                -webkit-print-color-adjust: exact;
            }
            
            .report-table td {
                border: 1px solid #000 !important;
                padding: 6px 5px;
                text-align: left;
                font-size: 10pt;
                vertical-align: top;
            }
            
            .section-header-row {
                background-color: #e8e8e8 !important;
                font-weight: bold;
                -webkit-print-color-adjust: exact;
            }
            
            .section-header-row td {
                font-weight: bold;
                font-size: 11pt;
                padding: 8px 5px;
            }
            
            .absent-row {
                background-color: #fff0f0 !important;
                -webkit-print-color-adjust: exact;
            }
            
            .no-data-row {
                background-color: #fff8e8 !important;
                -webkit-print-color-adjust: exact;
            }
            
            .subject-details {
                font-size: 9.5pt;
                line-height: 1.3;
            }
            
            .subject-item {
                margin-bottom: 3px;
                padding-bottom: 3px;
            }
            
            .absent-text {
                color: #c00;
                font-weight: bold;
            }
            
            .no-data-text {
                color: #e67e00;
                font-weight: bold;
            }
            
            /* Summary section */
            .summary-section {
                margin-top: 40px;
                padding: 15px;
                border: 1px solid #000;
                background-color: #f9f9f9;
                page-break-inside: avoid;
            }
            
            .summary-title {
                font-weight: bold;
                font-size: 12pt;
                margin-bottom: 10px;
                text-align: center;
                text-decoration: underline;
            }
            
            .summary-grid {
                display: grid;
                grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
                gap: 15px;
            }
            
            .summary-item {
                text-align: center;
            }
            
            .summary-value {
                font-size: 14pt;
                font-weight: bold;
                color: #000;
            }
            
            .summary-label {
                font-size: 10pt;
                color: #666;
            }
            
            /* Signature section */
            .signature-section {
                margin-top: 60px;
                page-break-inside: avoid;
            }
            
            .signature-line {
                display: flex;
                justify-content: space-between;
                margin-top: 50px;
            }
            
            .signature-box {
                text-align: center;
                width: 200px;
                border-top: 1px solid #000;
                padding-top: 10px;
            }
            
            .signature-name {
                font-weight: bold;
                margin-top: 5px;
            }
            
            .signature-title {
                font-size: 10pt;
                color: #666;
            }
            
            /* Footer */
            .print-footer {
                margin-top: 40px;
                text-align: center;
                font-size: 10pt;
                color: #666;
                border-top: 1px solid #ccc;
                padding-top: 10px;
            }
            
            .print-date {
                float: right;
                font-size: 10pt;
                margin-top: 10px;
            }
            
            /* Page break control */
            .page-break {
                page-break-before: always;
            }
            
            /* Force no background images/colors for print */
            * {
                -webkit-print-color-adjust: exact !important;
                print-color-adjust: exact !important;
            }
            
            /* Hide unnecessary elements in print */
            .stats-card, .section-badge, .selected-sections-display,
            .alert, .breadcrumb, .page-title-div {
                display: none !important;
            }
        }
        
        /* Screen styles */
        @media screen {
            #zeroMarksTable {
                border-collapse: collapse;
                width: 100%;
                margin-bottom: 10px;
            }
            
            #zeroMarksTable th, #zeroMarksTable td {
                border: 1px solid #ddd;
                padding: 8px;
                text-align: center;
                font-size: 12px;
            }
            
            #zeroMarksTable th {
                background-color: #f2f2f2;
                font-weight: bold;
            }
            
            .no-data-row {
                background-color: #ffebee !important;
            }
            
            .zero-marks-row {
                background-color: #fff3e0 !important;
            }
            
            .absent-cell {
                color: #d32f2f;
                font-weight: bold;
            }
            
            .no-data-cell {
                color: #f57c00;
                font-weight: bold;
            }
            
            .section-header {
                background-color: #e3f2fd !important;
                font-weight: bold;
                text-align: left !important;
            }
            
            .stats-card {
                background: #f8f9fa;
                border: 1px solid #dee2e6;
                border-radius: 5px;
                padding: 15px;
                margin-bottom: 20px;
            }
            
            .stat-item {
                display: inline-block;
                margin-right: 20px;
                margin-bottom: 10px;
            }
            
            .stat-value {
                font-size: 24px;
                font-weight: bold;
                color: #007bff;
            }
            
            .stat-label {
                font-size: 14px;
                color: #6c757d;
            }
            
            .section-badge {
                display: inline-block;
                background-color: #007bff;
                color: white;
                padding: 3px 10px;
                border-radius: 15px;
                font-size: 12px;
                margin: 2px;
                font-weight: 500;
            }
            
            .selected-sections-display {
                background-color: #f8f9fa;
                border: 1px solid #dee2e6;
                border-radius: 5px;
                padding: 10px;
                margin-top: 10px;
            }
            
            .badge-absent {
                background-color: #dc3545;
                color: white;
                padding: 2px 6px;
                border-radius: 10px;
                font-size: 11px;
            }
            
            .badge-no-data {
                background-color: #fd7e14;
                color: white;
                padding: 2px 6px;
                border-radius: 10px;
                font-size: 11px;
            }
            
            .print-only {
                display: none;
            }
        }
    </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'); ?>
                
                <div class="main-page">
                    <div class="container-fluid">
                        <div class="row page-title-div">
                            <div class="col-md-6">
                                <h2 class="title">Zero Marks/Absent Students Report</h2>
                            </div>
                        </div>
                        
                        <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="">Zero Marks Report</li>
                                </ul>
                            </div>
                        </div>
                    </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>Report for Students with Zero Marks/Absent/No Data</h5>
                                        </div>
                                    </div>
                                    <div class="panel-body">
                                        <div class="container no-print">
                                            <form action="absent_report.php" method="get" id="zeroMarksForm">
                                                <div class="row">
                                                    <div class="col-md-3">
                                                        <div class="form-group">
                                                            <label for="exam_id">Select Exam:</label>
                                                            <select id="exam_id" name="exam_id" class="form-control select2" required>
                                                                <option value="">Select Exam</option>
                                                                <?php
                                                                // Fetch exams from examination_type table
                                                                $queryexam = "SELECT id, exm_year, exam_type FROM examination_type ORDER BY exm_year DESC, id DESC";
                                                                $resultexam = $conn->query($queryexam);
                                                                
                                                                while ($row = $resultexam->fetch_assoc()) {
                                                                    $selected = (isset($_GET['exam_id']) && $_GET['exam_id'] == $row['id']) ? 'selected' : '';
                                                                    echo "<option value='" . $row['id'] . "' $selected>" . 
                                                                         htmlspecialchars($row['exam_type'] . " - " . $row['exm_year']) . "</option>";
                                                                }
                                                                ?>
                                                            </select>
                                                        </div>
                                                    </div>
                                                    
                                                    <div class="col-md-2">
                                                        <div class="form-group">
                                                            <label for="class_id">Select Class:</label>
                                                            <select name="class_id" id="class_id" class="form-control select2" onchange="loadSections(this.value)">
                                                                <option value="">Select Class</option>
                                                                <?php
                                                                // Query classes from the database
                                                                $classQuery = "SELECT DISTINCT c.class_id, c.class 
                                                                              FROM classes c
                                                                              INNER JOIN class_section cs ON c.class_id = cs.class_id
                                                                              WHERE c.status = 1
                                                                              ORDER BY c.class_numeric";
                                                                $classResult = $conn->query($classQuery);
                                                                
                                                                while ($row = $classResult->fetch_assoc()) {
                                                                    $selected = (isset($_GET['class_id']) && $_GET['class_id'] == $row['class_id']) ? 'selected' : '';
                                                                    echo "<option value='" . $row['class_id'] . "' $selected>" . 
                                                                         htmlspecialchars($row['class']) . "</option>";
                                                                }
                                                                ?>
                                                            </select>
                                                        </div>
                                                    </div>
                                                    
                                                    <div class="col-md-2">
                                                        <div class="form-group">
                                                            <label for="section_id">Select Sections:</label>
                                                            <select name="section_id[]" id="section_id" class="form-control select2" multiple="multiple">
                                                                <option value="all">All Sections</option>
                                                                <?php
                                                                if (isset($_GET['class_id']) && !empty($sections)) {
                                                                    foreach ($sections as $section) {
                                                                        $selected = '';
                                                                        if (isset($_GET['section_id'])) {
                                                                            if (is_array($_GET['section_id'])) {
                                                                                $selected = in_array($section['section_id'], $_GET['section_id']) ? 'selected' : '';
                                                                            } else {
                                                                                $selected = ($_GET['section_id'] == $section['section_id']) ? 'selected' : '';
                                                                            }
                                                                        }
                                                                        echo "<option value='" . $section['section_id'] . "' $selected>" . 
                                                                             htmlspecialchars($section['section_name']) . "</option>";
                                                                    }
                                                                }
                                                                ?>
                                                            </select>
                                                        </div>
                                                    </div>
                                                    
                                                    <div class="col-md-2">
                                                        <div class="form-group">
                                                            <label for="group_by">Group By:</label>
                                                            <select name="group_by" id="group_by" class="form-control">
                                                                <option value="student" <?= (isset($_GET['group_by']) && $_GET['group_by'] == 'student') ? 'selected' : '' ?>>By Student</option>
                                                                <option value="subject" <?= (isset($_GET['group_by']) && $_GET['group_by'] == 'subject') ? 'selected' : '' ?>>By Subject</option>
                                                            </select>
                                                        </div>
                                                    </div>
                                                    
                                                    <div class="col-md-3">
                                                        <div class="form-group" style="padding-top: 28px;">
                                                            <button type="submit" class="btn btn-primary">
                                                                <i class="fa fa-search"></i> Generate Report
                                                            </button>
                                                            <button type="button" onclick="resetForm()" class="btn btn-default">
                                                                <i class="fa fa-refresh"></i> Reset
                                                            </button>
                                                            <button type="button" onclick="printReport()" class="btn btn-success no-print">
                                                                <i class="fa fa-print"></i> Print Official Report
                                                            </button>
                                                        </div>
                                                    </div>
                                                </div>
                                                <div class="row">
                                                    <div class="col-md-12">
                                                        <div id="selectedSectionsDisplay" class="selected-sections-display" style="display: none;">
                                                            <strong>Selected Sections:</strong>
                                                            <div id="selectedSectionsList"></div>
                                                        </div>
                                                    </div>
                                                </div>
                                            </form>
                                        </div>
                                        
                                        <?php if (isset($zero_marks_data) && !empty($zero_marks_data)) : ?>
                                        <?php 
                                        // Calculate statistics
                                        $totalStudents = 0;
                                        $totalZeroMarks = 0;
                                        $totalNoData = 0;
                                        $totalSubjects = 0;
                                        
                                        if ($group_by == 'student') {
                                            $totalStudents = count($zero_marks_data);
                                            foreach ($zero_marks_data as $student) {
                                                if ($student['no_data']) {
                                                    $totalNoData++;
                                                } else {
                                                    $totalZeroMarks++;
                                                    $totalSubjects += count($student['zero_marks_subjects']);
                                                }
                                            }
                                        } else {
                                            $totalSubjects = count($zero_marks_data);
                                            foreach ($zero_marks_data as $subject) {
                                                $totalStudents += $subject['total_students'];
                                            }
                                        }
                                        
                                        // Current date for report
                                        $currentDate = date('F d, Y');
                                        ?>
                                        
                                        <!-- =========================================== -->
                                        <!-- PRINT VERSION (Hidden on screen) -->
                                        <!-- =========================================== -->
                                        <div class="print-only" id="printReport">
                                            <!-- School Header -->
                                            <div class="school-header">
                                                <div class="school-name"><?php echo htmlspecialchars($schoolName); ?></div>
                                                <div class="school-address"><?php echo htmlspecialchars($schoolAddress); ?></div>
                                                <div class="school-address"><?php echo htmlspecialchars($schoolPhone); ?> | <?php echo htmlspecialchars($schoolEmail); ?></div>
                                            </div>
                                            
                                            <!-- Report Title -->
                                            <div class="report-title">
                                                Absent/Zero Marks Students Report
                                            </div>
                                            
                                            <!-- Exam Details -->
                                            <div class="exam-details">
                                                <strong>Class:</strong> <?php echo htmlspecialchars($legclass); ?> 
                                                | <strong>Exam:</strong> <?php echo htmlspecialchars($examtype . " (" . $examyear . ")"); ?>
                                                <?php if (!empty($displaySections)): ?>
                                                | <strong>Section(s):</strong> <?php echo htmlspecialchars(implode(", ", $displaySections)); ?>
                                                <?php endif; ?>
                                                | <strong>Generated On:</strong> <?php echo $currentDate; ?>
                                            </div>
                                            
                                            <?php if ($group_by == 'student'): ?>
                                            <!-- Report Table for Student Grouping -->
                                            <table class="report-table">
                                                <thead>
                                                    <tr>
                                                        <th style="width: 5%;">S.N.</th>
                                                        <th style="width: 25%;">Student Name</th>
                                                        <th style="width: 10%;">Symbol No</th>
                                                        <th style="width: 10%;">Section</th>
                                                        <th style="width: 40%;">Subjects with Zero/Absent Marks</th>
                                                        <th style="width: 10%;">Status</th>
                                                    </tr>
                                                </thead>
                                                <tbody>
                                                    <?php 
                                                    $currentSection = '';
                                                    $sn = 1;
                                                    foreach ($zero_marks_data as $student): 
                                                        // Add section header if section changes
                                                        if ($currentSection !== $student['section']) {
                                                            $currentSection = $student['section'];
                                                            echo '<tr class="section-header-row">';
                                                            echo '<td colspan="6">';
                                                            echo '<strong>Section: ' . htmlspecialchars($currentSection) . '</strong>';
                                                            echo '</td>';
                                                            echo '</tr>';
                                                        }
                                                        
                                                        $rowClass = $student['no_data'] ? 'no-data-row' : 'absent-row';
                                                    ?>
                                                    <tr class="<?php echo $rowClass; ?>">
                                                        <td style="text-align: center;"><?php echo $sn++; ?></td>
                                                        <td><?php echo htmlspecialchars($student['name']); ?></td>
                                                        <td style="text-align: center;"><?php echo htmlspecialchars($student['symbol']); ?></td>
                                                        <td style="text-align: center;"><?php echo htmlspecialchars($student['section']); ?></td>
                                                        <td>
                                                            <?php if ($student['no_data']): ?>
                                                                <span class="no-data-text">NO MARKS DATA FOUND</span>
                                                            <?php else: ?>
                                                                <div class="subject-details">
                                                                    <?php foreach ($student['zero_marks_subjects'] as $subject): ?>
                                                                    <div class="subject-item">
                                                                        <strong><?php echo htmlspecialchars($subject['subject_name']); ?></strong> 
                                                                        (<?php echo htmlspecialchars($subject['subject_code']); ?>) - 
                                                                        <?php 
                                                                        if ($subject['marks'] == 0) {
                                                                            echo '<span class="absent-text">Absent (0/' . $subject['full_marks'] . ')</span>';
                                                                        } elseif ($subject['marks'] < 0) {
                                                                            echo '<span class="absent-text">' . $subject['marks'] . '/' . $subject['full_marks'] . '</span>';
                                                                        } else {
                                                                            echo '<span class="absent-text">' . $subject['marks'] . '/' . $subject['full_marks'] . '</span>';
                                                                        }
                                                                        ?>
                                                                    </div>
                                                                    <?php endforeach; ?>
                                                                </div>
                                                            <?php endif; ?>
                                                        </td>
                                                        <td style="text-align: center;">
                                                            <?php if ($student['no_data']): ?>
                                                                No Data
                                                            <?php else: ?>
                                                                Absent
                                                            <?php endif; ?>
                                                        </td>
                                                    </tr>
                                                    <?php endforeach; ?>
                                                </tbody>
                                            </table>
                                            <?php else: ?>
                                            <!-- Report Table for Subject Grouping -->
                                            <table class="report-table">
                                                <thead>
                                                    <tr>
                                                        <th style="width: 5%;">S.N.</th>
                                                        <th style="width: 15%;">Subject Code</th>
                                                        <th style="width: 30%;">Subject Name</th>
                                                        <th style="width: 25%;">Total Absent Students</th>
                                                        <th style="width: 25%;">Section-wise Distribution</th>
                                                    </tr>
                                                </thead>
                                                <tbody>
                                                    <?php $sn = 1; ?>
                                                    <?php foreach ($zero_marks_data as $subject): ?>
                                                    <tr>
                                                        <td style="text-align: center;"><?php echo $sn++; ?></td>
                                                        <td style="text-align: center;"><?php echo htmlspecialchars($subject['subject_code']); ?></td>
                                                        <td><?php echo htmlspecialchars($subject['subject_name']); ?></td>
                                                        <td style="text-align: center;">
                                                            <strong><?php echo $subject['total_students']; ?> Students</strong>
                                                        </td>
                                                        <td>
                                                            <?php if (!empty($subject['section_wise'])): ?>
                                                            <div class="subject-details">
                                                                <?php foreach ($subject['section_wise'] as $sectionName => $count): ?>
                                                                <div class="subject-item">
                                                                    <?php echo htmlspecialchars($sectionName); ?>: <?php echo $count; ?> students
                                                                </div>
                                                                <?php endforeach; ?>
                                                            </div>
                                                            <?php endif; ?>
                                                        </td>
                                                    </tr>
                                                    <?php endforeach; ?>
                                                </tbody>
                                            </table>
                                            <?php endif; ?>
                                            
                                            <!-- Summary Section -->
                                         <!--    <div class="summary-section no-print">
                                                <div class="summary-title">REPORT SUMMARY</div>
                                                <div class="summary-grid">
                                                    <?php if ($group_by == 'student'): ?>
                                                    <div class="summary-item">
                                                        <div class="summary-value"><?php echo $totalStudents; ?></div>
                                                        <div class="summary-label">Total Students</div>
                                                    </div>
                                                    <div class="summary-item">
                                                        <div class="summary-value"><?php echo $totalZeroMarks; ?></div>
                                                        <div class="summary-label">Students Absent/Zero Marks</div>
                                                    </div>
                                                    <div class="summary-item">
                                                        <div class="summary-value"><?php echo $totalNoData; ?></div>
                                                        <div class="summary-label">Students with No Data</div>
                                                    </div>
                                                    <div class="summary-item">
                                                        <div class="summary-value"><?php echo $totalSubjects; ?></div>
                                                        <div class="summary-label">Total Subjects Affected</div>
                                                    </div>
                                                    <?php else: ?>
                                                    <div class="summary-item">
                                                        <div class="summary-value"><?php echo $totalSubjects; ?></div>
                                                        <div class="summary-label">Subjects with Zero Marks</div>
                                                    </div>
                                                    <div class="summary-item">
                                                        <div class="summary-value"><?php echo $totalStudents; ?></div>
                                                        <div class="summary-label">Total Students Absent</div>
                                                    </div>
                                                    <?php endif; ?>
                                                </div>
                                            </div> -->
                                            
                                            <!-- Signature Section -->
                                            <div class="signature-section">
                                                <div class="signature-line">
                                                    <div class="signature-box">
                                                        <div class="signature-name">___________________________</div>
                                                        <div class="signature-title">Class Teacher</div>
                                                    </div>
                                                    <div class="signature-box">
                                                        <div class="signature-name">___________________________</div>
                                                        <div class="signature-title">Exam Coordinator</div>
                                                    </div>
                                                    <div class="signature-box">
                                                        <div class="signature-name">___________________________</div>
                                                        <div class="signature-title">Principal</div>
                                                    </div>
                                                </div>
                                            </div>
                                            
                                            <!-- Footer -->
                                            <div class="print-footer">
                                                <div class="print-date">Generated on: <?php echo $currentDate; ?></div>
                                                <div>Official Report - <?php echo htmlspecialchars($schoolName); ?></div>
                                                <div>Page 1 of 1</div>
                                            </div>
                                        </div>
                                        <!-- =========================================== -->
                                        <!-- END PRINT VERSION -->
                                        <!-- =========================================== -->
                                        
                                        <!-- Screen Display Version -->
                                        <div class="no-print mt-4">
                                            <div class="stats-card">
                                                <div class="row">
                                                    <div class="col-md-12">
                                                        <h4>
                                                            Zero Marks/Absent Students Report for <?php echo htmlspecialchars($legclass); ?> 
                                                            <?php if (!empty($displaySections)): ?>
                                                            - 
                                                            <?php foreach ($displaySections as $section): ?>
                                                            <span class="section-badge"><?php echo htmlspecialchars($section); ?></span>
                                                            <?php endforeach; ?>
                                                            <?php endif; ?>
                                                            in <?php echo htmlspecialchars($examtype . " (" . $examyear . ")"); ?>
                                                        </h4>
                                                    </div>
                                                </div>
                                                <div class="row">
                                                    <?php if ($group_by == 'student'): ?>
                                                    <div class="col-md-2">
                                                        <div class="stat-item">
                                                            <div class="stat-value"><?php echo $totalStudents; ?></div>
                                                            <div class="stat-label">Total Students</div>
                                                        </div>
                                                    </div>
                                                    <div class="col-md-2">
                                                        <div class="stat-item">
                                                            <div class="stat-value"><?php echo $totalZeroMarks; ?></div>
                                                            <div class="stat-label">Students with Zero/Absent</div>
                                                        </div>
                                                    </div>
                                                    <div class="col-md-2">
                                                        <div class="stat-item">
                                                            <div class="stat-value"><?php echo $totalNoData; ?></div>
                                                            <div class="stat-label">Students with No Data</div>
                                                        </div>
                                                    </div>
                                                    <div class="col-md-3">
                                                        <div class="stat-item">
                                                            <div class="stat-value"><?php echo $totalSubjects; ?></div>
                                                            <div class="stat-label">Total Subjects with Zero Marks</div>
                                                        </div>
                                                    </div>
                                                    <?php else: ?>
                                                    <div class="col-md-2">
                                                        <div class="stat-item">
                                                            <div class="stat-value"><?php echo $totalSubjects; ?></div>
                                                            <div class="stat-label">Subjects with Zero Marks</div>
                                                        </div>
                                                    </div>
                                                    <div class="col-md-3">
                                                        <div class="stat-item">
                                                            <div class="stat-value"><?php echo $totalStudents; ?></div>
                                                            <div class="stat-label">Total Students with Zero Marks</div>
                                                        </div>
                                                    </div>
                                                    <?php endif; ?>
                                                </div>
                                            </div>
                                            
                                            <div class="mb-3">
                                                <button onclick="printReport()" class="btn btn-primary">
                                                    <i class="fa fa-print"></i> Print Official Report
                                                </button>
                                                <button onclick="exportToExcel()" class="btn btn-success">
                                                    <i class="fa fa-file-excel-o"></i> Export to Excel
                                                </button>
                                            </div>
                                            
                                            <!-- Main Report Table for Screen -->
                                            <table id="zeroMarksTable" class="table table-bordered">
                                                <thead>
                                                    <tr>
                                                        <td colspan="<?php echo ($group_by == 'student') ? '6' : '5'; ?>" style="border:none;font-size: 18px; text-align: center; background-color: #f8f9fa;">
                                                            <b><u>Zero Marks/Absent Students Report</u></b><br>
                                                            <small>
                                                                <?php echo htmlspecialchars($legclass); ?> | 
                                                                <?php echo htmlspecialchars($examtype . " (" . $examyear . ")"); ?> | 
                                                                <?php echo htmlspecialchars($sectionDisplayText); ?>
                                                            </small>
                                                        </td>
                                                    </tr>
                                                    <?php if ($group_by == 'student'): ?>
                                                    <tr>
                                                        <th>S.N.</th>
                                                        <th>Student Name</th>
                                                        <th>Symbol No</th>
                                                        <th>Section</th>
                                                        <th>Subjects with Zero/Absent Marks</th>
                                                        <th>Status</th>
                                                    </tr>
                                                    <?php else: ?>
                                                    <tr>
                                                        <th>S.N.</th>
                                                        <th>Subject Code</th>
                                                        <th>Subject Name</th>
                                                        <th>Total Students with Zero/Absent</th>
                                                        <th>Section-wise Distribution</th>
                                                    </tr>
                                                    <?php endif; ?>
                                                </thead>
                                                <tbody>
                                                    <?php if ($group_by == 'student'): ?>
                                                        <?php 
                                                        $currentSection = '';
                                                        $sn = 1;
                                                        foreach ($zero_marks_data as $student): 
                                                            // Add section header if section changes
                                                            if ($currentSection !== $student['section']) {
                                                                $currentSection = $student['section'];
                                                                echo '<tr class="section-header">';
                                                                echo '<td colspan="6">';
                                                                echo '<strong>Section: ' . htmlspecialchars($currentSection) . '</strong>';
                                                                echo '</td>';
                                                                echo '</tr>';
                                                            }
                                                            
                                                            $rowClass = $student['no_data'] ? 'no-data-row' : 'zero-marks-row';
                                                        ?>
                                                        <tr class="<?php echo $rowClass; ?>">
                                                            <td><?php echo $sn++; ?></td>
                                                            <td><?php echo htmlspecialchars($student['name']); ?></td>
                                                            <td><?php echo htmlspecialchars($student['symbol']); ?></td>
                                                            <td><?php echo htmlspecialchars($student['section']); ?></td>
                                                            <td>
                                                                <?php if ($student['no_data']): ?>
                                                                    <span class="no-data-cell">NO MARKS DATA FOUND</span>
                                                                <?php else: ?>
                                                                    <table style="width: 100%; border: none;">
                                                                        <?php foreach ($student['zero_marks_subjects'] as $subject): ?>
                                                                        <tr>
                                                                            <td style="text-align: left; border: none; padding: 2px;">
                                                                                <?php echo htmlspecialchars($subject['subject_name']); ?> 
                                                                                (<?php echo htmlspecialchars($subject['subject_code']); ?>)
                                                                            </td>
                                                                            <td style="text-align: right; border: none; padding: 2px; width: 80px;">
                                                                                <?php 
                                                                                if ($subject['marks'] == 0) {
                                                                                    echo '<span class="absent-cell">Absent (0/' . $subject['full_marks'] . ')</span>';
                                                                                } elseif ($subject['marks'] < 0) {
                                                                                    echo '<span class="absent-cell">' . $subject['marks'] . '/' . $subject['full_marks'] . '</span>';
                                                                                } else {
                                                                                    echo '<span class="absent-cell">' . $subject['marks'] . '/' . $subject['full_marks'] . '</span>';
                                                                                }
                                                                                ?>
                                                                            </td>
                                                                        </tr>
                                                                        <?php endforeach; ?>
                                                                    </table>
                                                                <?php endif; ?>
                                                            </td>
                                                            <td>
                                                                <?php if ($student['no_data']): ?>
                                                                    <span class="badge badge-no-data">No Data</span>
                                                                <?php else: ?>
                                                                    <span class="badge badge-absent">Zero/Absent</span>
                                                                <?php endif; ?>
                                                            </td>
                                                        </tr>
                                                        <?php endforeach; ?>
                                                    <?php else: ?>
                                                        <?php $sn = 1; ?>
                                                        <?php foreach ($zero_marks_data as $subject): ?>
                                                        <tr>
                                                            <td><?php echo $sn++; ?></td>
                                                            <td><?php echo htmlspecialchars($subject['subject_code']); ?></td>
                                                            <td><?php echo htmlspecialchars($subject['subject_name']); ?></td>
                                                            <td>
                                                                <strong><?php echo $subject['total_students']; ?> Students</strong>
                                                                <?php if (!empty($subject['students'])): ?>
                                                                <br>
                                                                <small>
                                                                    <a href="#" onclick="toggleStudentList(<?php echo $sn-2; ?>); return false;">
                                                                        View Students (<?php echo count($subject['students']); ?>)
                                                                    </a>
                                                                </small>
                                                                <div id="studentList_<?php echo $sn-2; ?>" style="display: none; margin-top: 10px;">
                                                                    <table class="table table-sm table-bordered" style="font-size: 11px;">
                                                                        <thead>
                                                                            <tr>
                                                                                <th>S.N.</th>
                                                                                <th>Student Name</th>
                                                                                <th>Symbol No</th>
                                                                                <th>Section</th>
                                                                                <th>Marks</th>
                                                                            </tr>
                                                                        </thead>
                                                                        <tbody>
                                                                            <?php $studentSn = 1; ?>
                                                                            <?php foreach ($subject['students'] as $student): ?>
                                                                            <tr>
                                                                                <td><?php echo $studentSn++; ?></td>
                                                                                <td><?php echo htmlspecialchars($student['name']); ?></td>
                                                                                <td><?php echo htmlspecialchars($student['symbol']); ?></td>
                                                                                <td><?php echo htmlspecialchars($student['section']); ?></td>
                                                                                <td class="absent-cell">
                                                                                    <?php 
                                                                                    if ($student['marks'] == 0) {
                                                                                        echo 'Absent (0)';
                                                                                    } else {
                                                                                        echo $student['marks'];
                                                                                    }
                                                                                    ?>
                                                                                </td>
                                                                            </tr>
                                                                            <?php endforeach; ?>
                                                                        </tbody>
                                                                    </table>
                                                                </div>
                                                                <?php endif; ?>
                                                            </td>
                                                            <td>
                                                                <?php if (!empty($subject['section_wise'])): ?>
                                                                <table style="width: 100%; border: none;">
                                                                    <?php foreach ($subject['section_wise'] as $sectionName => $count): ?>
                                                                    <tr>
                                                                        <td style="text-align: left; border: none; padding: 2px;">
                                                                            <?php echo htmlspecialchars($sectionName); ?>
                                                                        </td>
                                                                        <td style="text-align: right; border: none; padding: 2px;">
                                                                            <?php echo $count; ?> students
                                                                        </td>
                                                                    </tr>
                                                                    <?php endforeach; ?>
                                                                </table>
                                                                <?php endif; ?>
                                                            </td>
                                                        </tr>
                                                        <?php endforeach; ?>
                                                    <?php endif; ?>
                                                </tbody>
                                            </table>
                                            
                                            <?php if ($group_by == 'student'): ?>
                                            <!-- Summary Section -->
                                            <div class="mt-4 p-3" style="background-color: #f8f9fa; border-radius: 5px;">
                                                <h5>Summary:</h5>
                                                <div class="row">
                                                    <div class="col-md-4">
                                                        <strong>Total Students with Zero/Absent Marks:</strong> <?php echo $totalZeroMarks; ?>
                                                    </div>
                                                    <div class="col-md-4">
                                                        <strong>Total Students with No Data:</strong> <?php echo $totalNoData; ?>
                                                    </div>
                                                    <div class="col-md-4">
                                                        <strong>Total Subjects Affected:</strong> <?php echo $totalSubjects; ?>
                                                    </div>
                                                </div>
                                            </div>
                                            <?php endif; ?>
                                        </div>
                                        <?php elseif (isset($_GET['class_id']) && isset($_GET['exam_id'])) : ?>
                                        <div class="alert alert-success mt-4">
                                            <h4>No Zero Marks Found</h4>
                                            <p>All students have marks data and no zero/absent marks found for the selected criteria.</p>
                                        </div>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <!-- Scripts -->
    <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>
    <script src="js/prism/prism.js"></script>
    <script src="js/select2/select2.min.js"></script>
    <script src="js/main.js"></script>
    
    <script>
    $(document).ready(function() {
        // Initialize Select2 with multiple selection
        $('.select2').select2({
            placeholder: "Select options",
            allowClear: true
        });
        
        // Initialize section select2
        $('#section_id').select2({
            placeholder: "Select sections or choose 'All Sections'",
            allowClear: true,
            closeOnSelect: false
        });
        
        // Handle "All Sections" selection
        $('#section_id').on('select2:select', function (e) {
            var data = e.params.data;
            if (data.id === 'all') {
                // If "All Sections" is selected, clear other selections
                $('#section_id').val('all').trigger('change');
            } else {
                // If a specific section is selected, remove "All Sections" if it was selected
                var currentValues = $('#section_id').val();
                if (currentValues && currentValues.includes('all')) {
                    currentValues = currentValues.filter(function(value) {
                        return value !== 'all';
                    });
                    $('#section_id').val(currentValues).trigger('change');
                }
            }
            updateSelectedSectionsDisplay();
        });
        
        $('#section_id').on('select2:unselect', function (e) {
            updateSelectedSectionsDisplay();
        });
        
        // Load sections when class changes
        if ($('#class_id').val()) {
            loadSections($('#class_id').val());
        }
        
        // Update selected sections display
        updateSelectedSectionsDisplay();
    });
    
    function loadSections(classId) {
        if (!classId) {
            $('#section_id').html('<option value="all">All Sections</option>').val('all').trigger('change');
            updateSelectedSectionsDisplay();
            return;
        }
        
        $.ajax({
            url: 'ajax/get_sections_by_class.php',
            type: 'GET',
            data: { class_id: classId },
            dataType: 'json',
            success: function(sections) {
                let options = '<option value="all">All Sections</option>';
                if (sections && sections.length > 0) {
                    sections.forEach(function(section) {
                        // Check if this section was previously selected
                        let selected = '';
                        <?php if (isset($_GET['section_id'])): ?>
                        let previousSelections = <?php echo json_encode((array)$_GET['section_id']); ?>;
                        if (previousSelections && previousSelections.includes(section.section_id.toString())) {
                            selected = 'selected';
                        }
                        <?php endif; ?>
                        options += '<option value="' + section.section_id + '" ' + selected + '>' + section.section_name + '</option>';
                    });
                }
                $('#section_id').html(options).trigger('change');
                updateSelectedSectionsDisplay();
            },
            error: function() {
                $('#section_id').html('<option value="all">All Sections</option>').val('all').trigger('change');
                updateSelectedSectionsDisplay();
            }
        });
    }
    
    function updateSelectedSectionsDisplay() {
        var selectedOptions = $('#section_id').val();
        var displayDiv = $('#selectedSectionsDisplay');
        var listDiv = $('#selectedSectionsList');
        
        if (!selectedOptions || selectedOptions.length === 0 || (selectedOptions.length === 1 && selectedOptions[0] === 'all')) {
            displayDiv.hide();
            return;
        }
        
        var sections = [];
        $('#section_id option:selected').each(function() {
            if ($(this).val() !== 'all') {
                sections.push($(this).text());
            }
        });
        
        if (sections.length === 0) {
            displayDiv.hide();
        } else {
            listDiv.empty();
            sections.forEach(function(section) {
                listDiv.append('<span class="section-badge">' + section + '</span>');
            });
            displayDiv.show();
        }
    }
    
    function resetForm() {
        $('#zeroMarksForm')[0].reset();
        $('#section_id').val('all').trigger('change');
        $('#group_by').val('student').trigger('change');
        $('.select2').trigger('change');
        updateSelectedSectionsDisplay();
    }
    
    function printReport() {
        var printContent = document.getElementById('printReport').innerHTML;
        var originalContent = document.body.innerHTML;
        
        // Create a new window for printing
        var printWindow = window.open('', '_blank', 'width=800,height=600');
        printWindow.document.write(`
            <!DOCTYPE html>
            <html>
            <head>
                <title>Absent/Zero Marks Report - <?php echo htmlspecialchars($legclass); ?></title>
                <style>
                    ${getPrintStyles()}
                </style>
            </head>
            <body>
                ${printContent}
                <script>
                    window.onload = function() {
                        window.print();
                        setTimeout(function() {
                            window.close();
                        }, 500);
                    };
                <\/script>
            </body>
            </html>
        `);
        printWindow.document.close();
    }
    
    function getPrintStyles() {
        return `
            @page {
                size: A4 portrait;
                margin: 0.5in;
            }
            
            body {
                font-family: 'Times New Roman', Times, serif;
                font-size: 12pt;
                line-height: 1.4;
                color: #000;
                background: white;
                margin: 0;
                padding: 0;
            }
            
            .school-header {
                text-align: center;
                border-bottom: 2px solid #000;
                padding-bottom: 10px;
                margin-bottom: 20px;
            }
            
            .school-name {
                font-size: 24pt;
                font-weight: bold;
                text-transform: uppercase;
                letter-spacing: 1px;
                margin-bottom: 5px;
            }
            
            .school-address {
                font-size: 11pt;
                margin-bottom: 3px;
            }
            
            .report-title {
                text-align: center;
                margin: 30px 0 20px 0;
                font-size: 18pt;
                font-weight: bold;
                text-decoration: underline;
                text-transform: uppercase;
            }
            
            .exam-details {
                text-align: center;
                margin-bottom: 25px;
                font-size: 12pt;
                border: 1px solid #000;
                padding: 10px;
                background-color: #f9f9f9;
            }
            
            .report-table {
                width: 100%;
                border-collapse: collapse;
                margin-bottom: 30px;
                page-break-inside: auto;
            }
            
            .report-table th {
                background-color: #f2f2f2;
                color: #000;
                font-weight: bold;
                border: 1px solid #000;
                padding: 8px 5px;
                text-align: center;
                font-size: 11pt;
            }
            
            .report-table td {
                border: 1px solid #000;
                padding: 6px 5px;
                text-align: left;
                font-size: 10pt;
                vertical-align: top;
            }
            
            .section-header-row {
                background-color: #e8e8e8;
                font-weight: bold;
            }
            
            .section-header-row td {
                font-weight: bold;
                font-size: 11pt;
                padding: 8px 5px;
            }
            
            .absent-row {
                background-color: #fff0f0;
            }
            
            .no-data-row {
                background-color: #fff8e8;
            }
            
            .subject-details {
                font-size: 9.5pt;
                line-height: 1.3;
            }
            
            .subject-item {
                margin-bottom: 3px;
                padding-bottom: 3px;
            }
            
            .absent-text {
                color: #c00;
                font-weight: bold;
            }
            
            .no-data-text {
                color: #e67e00;
                font-weight: bold;
            }
            
            .summary-section {
                margin-top: 40px;
                padding: 15px;
                border: 1px solid #000;
                background-color: #f9f9f9;
                page-break-inside: avoid;
            }
            
            .summary-title {
                font-weight: bold;
                font-size: 12pt;
                margin-bottom: 10px;
                text-align: center;
                text-decoration: underline;
            }
            
            .summary-grid {
                display: grid;
                grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
                gap: 15px;
            }
            
            .summary-item {
                text-align: center;
            }
            
            .summary-value {
                font-size: 14pt;
                font-weight: bold;
                color: #000;
            }
            
            .summary-label {
                font-size: 10pt;
                color: #666;
            }
            
            .signature-section {
                margin-top: 60px;
                page-break-inside: avoid;
            }
            
            .signature-line {
                display: flex;
                justify-content: space-between;
                margin-top: 50px;
            }
            
            .signature-box {
                text-align: center;
                width: 200px;
                border-top: 1px solid #000;
                padding-top: 10px;
            }
            
            .signature-name {
                font-weight: bold;
                margin-top: 5px;
            }
            
            .signature-title {
                font-size: 10pt;
                color: #666;
            }
            
            .print-footer {
                margin-top: 40px;
                text-align: center;
                font-size: 10pt;
                color: #666;
                border-top: 1px solid #ccc;
                padding-top: 10px;
            }
            
            .print-date {
                float: right;
                font-size: 10pt;
                margin-top: 10px;
            }
            
            * {
                -webkit-print-color-adjust: exact;
                print-color-adjust: exact;
            }
        `;
    }
    
    function exportToExcel() {
        var table = document.getElementById('zeroMarksTable');
        var wb = XLSX.utils.book_new();
        var ws = XLSX.utils.table_to_sheet(table);
        
        XLSX.utils.book_append_sheet(wb, ws, 'Zero Marks Report');
        
        var fileName = 'Zero_Marks_Report_' + 
                      '<?php echo preg_replace("/[^a-zA-Z0-9]/", "_", $legclass); ?>_' + 
                      '<?php echo (!empty($displaySections) && count($displaySections) <= 3) ? preg_replace("/[^a-zA-Z0-9]/", "_", implode("_", $displaySections)) . "_" : ""; ?>' +
                      '<?php echo preg_replace("/[^a-zA-Z0-9]/", "_", $examtype); ?>_' + 
                      '<?php echo $examyear; ?>_' + 
                      new Date().toISOString().slice(0,10) + '.xlsx';
        
        XLSX.writeFile(wb, fileName);
    }
    
    function toggleStudentList(index) {
        var element = document.getElementById('studentList_' + index);
        if (element.style.display === 'none') {
            element.style.display = 'block';
        } else {
            element.style.display = 'none';
        }
    }
    </script>
</body>
</html>