<?php
include('session_validator.php');
include('includes/db.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 - Mark Slip Generator</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.jsdelivr.net/npm/sweetalert2@11"></script>
        <link rel="stylesheet" href="css/print-style.css" type="text/css" media="print" />
        
        <!-- DataTables CSS -->
        <link rel="stylesheet" href="https://cdn.datatables.net/1.13.6/css/jquery.dataTables.min.css">
        <link rel="stylesheet" href="https://cdn.datatables.net/buttons/2.4.1/css/buttons.dataTables.min.css">
        <link rel="stylesheet" href="https://cdn.datatables.net/responsive/2.5.0/css/responsive.dataTables.min.css">
        
        <style>
            .compact-form .form-group {
                margin-bottom: 15px;
            }
            .compact-form label {
                font-weight: 600;
                font-size: 14px;
                color: #495057;
                margin-bottom: 5px;
            }
            .panel-title h5 {
                font-weight: 600;
                color: #2c3e50;
                border-bottom: 2px solid #3498db;
                padding-bottom: 10px;
                margin-bottom: 20px;
            }
            .btn-generate {
                background: linear-gradient(135deg, #3498db, #2980b9);
                color: white;
                border: none;
                padding: 10px 25px;
                font-weight: 600;
                border-radius: 5px;
                transition: all 0.3s ease;
            }
            .btn-generate:hover {
                background: linear-gradient(135deg, #2980b9, #21618c);
                transform: translateY(-2px);
                box-shadow: 0 5px 15px rgba(41, 128, 185, 0.3);
            }
            .loading-spinner {
                display: none;
                text-align: center;
                padding: 20px;
            }
            #mark-slip-result {
                margin-top: 20px;
            }
            .section-info {
                background: #f8f9fa;
                padding: 10px;
                border-radius: 5px;
                margin-bottom: 15px;
                border-left: 4px solid #3498db;
            }
            
            /* Mark Slip Table Styles */
            .markslip-table {
                width: 100%;
                border-collapse: collapse;
                margin: 20px 0;
                box-shadow: 0 0 20px rgba(0,0,0,0.1);
            }
            .markslip-table thead {
                background: linear-gradient(135deg, #3498db, #2980b9);
                color: white;
            }
            .markslip-table th {
                padding: 12px 15px;
                text-align: center;
                font-weight: 600;
                border: 1px solid #ddd;
            }
            .markslip-table td {
                padding: 10px 15px;
                border: 1px solid #ddd;
                text-align: center;
            }
            .markslip-table tbody tr:nth-child(even) {
                background-color: #f8f9fa;
            }
            .markslip-table tbody tr:hover {
                background-color: #e3f2fd;
            }
            .student-info-cell {
                text-align: left !important;
                font-weight: 500;
            }
            .input-mark {
                width: 80px;
                padding: 5px;
                text-align: center;
                border: 1px solid #ced4da;
                border-radius: 3px;
                font-size: 14px;
            }
            .input-mark:focus {
                outline: none;
                border-color: #3498db;
                box-shadow: 0 0 5px rgba(52, 152, 219, 0.3);
            }
            .photo-cell {
                width: 80px;
            }
            .student-photo {
                width: 60px;
                height: 60px;
                border-radius: 50%;
                object-fit: cover;
                border: 2px solid #ddd;
            }
            
            /* Action Buttons */
            .action-buttons {
                margin: 20px 0;
                padding: 15px;
                background: #f8f9fa;
                border-radius: 5px;
                border-left: 4px solid #28a745;
            }
            .btn-print {
                background: linear-gradient(135deg, #28a745, #218838);
                color: white;
                border: none;
                padding: 8px 20px;
                border-radius: 4px;
                margin-right: 10px;
            }
            .btn-download {
                background: linear-gradient(135deg, #6c757d, #495057);
                color: white;
                border: none;
                padding: 8px 20px;
                border-radius: 4px;
                margin-right: 10px;
            }
            .btn-save {
                background: linear-gradient(135deg, #17a2b8, #138496);
                color: white;
                border: none;
                padding: 8px 20px;
                border-radius: 4px;
                margin-right: 10px;
            }
            
            /* Student Summary */
            .student-summary {
                background: #e8f5e9;
                padding: 15px;
                border-radius: 5px;
                margin-bottom: 20px;
                border-left: 4px solid #4caf50;
            }
            .summary-item {
                display: inline-block;
                margin-right: 20px;
                font-size: 14px;
            }
            .summary-item strong {
                color: #2e7d32;
            }
            
            /* Print specific styles */
            @media print {
                body * {
                    visibility: hidden;
                }
                #printable-markslip, #printable-markslip * {
                    visibility: visible;
                }
                #printable-markslip {
                    position: absolute;
                    left: 0;
                    top: 0;
                    width: 100%;
                    background: white;
                }
                .no-print {
                    display: none !important;
                }
                .markslip-table {
                    box-shadow: none;
                    border: 1px solid #000;
                }
                .input-mark {
                    border: 1px solid #000 !important;
                }
                .student-photo {
                    width: 50px;
                    height: 50px;
                }
            }
            
            /* Responsive adjustments */
            @media (max-width: 768px) {
                .markslip-table {
                    display: block;
                    overflow-x: auto;
                }
                .input-mark {
                    width: 60px;
                }
            }
            
            /* Grade colors */
            .grade-A { color: #28a745; font-weight: bold; }
            .grade-B { color: #17a2b8; font-weight: bold; }
            .grade-C { color: #ffc107; font-weight: bold; }
            .grade-D { color: #dc3545; font-weight: bold; }
            
            /* Status indicators */
            .status-active { color: #28a745; }
            .status-inactive { color: #dc3545; }
            
            /* Progress steps */
            .progress-steps {
                display: flex;
                margin-bottom: 30px;
                position: relative;
            }
            .progress-step {
                flex: 1;
                text-align: center;
                position: relative;
                padding: 10px;
                z-index: 1;
            }
            .step-circle {
                width: 40px;
                height: 40px;
                border-radius: 50%;
                background: #e9ecef;
                color: #6c757d;
                display: flex;
                align-items: center;
                justify-content: center;
                margin: 0 auto 10px;
                font-weight: bold;
                border: 3px solid #e9ecef;
                transition: all 0.3s ease;
            }
            .step-circle.active {
                background: #3498db;
                color: white;
                border-color: #3498db;
            }
            .step-circle.completed {
                background: #28a745;
                color: white;
                border-color: #28a745;
            }
            .step-label {
                font-size: 12px;
                color: #6c757d;
                transition: all 0.3s ease;
            }
            .step-label.active {
                color: #3498db;
                font-weight: bold;
            }
            .progress-line {
                position: absolute;
                top: 20px;
                left: 0;
                right: 0;
                height: 3px;
                background: #e9ecef;
                z-index: 0;
            }
            .progress-line-fill {
                position: absolute;
                top: 20px;
                left: 0;
                height: 3px;
                background: #28a745;
                z-index: 0;
                transition: width 0.3s ease;
            }
        </style>
    </head>
    <body class="top-navbar-fixed">
        <div class="main-wrapper">
            <?php include('includes/topbar.php'); ?> 
            <div class="content-wrapper">
                <div class="content-container">
                    <?php include('includes/leftbar.php'); ?>  
                    <div class="main-page">
                        <div class="container-fluid">
                            <!-- Page Header -->
                            <div class="row page-title-div">
                                <div class="col-md-6">
                                    <h2 class="title"><i class="fa fa-file-text-o mr-2"></i>Mark Slip Generator</h2>
                                </div>
                                <div class="col-md-6 text-right">
                                    <div class="stats-badge" style="background: #e3f2fd; border: 1px solid #bbdefb; color: #1976d2; padding: 5px 15px; border-radius: 20px; font-size: 13px;">
                                        <i class="fa fa-info-circle mr-1"></i>Create, generate and print mark slips
                                    </div>
                                </div>
                            </div>
                            
                            <!-- Breadcrumb -->
                            <div class="row breadcrumb-div">
                                <div class="col-md-12">
                                    <ul class="breadcrumb">
                                        <li><a href="dashboard.php"><i class="fa fa-home"></i> Home</a></li>
                                        <li><a href="#"><i class="fa fa-bar-chart"></i> Examination</a></li>
                                        <li class="active"><i class="fa fa-file-text-o"></i> Mark Slip</li>
                                    </ul>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Main Content -->
                        <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-cogs mr-2"></i>Generate Mark Slip</h5>
                                            </div>
                                        </div>
                                        <div class="panel-body">
                                            <!-- Progress Steps -->
                                            <div class="progress-steps">
                                                <div class="progress-line"></div>
                                                <div class="progress-line-fill" id="progressFill"></div>
                                                
                                                <div class="progress-step">
                                                    <div class="step-circle active" id="step1">1</div>
                                                    <div class="step-label active">Select Class</div>
                                                </div>
                                                <div class="progress-step">
                                                    <div class="step-circle" id="step2">2</div>
                                                    <div class="step-label">Select Section</div>
                                                </div>
                                                <div class="progress-step">
                                                    <div class="step-circle" id="step3">3</div>
                                                    <div class="step-label">Select Exam</div>
                                                </div>
                                                <div class="progress-step">
                                                    <div class="step-circle" id="step4">4</div>
                                                    <div class="step-label">Select Subject</div>
                                                </div>
                                                <div class="progress-step">
                                                    <div class="step-circle" id="step5">5</div>
                                                    <div class="step-label">Generate</div>
                                                </div>
                                            </div>
                                            
                                            <!-- Filter Form -->
                                            <form id="generate-mark-slip-form" class="compact-form">
                                                <div class="section-info">
                                                    <i class="fa fa-info-circle mr-2"></i>
                                                    Step 1: Select class, then section, then exam, then subject to generate mark slip
                                                </div>
                                                
                                                <div class="row">
                                                    <!-- Step 1: Class Selection -->
                                                    <div class="form-group col-md-3">
                                                        <label for="class_id" class="required-field">
                                                            <i class="fa fa-graduation-cap mr-1"></i>Step 1: Select Class:
                                                        </label>
                                                        <select id="class_id" name="class_id" class="form-control select2" required>
                                                            <option value="">-- Select Class --</option>
                                                            <?php
                                                            $queryclass = "SELECT class_id, class, class_numeric 
                                                                         FROM classes 
                                                                         WHERE status = '1' 
                                                                         ORDER BY class_numeric ASC";
                                                            $resultclass = $conn->query($queryclass);
                                                            while ($row = $resultclass->fetch_assoc()) {
                                                                echo "<option value='" . $row['class_id'] . "'>" . 
                                                                    htmlspecialchars($row['class']) . "</option>";
                                                            }
                                                            ?>
                                                        </select>
                                                        <small class="form-text text-muted">Select class first</small>
                                                    </div>

                                                    <!-- Step 2: Section Selection -->
                                                    <div class="form-group col-md-3">
                                                        <label for="section_id">
                                                            <i class="fa fa-columns mr-1"></i>Step 2: Select Section:
                                                        </label>
                                                        <select id="section_id" name="section_id" class="form-control select2" disabled required>
                                                            <option value="">-- Select Section --</option>
                                                        </select>
                                                        <small class="form-text text-muted">Section will be loaded after selecting class</small>
                                                    </div>

                                                    <!-- Step 3: Exam Selection -->
                                                    <div class="form-group col-md-3">
                                                        <label for="exam_id" class="required-field">
                                                            <i class="fa fa-calendar-check-o mr-1"></i>Step 3: Select Exam:
                                                        </label>
                                                        <select id="exam_id" name="exam_id" class="form-control select2" disabled required>
                                                            <option value="">-- Select Exam --</option>
                                                        </select>
                                                        <small class="form-text text-muted">Exam will be loaded after selecting class</small>
                                                    </div>

                                                    <!-- Step 4: Subject Selection -->
                                                    <div class="form-group col-md-3">
                                                        <label for="subject_id" class="required-field">
                                                            <i class="fa fa-book mr-1"></i>Step 4: Select Subject:
                                                        </label>
                                                        <select id="subject_id" name="subject_id" class="form-control select2" disabled required>
                                                            <option value="">-- Select Subject --</option>
                                                        </select>
                                                        <small class="form-text text-muted">Subject will be loaded after selecting class & section</small>
                                                    </div>
                                                </div>
                                                
                                                <!-- Additional Options -->
                                                <div class="row mt-3" id="additional-options" style="display: none;">
                                                    <div class="col-md-12">
                                                        <div class="section-info">
                                                            <i class="fa fa-cog mr-2"></i>
                                                            Step 5: Additional Options
                                                        </div>
                                                        <div class="row">
                                                            <div class="form-group col-md-4">
                                                                <div class="form-check">
                                                                    <input type="checkbox" class="form-check-input" id="include_student_photo" name="include_student_photo">
                                                                    <label class="form-check-label" for="include_student_photo">
                                                                        <i class="fa fa-camera mr-1"></i> Include Student Photos
                                                                    </label>
                                                                </div>
                                                                <div class="form-check">
                                                                    <input type="checkbox" class="form-check-input" id="show_roll_numbers" name="show_roll_numbers" checked>
                                                                    <label class="form-check-label" for="show_roll_numbers">
                                                                        <i class="fa fa-sort-numeric-asc mr-1"></i> Show Roll Numbers
                                                                    </label>
                                                                </div>
                                                            </div>
                                                            <div class="form-group col-md-4">
                                                                <label for="academic_year">
                                                                    <i class="fa fa-calendar mr-1"></i>Academic Year:
                                                                </label>
                                                                <select id="academic_year" name="academic_year" class="form-control">
                                                                    <option value="">Current Year</option>
                                                                    <?php
                                                                    $current_year = date('Y');
                                                                    for($i = $current_year - 5; $i <= $current_year + 1; $i++) {
                                                                        $next_year = $i + 1;
                                                                        echo "<option value='$i-$next_year'>$i-$next_year</option>";
                                                                    }
                                                                    ?>
                                                                </select>
                                                            </div>
                                                            <div class="form-group col-md-4">
                                                                <label for="display_format">
                                                                    <i class="fa fa-file-text-o mr-1"></i>Display Format:
                                                                </label>
                                                                <select id="display_format" name="display_format" class="form-control">
                                                                    <option value="detailed">Detailed View</option>
                                                                    <option value="compact">Compact View</option>
                                                                    <option value="print">Print Optimized</option>
                                                                </select>
                                                            </div>
                                                        </div>
                                                    </div>
                                                </div>
                                                
                                                <!-- Action Buttons -->
                                                <div class="form-actions text-center mt-4">
                                                    <button class="btn btn-generate" type="submit" id="generateBtn" disabled>
                                                        <i class="fa fa-file-text-o mr-1"></i> Generate Mark Slip
                                                    </button>
                                                    <button type="button" class="btn btn-secondary" id="resetBtn">
                                                        <i class="fa fa-refresh mr-1"></i> Reset
                                                    </button>
                                                </div>
                                            </form>
                                            
                                            <!-- Loading Indicator -->
                                            <div class="loading-spinner" id="loadingSpinner">
                                                <div class="spinner-border text-primary" role="status">
                                                    <span class="sr-only">Loading...</span>
                                                </div>
                                                <p class="mt-2">Generating mark slip, please wait...</p>
                                            </div>
                                            
                                            <!-- Result Display Area -->
                                            <div id="mark-slip-result" class="mt-4"></div>
                                        </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>
        
        <!-- DataTables JS -->
        <script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>
        <script src="https://cdn.datatables.net/buttons/2.4.1/js/dataTables.buttons.min.js"></script>
        <script src="https://cdn.datatables.net/buttons/2.4.1/js/buttons.print.min.js"></script>
        <script src="https://cdn.datatables.net/buttons/2.4.1/js/buttons.html5.min.js"></script>
        <script src="https://cdn.datatables.net/responsive/2.5.0/js/dataTables.responsive.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.1/jszip.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/pdfmake.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/vfs_fonts.js"></script>
        
        <script>
    $(document).ready(function () {
        // Initialize Select2
        $('.select2').select2({
            width: '100%',
            placeholder: "Select option",
            allowClear: true
        });
        
        // Update progress
        function updateProgress(currentStep) {
            // Reset all steps
            $('.step-circle').removeClass('active completed');
            $('.step-label').removeClass('active');
            
            // Set completed and active steps
            for (let i = 1; i <= 5; i++) {
                if (i < currentStep) {
                    $('#step' + i).addClass('completed');
                    $('#step' + i).siblings('.step-label').addClass('active');
                } else if (i === currentStep) {
                    $('#step' + i).addClass('active');
                    $('#step' + i).siblings('.step-label').addClass('active');
                }
            }
            
            // Update progress bar
            var progress = ((currentStep - 1) / 4) * 100;
            $('#progressFill').css('width', progress + '%');
        }
        
        // Initialize progress
        updateProgress(1);
        
        // Step 1: When class is selected
        $('#class_id').change(function () {
            var classId = $(this).val();
            
            if (classId) {
                // Enable section select
                $('#section_id').prop('disabled', false);
                $('#exam_id').prop('disabled', false);
                
                // Clear and load sections
                $('#section_id').html('<option value="">Loading sections...</option>').trigger('change');
                loadSections(classId);
                
                // Clear and load exams
                $('#exam_id').html('<option value="">Loading exams...</option>').trigger('change');
                loadExams(classId);
                
                // Disable subject until section is selected
                $('#subject_id').prop('disabled', true).html('<option value="">-- Select Subject --</option>');
                
                // Disable generate button
                $('#generateBtn').prop('disabled', true);
                
                // Update progress
                updateProgress(1);
            } else {
                // Reset everything
                resetForm();
                updateProgress(1);
            }
        });
        
        // Step 2: When section is selected
        $('#section_id').change(function () {
            var classId = $('#class_id').val();
            var sectionId = $(this).val();
            
            console.log('Section selected - Class:', classId, 'Section:', sectionId);
            
            if (classId && sectionId) {
                // Enable subject select and load subjects
                $('#subject_id').prop('disabled', false);
                loadSubjects(classId, sectionId);
                
                // Update progress
                updateProgress(2);
            } else {
                $('#subject_id').prop('disabled', true).html('<option value="">-- Select Subject --</option>');
                updateProgress(1);
            }
        });
        
        // Step 3: When exam is selected
        $('#exam_id').change(function () {
            if ($(this).val()) {
                updateProgress(3);
            } else {
                updateProgress(2);
            }
        });
        
        // Step 4: When subject is selected
        $('#subject_id').change(function () {
            if ($(this).val()) {
                // Show additional options
                $('#additional-options').show();
                // Enable generate button
                $('#generateBtn').prop('disabled', false);
                updateProgress(4);
            } else {
                $('#additional-options').hide();
                $('#generateBtn').prop('disabled', true);
                updateProgress(3);
            }
        });
        
// Function to load sections
function loadSections(classId) {
    $.ajax({
        url: 'ajax/get_sections_by_class.php',
        type: 'GET',
        dataType: 'json', // Add this
        data: { class_id: classId },
        success: function (sections) { // Already parsed
            console.log('Sections received:', sections);
            var options = '<option value="">-- Select Section --</option>';
            
            if (sections && sections.length > 0) {
                sections.forEach(function (section) {
                    options += '<option value="' + section.section_id + '">' + 
                              section.section_name + '</option>';
                });
            } else {
                options = '<option value="">No sections available</option>';
            }
            
            $('#section_id').html(options).trigger('change');
        },
        error: function (xhr, status, error) {
            console.error('AJAX error loading sections:', status, error);
            $('#section_id').html('<option value="">Error loading sections</option>').trigger('change');
        }
    });
}

// Function to load exams for the class
function loadExams(classId) {
    $.ajax({
        url: 'ajax/get_exams_by_class.php',
        type: 'GET',
        dataType: 'json', // Add this
        data: { class_id: classId },
        success: function (exams) { // Already parsed
            console.log('Exams received:', exams);
            var options = '<option value="">-- Select Exam --</option>';
            
            if (exams && exams.length > 0) {
                exams.forEach(function (exam) {
                    options += '<option value="' + exam.id + '">' + 
                              exam.exam_type + ' - ' + exam.exm_year + '</option>';
                });
            } else {
                options = '<option value="">No exams available</option>';
            }
            
            $('#exam_id').html(options).trigger('change');
        },
        error: function (xhr, status, error) {
            console.error('AJAX error loading exams:', status, error);
            $('#exam_id').html('<option value="">Error loading exams</option>').trigger('change');
        }
    });
}
        
        // Function to load subjects - CORRECTED VERSION
function loadSubjects(classId, sectionId) {
    console.log('Loading subjects for class:', classId, 'section:', sectionId);
    
    $.ajax({
        url: 'ajax/get_subjects_by_class_section.php',
        type: 'GET',
        dataType: 'json', // Explicitly tell jQuery to expect JSON
        data: { 
            class_id: classId,
            section_id: sectionId
        },
        beforeSend: function() {
            $('#subject_id').html('<option value="">Loading subjects...</option>');
        },
        success: function (data) { // data is already parsed by jQuery
            console.log('Subjects data received:', data);
            
            if (data.success === true && data.subjects && data.subjects.length > 0) {
                var options = '<option value="">-- Select Subject --</option>';
                
                data.subjects.forEach(function (subject) {
                    options += '<option value="' + subject.subject_id + '" ' +
                              'data-theory="' + (subject.theory_full_marks || 0) + '" ' +
                              'data-internal="' + (subject.internal_full_marks || 0) + '">' + 
                              subject.subject_name + ' (' + subject.subject_code + ')' + '</option>';
                });
                
                $('#subject_id').html(options).prop('disabled', false).trigger('change');
                console.log('Loaded ' + data.subjects.length + ' subjects');
                
            } else {
                var errorMsg = data.error || 'No subjects found';
                console.error('No subjects:', errorMsg);
                $('#subject_id').html('<option value="">' + errorMsg + '</option>').prop('disabled', true).trigger('change');
                
                Swal.fire({ 
                    icon: 'warning', 
                    title: 'No Subjects', 
                    text: 'No subjects found for this class-section combination.',
                    footer: 'Please check subject allocation.'
                });
            }
        },
        error: function (xhr, status, error) {
            console.error('AJAX Error loading subjects:', status, error);
            console.log('XHR response:', xhr.responseText);
            $('#subject_id').html('<option value="">Error loading subjects</option>').prop('disabled', true).trigger('change');
            
            Swal.fire({ 
                icon: 'error', 
                title: 'AJAX Error', 
                text: 'Failed to load subjects: ' + error 
            });
        }
    });
}
        
        // Form submission
        $("#generate-mark-slip-form").submit(function (e) {
            e.preventDefault();
            
            // Validate all required fields
            var classId = $('#class_id').val();
            var sectionId = $('#section_id').val();
            var examId = $('#exam_id').val();
            var subjectId = $('#subject_id').val();
            
            if (!classId || !sectionId || !examId || !subjectId) {
                Swal.fire({ 
                    icon: 'warning', 
                    title: 'Incomplete Form', 
                    text: 'Please complete all selection steps: Class, Section, Exam, and Subject.' 
                });
                return false;
            }
            
            // Show loading
            $("#loadingSpinner").show();
            $("#generateBtn").prop('disabled', true).html('<i class="fa fa-spinner fa-spin mr-1"></i> Generating...');
            $("#mark-slip-result").empty();
            
            // Get form data
            var formData = $(this).serialize();
            
           // In the form submission handler, update this part:
$.ajax({
    type: "POST",
    url: "ajax/generate_markslip.php",
    dataType: 'json', // Add this
    data: formData,
    success: function (result) { // Already parsed
        $("#loadingSpinner").hide();
        $("#generateBtn").prop('disabled', false).html('<i class="fa fa-file-text-o mr-1"></i> Generate Mark Slip');
        
        if (result.status === 'success') {
            displayMarkSlip(result.data);
            updateProgress(5);
        } else {
            Swal.fire({ 
                icon: "error", 
                title: "Error", 
                text: result.message 
            });
        }
    },
    error: function (xhr, status, error) {
        $("#loadingSpinner").hide();
        $("#generateBtn").prop('disabled', false).html('<i class="fa fa-file-text-o mr-1"></i> Generate Mark Slip');
        Swal.fire({ 
            icon: "error", 
            title: "Error", 
            text: "Failed to load mark slip. Please try again." 
        });
        console.error("AJAX Error:", status, error, xhr.responseText);
    }
});
        });
        
        // Reset form
        $("#resetBtn").click(function () {
            resetForm();
        });
        
        // Reset form function
        function resetForm() {
            $('#generate-mark-slip-form')[0].reset();
            $('#class_id').val('').trigger('change');
            $('#section_id').html('<option value="">-- Select Section --</option>').prop('disabled', true).trigger('change');
            $('#exam_id').html('<option value="">-- Select Exam --</option>').prop('disabled', true).trigger('change');
            $('#subject_id').html('<option value="">-- Select Subject --</option>').prop('disabled', true).trigger('change');
            $('#additional-options').hide();
            $('#generateBtn').prop('disabled', true);
            $('#mark-slip-result').empty();
            $('.select2').trigger('change');
            updateProgress(1);
        }
        
        // Auto-hide alerts after 5 seconds
        setTimeout(function() {
            $('.alert').fadeOut('slow');
        }, 5000);
    });
    
    
            
            // Function to display mark slip
            function displayMarkSlip(data) {
                var html = '<div id="printable-markslip">';
                
                // Header section
                html += '<div class="student-summary">';
                html += '<h5><i class="fa fa-file-text-o mr-2"></i>Mark Slip - ' + data.exam_name + '</h5>';
                html += '<div class="summary-item"><strong>Class:</strong> ' + data.class_name + '</div>';
                html += '<div class="summary-item"><strong>Section:</strong> ' + data.section_name + '</div>';
                html += '<div class="summary-item"><strong>Subject:</strong> ' + data.subject_name + ' (' + data.subject_code + ')</div>';
                html += '<div class="summary-item"><strong>Academic Year:</strong> ' + (data.academic_year || 'Current') + '</div>';
                html += '<div class="summary-item"><strong>Total Students:</strong> ' + data.total_students + '</div>';
                if (data.full_marks_theory > 0) {
                    html += '<div class="summary-item"><strong>Theory:</strong> ' + data.full_marks_theory + ' marks</div>';
                }
                if (data.full_marks_internal > 0) {
                    html += '<div class="summary-item"><strong>Internal:</strong> ' + data.full_marks_internal + ' marks</div>';
                }
                html += '</div>';
                
                // Action buttons
                html += '<div class="action-buttons no-print">';
                html += '<button onclick="printMarkSlip()" class="btn btn-print"><i class="fa fa-print mr-1"></i> Print</button>';
                html += '<button onclick="downloadExcel()" class="btn btn-download"><i class="fa fa-download mr-1"></i> Download Excel</button>';
                html += '<button onclick="saveMarks()" class="btn btn-save"><i class="fa fa-save mr-1"></i> Save All Marks</button>';
                html += '</div>';
                
                // Table
                html += '<div class="table-responsive">';
                html += '<table class="markslip-table" id="markslip-table">';
                html += '<thead>';
                html += '<tr>';
                html += '<th width="4%">SN</th>';
                
                if ($('#include_student_photo').is(':checked')) {
                    html += '<th width="8%">Photo</th>';
                }
                
                if ($('#show_roll_numbers').is(':checked')) {
                    html += '<th width="8%">Roll No</th>';
                }
                
                html += '<th width="' + ($('#include_student_photo').is(':checked') ? '20%' : '25%') + '">Student Name</th>';
                
                // Add mark columns based on subject data
                if (data.has_theory) {
                    html += '<th width="12%">Theory (' + data.full_marks_theory + ')</th>';
                }
                if (data.has_practical) {
                    html += '<th width="12%">Practical (' + data.full_marks_practical + ')</th>';
                }
                if (data.has_internal) {
                    html += '<th width="12%">Internal (' + data.full_marks_internal + ')</th>';
                }
                
                html += '<th width="10%">Total</th>';
                html += '<th width="8%">Grade</th>';
                html += '<th width="10%">Percentage</th>';
                html += '<th width="15%">Remarks</th>';
                html += '</tr>';
                html += '</thead>';
                html += '<tbody>';
                
                // Student rows
                if (data.students && data.students.length > 0) {
                    data.students.forEach(function(student, index) {
                        html += '<tr data-student-id="' + student.student_id + '">';
                        html += '<td>' + (index + 1) + '</td>';
                        
                        if ($('#include_student_photo').is(':checked')) {
                            var photoUrl = student.photo ? 'uploads/student_photos/' + student.photo : 'images/avatar.png';
                            html += '<td class="photo-cell">';
                            html += '<img src="' + photoUrl + '" class="student-photo" alt="' + student.student_name + '">';
                            html += '</td>';
                        }
                        
                        if ($('#show_roll_numbers').is(':checked')) {
                            html += '<td>' + (student.roll_no || student.symbol_no || '-') + '</td>';
                        }
                        
                        html += '<td class="student-info-cell">' + student.student_name + '</td>';
                        
                        // Theory mark input
                        if (data.has_theory) {
                            html += '<td>';
                            html += '<input type="number" class="input-mark theory-mark" ' +
                                   'data-student-id="' + student.student_id + '" data-type="theory" ' +
                                   'min="0" max="' + data.full_marks_theory + '" ' +
                                   'placeholder="0" value="' + (student.theory_marks || '') + '">';
                            html += '</td>';
                        }
                        
                        // Practical mark input (if available)
                        if (data.has_practical) {
                            html += '<td>';
                            html += '<input type="number" class="input-mark practical-mark" ' +
                                   'data-student-id="' + student.student_id + '" data-type="practical" ' +
                                   'min="0" max="' + data.full_marks_practical + '" ' +
                                   'placeholder="0" value="' + (student.practical_marks || '') + '">';
                            html += '</td>';
                        }
                        
                        // Internal mark input
                        if (data.has_internal) {
                            html += '<td>';
                            html += '<input type="number" class="input-mark internal-mark" ' +
                                   'data-student-id="' + student.student_id + '" data-type="internal" ' +
                                   'min="0" max="' + data.full_marks_internal + '" ' +
                                   'placeholder="0" value="' + (student.internal_marks || '') + '">';
                            html += '</td>';
                        }
                        
                        // Total, grade and percentage (calculated)
                        var total = (parseFloat(student.theory_marks) || 0) + 
                                   (parseFloat(student.practical_marks) || 0) + 
                                   (parseFloat(student.internal_marks) || 0);
                        var maxMarks = data.full_marks_theory + data.full_marks_internal + (data.full_marks_practical || 0);
                        var percentage = maxMarks > 0 ? ((total / maxMarks) * 100).toFixed(2) : 0;
                        
                        html += '<td><span class="total-mark" data-student-id="' + student.student_id + '">' + total.toFixed(2) + '</span></td>';
                        html += '<td><span class="grade" data-student-id="' + student.student_id + '">' + calculateGrade(percentage) + '</span></td>';
                        html += '<td><span class="percentage" data-student-id="' + student.student_id + '">' + percentage + '%</span></td>';
                        html += '<td><input type="text" class="form-control input-remark" ' +
                               'data-student-id="' + student.student_id + '" ' +
                               'placeholder="Enter remarks" value="' + (student.remarks || '') + '"></td>';
                        html += '</tr>';
                    });
                } else {
                    html += '<tr><td colspan="12" class="text-center">No students found in this class-section</td></tr>';
                }
                
                html += '</tbody>';
                html += '</table>';
                html += '</div>';
                
                // Footer with statistics
                html += '<div class="student-summary mt-3">';
                html += '<h6><i class="fa fa-bar-chart mr-2"></i>Statistics</h6>';
                html += '<div class="summary-item"><strong>Class Average:</strong> <span id="classAverage">Calculating...</span></div>';
                html += '<div class="summary-item"><strong>Highest Score:</strong> <span id="highestScore">-</span></div>';
                html += '<div class="summary-item"><strong>Lowest Score:</strong> <span id="lowestScore">-</span></div>';
                html += '<div class="summary-item"><strong>Pass Percentage:</strong> <span id="passPercentage">-</span></div>';
                html += '</div>';
                
                html += '</div>';
                
                $('#mark-slip-result').html(html);
                
                // Initialize DataTable if there are students
                if (data.students && data.students.length > 0) {
                    $('#markslip-table').DataTable({
                        responsive: true,
                        dom: 'Bfrtip',
                        buttons: [
                            {
                                extend: 'copy',
                                text: '<i class="fa fa-copy"></i> Copy',
                                className: 'btn btn-secondary btn-sm'
                            },
                            {
                                extend: 'excel',
                                text: '<i class="fa fa-file-excel-o"></i> Excel',
                                className: 'btn btn-success btn-sm'
                            },
                            {
                                extend: 'pdf',
                                text: '<i class="fa fa-file-pdf-o"></i> PDF',
                                className: 'btn btn-danger btn-sm'
                            },
                            {
                                extend: 'print',
                                text: '<i class="fa fa-print"></i> Print',
                                className: 'btn btn-info btn-sm'
                            }
                        ],
                        pageLength: 50,
                        lengthMenu: [[10, 25, 50, 100, -1], [10, 25, 50, 100, "All"]],
                        order: [[0, 'asc']],
                        language: {
                            search: "Search students:",
                            lengthMenu: "Show _MENU_ students",
                            info: "Showing _START_ to _END_ of _TOTAL_ students",
                            paginate: {
                                first: "First",
                                last: "Last",
                                next: "Next",
                                previous: "Previous"
                            }
                        }
                    });
                }
                
                // Add calculation logic
                $('.input-mark').on('input', function() {
                    var studentId = $(this).data('student-id');
                    calculateStudentResult(studentId);
                    calculateStatistics();
                });
                
                // Calculate initial statistics
                calculateStatistics();
                
                // Scroll to result
                $('html, body').animate({
                    scrollTop: $("#mark-slip-result").offset().top - 100
                }, 500);
            }
            
            // Calculate student result
            function calculateStudentResult(studentId) {
                var theory = parseFloat($('.theory-mark[data-student-id="' + studentId + '"]').val()) || 0;
                var practical = parseFloat($('.practical-mark[data-student-id="' + studentId + '"]').val()) || 0;
                var internal = parseFloat($('.internal-mark[data-student-id="' + studentId + '"]').val()) || 0;
                
                var total = theory + practical + internal;
                
                // Get max marks from hidden inputs
                var subjectOption = $('#subject_id option:selected');
                var maxTheory = parseFloat(subjectOption.data('theory')) || 0;
                var maxInternal = parseFloat(subjectOption.data('internal')) || 0;
                var maxPractical = 0; // Assuming practical marks if needed
                
                var maxMarks = maxTheory + maxInternal + maxPractical;
                var percentage = maxMarks > 0 ? ((total / maxMarks) * 100).toFixed(2) : 0;
                
                $('.total-mark[data-student-id="' + studentId + '"]').text(total.toFixed(2));
                $('.grade[data-student-id="' + studentId + '"]').html(calculateGrade(percentage));
                $('.percentage[data-student-id="' + studentId + '"]').text(percentage + '%');
            }
            
            // Grade calculation based on percentage
            function calculateGrade(percentage) {
                if (percentage >= 90) return '<span class="grade-A">A+</span>';
                if (percentage >= 80) return '<span class="grade-A">A</span>';
                if (percentage >= 70) return '<span class="grade-B">B+</span>';
                if (percentage >= 60) return '<span class="grade-B">B</span>';
                if (percentage >= 50) return '<span class="grade-C">C+</span>';
                if (percentage >= 40) return '<span class="grade-C">C</span>';
                if (percentage >= 30) return '<span class="grade-D">D+</span>';
                return '<span class="grade-D">F</span>';
            }
            
            // Calculate class statistics
            function calculateStatistics() {
                var totals = [];
                var passCount = 0;
                var totalStudents = 0;
                
                $('.total-mark').each(function() {
                    var total = parseFloat($(this).text()) || 0;
                    totals.push(total);
                    
                    // Consider pass if grade is not F (>= 30%)
                    var gradeHtml = $(this).closest('tr').find('.grade').html();
                    if (gradeHtml && !gradeHtml.includes('grade-D F')) {
                        passCount++;
                    }
                    
                    totalStudents++;
                });
                
                if (totals.length > 0) {
                    var sum = totals.reduce((a, b) => a + b, 0);
                    var average = (sum / totals.length).toFixed(2);
                    var highest = Math.max(...totals).toFixed(2);
                    var lowest = Math.min(...totals).toFixed(2);
                    var passPercentage = totalStudents > 0 ? ((passCount / totalStudents) * 100).toFixed(2) : 0;
                    
                    $('#classAverage').text(average);
                    $('#highestScore').text(highest);
                    $('#lowestScore').text(lowest);
                    $('#passPercentage').text(passPercentage + '%');
                }
            }
            
            // Print function
            function printMarkSlip() {
                var printContent = document.getElementById('printable-markslip').innerHTML;
                var originalContent = document.body.innerHTML;
                
                document.body.innerHTML = printContent;
                window.print();
                document.body.innerHTML = originalContent;
                window.location.reload();
            }
            
            // Download Excel function
            function downloadExcel() {
                var table = $('#markslip-table').DataTable();
                table.button('.buttons-excel').trigger();
            }
            
            // Save marks function
            function saveMarks() {
                var examId = $('#exam_id').val();
                var subjectId = $('#subject_id').val();
                var classId = $('#class_id').val();
                var sectionId = $('#section_id').val();
                
                var marksData = [];
                var hasErrors = false;
                var errorMessages = [];
                
                $('tr[data-student-id]').each(function() {
                    var studentId = $(this).data('student-id');
                    var theory = $(this).find('.theory-mark').val() || 0;
                    var practical = $(this).find('.practical-mark').val() || 0;
                    var internal = $(this).find('.internal-mark').val() || 0;
                    var total = $(this).find('.total-mark').text();
                    var remark = $(this).find('.input-remark').val();
                    
                    // Validate marks
                    var subjectOption = $('#subject_id option:selected');
                    var maxTheory = parseFloat(subjectOption.data('theory')) || 0;
                    var maxInternal = parseFloat(subjectOption.data('internal')) || 0;
                    
                    if (parseFloat(theory) > maxTheory) {
                        hasErrors = true;
                        errorMessages.push('Theory marks for student ID ' + studentId + ' exceeds maximum (' + maxTheory + ')');
                    }
                    
                    if (parseFloat(internal) > maxInternal) {
                        hasErrors = true;
                        errorMessages.push('Internal marks for student ID ' + studentId + ' exceeds maximum (' + maxInternal + ')');
                    }
                    
                    marksData.push({
                        student_id: studentId,
                        theory: theory,
                        practical: practical,
                        internal: internal,
                        total: total,
                        remark: remark
                    });
                });
                
                if (hasErrors) {
                    Swal.fire({ 
                        icon: "error", 
                        title: "Validation Errors", 
                        html: errorMessages.join('<br>') 
                    });
                    return;
                }
                
                Swal.fire({
                    title: 'Save Marks?',
                    text: 'This will save marks for ' + marksData.length + ' students.',
                    icon: 'question',
                    showCancelButton: true,
                    confirmButtonColor: '#3085d6',
                    cancelButtonColor: '#d33',
                    confirmButtonText: 'Yes, save them!',
                    cancelButtonText: 'Cancel'
                }).then((result) => {
                    if (result.isConfirmed) {
                        $.ajax({
                            url: 'ajax/save_marks.php',
                            type: 'POST',
                            data: {
                                exam_id: examId,
                                subject_id: subjectId,
                                class_id: classId,
                                section_id: sectionId,
                                marks: marksData
                            },
                            success: function(response) {
                                try {
                                    var result = JSON.parse(response);
                                    if (result.status === 'success') {
                                        Swal.fire({ 
                                            icon: "success", 
                                            title: "Success", 
                                            text: result.message 
                                        });
                                    } else {
                                        Swal.fire({ 
                                            icon: "error", 
                                            title: "Error", 
                                            text: result.message 
                                        });
                                    }
                                } catch(e) {
                                    Swal.fire({ 
                                        icon: "error", 
                                        title: "Error", 
                                        text: "Failed to save marks" 
                                    });
                                }
                            },
                            error: function() {
                                Swal.fire({ 
                                    icon: "error", 
                                    title: "Error", 
                                    text: "Server error occurred" 
                                });
                            }
                        });
                    }
                });
            }
        </script>
    </body>
</html>