<?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>Generate Symbol Numbers</title>
    
    <!-- CSS Files -->
    <link rel="stylesheet" href="css/bootstrap.min.css" media="screen">
    <link rel="stylesheet" href="css/font-awesome.min.css" media="screen">
    <link rel="stylesheet" href="css/select2/select2.min.css">
    <link rel="stylesheet" href="css/main.css" media="screen">
    
    <!-- DataTables CSS -->
    <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.13.4/css/jquery.dataTables.min.css">
    <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/buttons/2.3.6/css/buttons.dataTables.min.css">
    
    <style>
        .step-box {
            background: #f8f9fa;
            padding: 20px;
            border-radius: 8px;
            margin-bottom: 10px;
            border-left: 4px solid #007bff;
        }
        .step-number {
            background: #007bff;
            color: white;
            width: 16px;
            height: 16px;
            border-radius: 50%;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            margin-right: 10px;
            font-weight: bold;
        }
        .hidden {
            display: none;
        }
        .symbol-input {
            font-weight: bold;
            text-align: center;
        }
        .symbol-input.assigned {
            color: #28a745;
        }
        .symbol-input.empty {
            color: #dc3545;
        }
        .action-buttons {
            margin-top: 20px;
            padding-top: 20px;
            border-top: 1px solid #dee2e6;
        }
    /* Main Table Container */
#studentTableContainer {
    max-height: 600px;
    overflow-y: auto;
    margin-top: 15px;
    padding: 0;
    border: 1px solid #dee2e6;
    border-radius: 6px;
    background: #fff;
}

/* Summary Card - More Compact */
.summary-card {
    background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
    border-bottom: 1px solid #dee2e6;
    border-radius: 6px 6px 0 0;
    padding: 8px 10px;
    margin: 0;
}

.summary-card .row {
    margin: 0 -5px;
}

.summary-card .col-md-3 {
    padding: 0 5px;
}

.summary-card .text-center {
    padding: 8px 5px;
    background: #fff;
    border-radius: 4px;
    border: 1px solid #e0e0e0;
    box-shadow: 0 2px 4px rgba(0,0,0,0.05);
    transition: all 0.3s ease;
}

.summary-card .text-center:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 6px rgba(0,0,0,0.1);
}

.summary-card h3 {
    font-size: 1.5rem;
    font-weight: 700;
    margin: 0;
    color: #2c3e50;
    line-height: 1.2;
}

.summary-card p.text-muted {
    font-size: 0.8rem;
    margin: 5px 0 0 0;
    color: #6c757d;
    text-transform: uppercase;
    letter-spacing: 0.5px;
    font-weight: 500;
}

/* Table Container */
.table-responsive {
    margin: 0;
    padding: 0;
    max-height: 850px;
    overflow-y: auto;
}

/* Table Styling */
#studentsTable {
    margin: 0;
    border-collapse: separate;
    border-spacing: 0;
    font-size: 0.9rem;
}

#studentsTable thead {
    position: sticky;
    top: 0;
    z-index: 10;
}

#studentsTable thead th {
    background-color: #2c3e50;
    color: white;
    font-weight: 600;
    padding: 10px 8px;
    border-bottom: 2px solid #1a252f;
    text-transform: uppercase;
    font-size: 0.8rem;
    letter-spacing: 0.5px;
    white-space: nowrap;
    vertical-align: middle;
}

#studentsTable tbody td {
    padding: 8px 8px;
    vertical-align: middle;
    border-top: 1px solid #f0f0f0;
    border-bottom: 1px solid #f0f0f0;
}

#studentsTable tbody tr {
    height: 30px;
    transition: all 0.2s ease;
}

#studentsTable tbody tr:hover {
    background-color: #f8f9fa;
    transform: scale(1.001);
    box-shadow: 0 2px 5px rgba(0,0,0,0.1);
}

/* Symbol Input Field */
.symbol-input {
    padding: 6px 8px;
    font-size: 0.9rem;
    height: 32px;
    min-width: 120px;
    border: 2px solid #e0e0e0;
    border-radius: 4px;
    font-weight: 600;
    text-align: center;
    transition: all 0.3s ease;
}

.symbol-input:focus {
    border-color: #3498db;
    box-shadow: 0 0 0 3px rgba(52, 152, 219, 0.2);
    outline: none;
}

.symbol-input.assigned {
    border-color: #27ae60;
    background-color: #e8f6f3;
    color: #1e8449;
}

.symbol-input.empty {
    border-color: #e74c3c;
    background-color: #fdedec;
    color: #c0392b;
}

.symbol-input.is-valid {
    border-color: #27ae60;
    background-color: #e8f6f3;
}

.symbol-input.is-invalid {
    border-color: #e74c3c;
    background-color: #fdedec;
}

/* Badge Styling */
.badge {
    font-size: 0.75rem;
    padding: 4px 8px;
    font-weight: 600;
}

.badge-success {
    background-color: #27ae60;
}

.badge-danger {
    background-color: #e74c3c;
}

/* Compact Table Cells */
#studentsTable td:nth-child(1) { /* # column */
    text-align: center;
    font-weight: 600;
    color: #7f8c8d;
}

#studentsTable td:nth-child(2), /* Regd ID */
#studentsTable td:nth-child(3) { /* Registration No */
    font-family: 'Courier New', monospace;
    font-weight: 600;
    color: #2c3e50;
}

#studentsTable td:nth-child(4) { /* Student Name */
    font-weight: 500;
    color: #34495e;
}

#studentsTable td:nth-child(5), /* Class */
#studentsTable td:nth-child(6) { /* Section */
    text-align: center;
    font-weight: 500;
}

#studentsTable td:nth-child(7) { /* Existing Symbol */
    text-align: center;
}

/* Responsive Design */
@media (max-width: 1200px) {
    #studentsTable {
        font-size: 0.85rem;
    }
    
    .symbol-input {
        font-size: 0.85rem;
        min-width: 100px;
        padding: 5px 6px;
    }
    
    .summary-card h3 {
        font-size: 1.3rem;
    }
}

@media (max-width: 992px) {
    #studentTableContainer {
        max-height: 700px;
    }
    
    .summary-card .col-md-3 {
        margin-bottom: 8px;
    }
    
    .summary-card h3 {
        font-size: 1.2rem;
    }
    
    #studentsTable thead th {
        font-size: 0.75rem;
        padding: 8px 6px;
    }
    
    #studentsTable tbody td {
        padding: 6px 6px;
    }
}

@media (max-width: 768px) {
    #studentTableContainer {
        max-height: 600px;
        border: none;
        border-radius: 0;
    }
    
    .summary-card {
        padding: 8px 10px;
    }
    
    .summary-card .text-center {
        padding: 6px 4px;
    }
    
    .table-responsive {
        max-height: 500px;
    }
    
    #studentsTable {
        font-size: 0.8rem;
        min-width: 800px; /* Enable horizontal scroll on small screens */
    }
    
    .symbol-input {
        font-size: 0.8rem;
        height: 32px;
        min-width: 90px;
    }
}

@media (max-width: 576px) {
    #studentTableContainer {
        max-height: 500px;
    }
    
    .summary-card h3 {
        font-size: 1rem;
    }
    
    .summary-card p.text-muted {
        font-size: 0.7rem;
    }
    
    .table-responsive {
        max-height: 400px;
    }
}

/* Custom Scrollbar */
#studentTableContainer::-webkit-scrollbar {
    width: 8px;
    height: 8px;
}

#studentTableContainer::-webkit-scrollbar-track {
    background: #f1f1f1;
    border-radius: 4px;
}

#studentTableContainer::-webkit-scrollbar-thumb {
    background: #c1c1c1;
    border-radius: 4px;
}

#studentTableContainer::-webkit-scrollbar-thumb:hover {
    background: #a8a8a8;
}

/* Sticky Header Enhancement */
#studentsTable thead th {
    box-shadow: 0 2px 5px rgba(0,0,0,0.1);
}

/* Zebra Striping for Readability */
#studentsTable tbody tr:nth-child(even) {
    background-color: #f9f9f9;
}

#studentsTable tbody tr:nth-child(even):hover {
    background-color: #f0f0f0;
}

/* Loading State */
.loading {
    opacity: 0.7;
    pointer-events: none;
}

/* Action Buttons Container */
.action-buttons {
    margin-top: 15px;
    padding: 15px;
    background: #f8f9fa;
    border-top: 1px solid #dee2e6;
    border-radius: 0 0 6px 6px;
}

.action-buttons .row {
    margin: 0 -5px;
}

.action-buttons .col-md-8,
.action-buttons .col-md-4 {
    padding: 0 5px;
}

.action-buttons .form-control {
    font-size: 0.875rem;
    padding: 6px 8px;
    height: 36px;
}

.action-buttons .btn {
    padding: 6px 12px;
    font-size: 0.875rem;
    margin: 0 2px;
}

/* Adjust Form Controls in Action Buttons */
#startNumber, #incrementBy {
    width: 80px !important;
}

#resetOption {
    width: 120px !important;
}
    </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">
                <?php include('includes/leftbar.php'); ?>
                
                <div class="main-page">
                    <div class="container-fluid">
                        <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> Exam</li>
                                    <li class="active">Generate Symbol Numbers</li>
                                </ul>
                            </div>
                        </div>
                    </div>
                   
                    <section class="section">
                        <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-hashtag"></i> Generate Symbol Numbers</h5>
                                            </div>
                                        </div>
                                        
                                        <div class="panel-body">
                                             <div class="row">
                                            <!-- Step 1: Select Exam -->
                                            <div class="step-box col-md-3">
                                                <!--<div class="step-header">-->
                                                <!--    <h5><span class="step-number">1</span> Select Examination</h5>-->
                                                <!--</div>-->
                                                <div class="form-group">
                                                    <label for="exam_type">Select Exam Type:</label>
                                                    <select id="exam_type" name="exam_type" class="form-control" style="width: 100%;" required>
                                                        <option value="">-- Select Exam Type --</option>
                                                        <?php
                                                        $examQuery = "SELECT id, exam_type, exm_year FROM examination_type ORDER BY exm_year DESC";
                                                        $result = $conn->query($examQuery);
                                                        while ($row = $result->fetch_assoc()) {
                                                            echo '<option value="' . $row['id'] . '">' . 
                                                                 htmlspecialchars($row['exam_type']) . ' (' . 
                                                                 htmlspecialchars($row['exm_year']) . ')' . '</option>';
                                                        }
                                                        ?>
                                                    </select>
                                                </div>
                                            </div>
                                            
                                            <!-- Step 2: Select Class -->
                                            <div id="step2" class="step-box hidden col-md-3">
                                                <!--<div class="step-header">-->
                                                <!--    <h5><span class="step-number">2</span> Select Class</h5>-->
                                                <!--</div>-->
                                                <div class="form-group">
                                                    <label for="class_id">Select Class:</label>
                                                    <select id="class_id" name="class_id" class="form-control" style="width: 100%;" required>
                                                        <option value="">-- Select Class --</option>
                                                    </select>
                                                </div>
                                            </div>
                                            
                                            <!-- Step 3: Select Sections -->
                                            <div id="step3" class="step-box hidden col-md-6">
                                                <!--<div class="step-header">-->
                                                <!--    <h5><span class="step-number">3</span> Select Sections</h5>-->
                                                <!--</div>-->
                                                <div class="form-group col-md-6">
                                                    <label for="section_id">Select Section(s):</label>
                                                    <select id="section_id" name="section_id[]" class="form-control select2-multiple" multiple="multiple" style="width: 100%;" required>
                                                        <option value="">-- Select Sections --</option>
                                                    </select>
                                                    <small class="form-text text-muted">Hold Ctrl/Cmd to select multiple sections</small>
                                                </div>
                                                <div class="form-group col-md-2">
                                                    <button type="button" id="fetchStudents" class="btn btn-primary">
                                                        <i class="fa fa-search"></i> Fetch Students
                                                    </button>
                                                    <button type="button" id="selectAllSections" class="btn btn-secondary">
                                                        <i class="fa fa-check-square"></i> Select All
                                                    </button>
                                                </div>
                                            </div>
                                            
                                            </div>
                                            <!-- Student Table Container -->
                                            <div id="studentTableContainer" class="hidden">
                                                <div class="summary-card">
                                                    <div class="row">
                                                        <div class="col-md-3">
                                                            <div class="text-center">
                                                                <h3 id="totalStudents">0</h3>
                                                                <p class="text-muted">Total Students</p>
                                                            </div>
                                                        </div>
                                                        <div class="col-md-3">
                                                            <div class="text-center">
                                                                <h3 id="assignedCount">0</h3>
                                                                <p class="text-muted">Already Assigned</p>
                                                            </div>
                                                        </div>
                                                        <div class="col-md-3">
                                                            <div class="text-center">
                                                                <h3 id="pendingCount">0</h3>
                                                                <p class="text-muted">Pending Assignment</p>
                                                            </div>
                                                        </div>
                                                        <div class="col-md-3">
                                                            <div class="text-center">
                                                                <h3 id="selectedCount">0</h3>
                                                                <p class="text-muted">Selected Sections</p>
                                                            </div>
                                                        </div>
                                                    </div>
                                                </div>
                                                
                                                <div class="table-responsive">
                                                    <table class="table table-bordered table-hover" id="studentsTable" style="width: 100%;">
                                                        <thead class="thead-light">
                                                            <tr>
                                                                <th width="5%">#</th>
                                                                <th width="10%">Regd ID</th>
                                                                <th width="10%">Registration No</th>
                                                                <th width="20%">Student Name</th>
                                                                <th width="10%">Class</th>
                                                                <th width="5%">Section</th>
                                                                <th width="10%">Existing Symbol</th>
                                                                <th width="20%">New Symbol Number</th>
                                                            </tr>
                                                        </thead>
                                                        <tbody>
                                                            <!-- Data will be loaded via AJAX -->
                                                        </tbody>
                                                    </table>
                                                </div>
                                                
                                                <!-- Auto Generation Options -->
                                                <div class="action-buttons">
                                                    <div class="row">
                                                        <div class="col-md-8">
                                                            <div class="form-inline">
                                                                <div class="form-group mr-3">
                                                                    <label for="startNumber" class="mr-2">Start From:</label>
                                                                    <input type="number" id="startNumber" class="form-control" min="1" value="1001" style="width: 100px;">
                                                                </div>
                                                                <div class="form-group mr-3">
                                                                    <label for="incrementBy" class="mr-2">Increment By:</label>
                                                                    <input type="number" id="incrementBy" class="form-control" min="1" value="1" style="width: 100px;">
                                                                </div>
                                                                <div class="form-group mr-3">
                                                                    <label for="resetOption" class="mr-2">Reset For:</label>
                                                                    <select id="resetOption" class="form-control">
                                                                        <option value="none">Don't Reset</option>
                                                                        <option value="section">Each Section</option>
                                                                    </select>
                                                                </div>
                                                                <button type="button" id="autoGenerateBtn" class="btn btn-info">
                                                                    <i class="fa fa-magic"></i> Auto Generate
                                                                </button>
                                                            </div>
                                                        </div>
                                                        <div class="col-md-4 text-right">
                                                            <button type="button" id="clearAllBtn" class="btn btn-warning">
                                                                <i class="fa fa-eraser"></i> Clear All
                                                            </button>
                                                            <button type="button" id="saveAllBtn" class="btn btn-success">
                                                                <i class="fa fa-save"></i> Save All
                                                            </button>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </section>
                </div>
            </div>
        </div>
    </div>

    <!-- JavaScript Files -->
       <script src="js/jquery/jquery-2.2.4.min.js"></script>
        <script src="js/bootstrap/bootstrap.min.js"></script>
        <script src="js/pace/pace.min.js"></script>
        <script src="js/lobipanel/lobipanel.min.js"></script>
        <script src="js/iscroll/iscroll.js"></script>
        <script src="js/prism/prism.js"></script>
        <script src="js/select2/select2.min.js"></script>
        <script src="js/main.js"></script>
    
    <!-- DataTables -->
    <script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.13.4/js/jquery.dataTables.min.js"></script>
    
    <!-- SweetAlert2 -->
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    
    <script>
    $(document).ready(function() {
        // Initialize select2 for single select
        $('#exam_type, #class_id').select2();
        
        // Initialize select2 for multiple select
        $('.select2-multiple').select2({
            placeholder: "Select sections...",
            allowClear: true
        });
        
        // DataTable instance
        var studentsTable = null;
        
        // When exam is selected
        $('#exam_type').change(function() {
            var examId = $(this).val();
            
            if (!examId) {
                $('#step2').addClass('hidden');
                $('#step3').addClass('hidden');
                return;
            }
            
            // Show loading
            $('#class_id').html('<option value="">Loading classes...</option>').trigger('change');
            
            // Fetch classes for this exam
            $.ajax({
                url: 'ajax/get_classes_for_exam.php',
                type: 'GET',
                data: { exam_id: examId },
                dataType: 'json',
                success: function(response) {
                    $('#class_id').empty().append('<option value="">-- Select Class --</option>');
                    
                    if (response && response.length > 0) {
                        $.each(response, function(index, cls) {
                            $('#class_id').append(
                                $('<option></option>')
                                    .val(cls.class_id)
                                    .text(cls.class_name)
                            );
                        });
                        
                        // Show step 2
                        $('#step2').removeClass('hidden');
                        $('#step3').addClass('hidden');
                        $('#studentTableContainer').addClass('hidden');
                        
                        // Show success message
                        Swal.fire({
                            icon: 'success',
                            title: 'Classes Loaded',
                            text: 'Select a class to continue',
                            timer: 1500,
                            showConfirmButton: false
                        });
                    } else {
                        Swal.fire({
                            icon: 'warning',
                            title: 'No Classes',
                            text: 'No classes found for this exam.',
                        });
                    }
                },
                error: function(xhr, status, error) {
                    console.error('Error loading classes:', error);
                    Swal.fire({
                        icon: 'error',
                        title: 'Error',
                        text: 'Failed to load classes.',
                    });
                }
            });
        });
        
        // When class is selected
        $('#class_id').change(function() {
            var classId = $(this).val();
            var examId = $('#exam_type').val();
            
            if (!classId || !examId) {
                $('#step3').addClass('hidden');
                return;
            }
            
            // Show loading
            $('#section_id').html('<option value="">Loading sections...</option>').trigger('change');
            
            // Fetch sections for this class and exam
            $.ajax({
                url: 'ajax/get_sections_for_class.php',
                type: 'GET',
                data: { 
                    exam_id: examId,
                    class_id: classId
                },
                dataType: 'json',
                success: function(response) {
                    $('#section_id').empty();
                    
                    if (response && response.length > 0) {
                        $.each(response, function(index, section) {
                            $('#section_id').append(
                                $('<option></option>')
                                    .val(section.section_id)
                                    .text(section.section_name)
                            );
                        });
                        
                        // Show step 3
                        $('#step3').removeClass('hidden');
                        $('#studentTableContainer').addClass('hidden');
                        
                        // Show success message
                        Swal.fire({
                            icon: 'success',
                            title: 'Sections Loaded',
                            text: 'Select section(s) to fetch students',
                            timer: 1500,
                            showConfirmButton: false
                        });
                    } else {
                        Swal.fire({
                            icon: 'warning',
                            title: 'No Sections',
                            text: 'No sections found for this class.',
                        });
                    }
                },
                error: function(xhr, status, error) {
                    console.error('Error loading sections:', error);
                    Swal.fire({
                        icon: 'error',
                        title: 'Error',
                        text: 'Failed to load sections.',
                    });
                }
            });
        });
        
        // Select all sections
        $('#selectAllSections').click(function() {
            $('#section_id').val($('#section_id option').map(function() {
                return $(this).val();
            }).get()).trigger('change');
        });
        
        // Fetch students button
        $('#fetchStudents').click(function() {
            var examId = $('#exam_type').val();
            var classId = $('#class_id').val();
            var sectionIds = $('#section_id').val();
            
            // Validation
            if (!examId) {
                Swal.fire({
                    icon: 'warning',
                    title: 'Select Exam',
                    text: 'Please select an exam first.',
                });
                return;
            }
            
            if (!classId) {
                Swal.fire({
                    icon: 'warning',
                    title: 'Select Class',
                    text: 'Please select a class.',
                });
                return;
            }
            
            if (!sectionIds || sectionIds.length === 0) {
                Swal.fire({
                    icon: 'warning',
                    title: 'Select Sections',
                    text: 'Please select at least one section.',
                });
                return;
            }
            
            // Show loading
            Swal.fire({
                title: 'Loading...',
                text: 'Fetching student data',
                allowOutsideClick: false,
                didOpen: () => {
                    Swal.showLoading();
                }
            });
            
            // Prepare data
            var formData = new FormData();
            formData.append('exam_id', examId);
            formData.append('class_id', classId);
            
            // Add each section_id
            $.each(sectionIds, function(index, sectionId) {
                formData.append('section_ids[]', sectionId);
            });
            
            // Send request
            $.ajax({
                url: 'ajax/fetch_students.php',
                type: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                dataType: 'json',
                success: function(response) {
                    Swal.close();
                    
                    if (response.error) {
                        Swal.fire({
                            icon: 'error',
                            title: 'Error',
                            text: response.error,
                        });
                        return;
                    }
                    
                    if (!response || response.length === 0) {
                        Swal.fire({
                            icon: 'info',
                            title: 'No Students',
                            text: 'No students found for the selected criteria.',
                        });
                        return;
                    }
                    
                    // Show student table
                    $('#studentTableContainer').removeClass('hidden');
                    
                    // Update summary
                    updateSummary(response);
                    
                    // Populate table
                    populateStudentTable(response);
                    
                    // Show success message
                    Swal.fire({
                        icon: 'success',
                        title: 'Students Loaded!',
                        text: 'Found ' + response.length + ' student(s)',
                        timer: 2000,
                        showConfirmButton: false
                    });
                },
                error: function(xhr, status, error) {
                    Swal.close();
                    Swal.fire({
                        icon: 'error',
                        title: 'Error',
                        text: 'Failed to fetch students: ' + error,
                    });
                    console.error('AJAX Error:', error, xhr.responseText);
                }
            });
        });
        
        // Update summary function
        function updateSummary(students) {
            var total = students.length;
            var assigned = 0;
            
            $.each(students, function(index, student) {
                if (student.symbol_no && student.symbol_no.trim() !== '') {
                    assigned++;
                }
            });
            
            var selectedSections = $('#section_id').val() ? $('#section_id').val().length : 0;
            
            $('#totalStudents').text(total);
            $('#assignedCount').text(assigned);
            $('#pendingCount').text(total - assigned);
            $('#selectedCount').text(selectedSections);
        }
        
        // Populate student table
        function populateStudentTable(students) {
            // Destroy existing DataTable if exists
            if ($.fn.DataTable.isDataTable('#studentsTable')) {
                studentsTable.destroy();
                $('#studentsTable tbody').empty();
            }
            
            // Populate table body
            var tbody = $('#studentsTable tbody');
            tbody.empty();
            
            $.each(students, function(index, student) {
                var hasExistingSymbol = student.symbol_no && student.symbol_no.trim() !== '';
                var symbolClass = hasExistingSymbol ? 'assigned' : 'empty';
                
                var row = '<tr>' +
                    '<td>' + (index + 1) + '</td>' +
                    '<td>' + student.regd_id + '</td>' +
                    '<td>' + (student.registration_no || 'N/A') + '</td>' +
                    '<td>' + student.name + '</td>' +
                    '<td>' + student.class_name + '</td>' +
                    '<td>' + (student.section || 'N/A') + '</td>' +
                    '<td class="text-center">' +
                        (hasExistingSymbol ? 
                         '<span class="badge badge-success">' + student.symbol_no + '</span>' : 
                         '<span class="badge badge-danger">Not assigned</span>') +
                    '</td>' +
                    '<td>' +
                        '<input type="text" class="form-control symbol-input ' + symbolClass + '" ' +
                               'data-student-id="' + student.student_id + '" ' +
                               'data-class-id="' + student.class_id + '" ' +
                               'data-section-id="' + student.section_id + '" ' +
                               'value="' + (student.symbol_no || '') + '" ' +
                               'placeholder="Enter symbol">' +
                    '</td>' +
                    '</tr>';
                tbody.append(row);
            });
            
            // Initialize DataTable
            studentsTable = $('#studentsTable').DataTable({
                paging: true,
                pageLength: 25,
                lengthMenu: [[10, 25, 50, 100, -1], [10, 25, 50, 100, "All"]],
                ordering: true,
                searching: true,
                info: true,
                order: [[3, 'asc']], // Sort by name
                columnDefs: [
                    { orderable: false, targets: [0, 7] }
                ],
                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"
                    }
                }
            });
        }
        
        // Auto generate symbol numbers
        $('#autoGenerateBtn').click(function() {
            var start = parseInt($('#startNumber').val());
            var increment = parseInt($('#incrementBy').val());
            var resetOption = $('#resetOption').val();
            
            if (isNaN(start) || start < 1) {
                Swal.fire({
                    icon: 'warning',
                    title: 'Invalid Start',
                    text: 'Please enter a valid starting number.',
                });
                $('#startNumber').focus();
                return;
            }
            
            if (isNaN(increment) || increment < 1) {
                Swal.fire({
                    icon: 'warning',
                    title: 'Invalid Increment',
                    text: 'Please enter a valid increment value.',
                });
                $('#incrementBy').focus();
                return;
            }
            
            var counter = start;
            var lastSectionId = null;
            var generatedCount = 0;
            
            $('.symbol-input').each(function() {
                var $input = $(this);
                var sectionId = $input.data('section-id');
                
                // Reset counter if needed
                if (resetOption === 'section' && sectionId !== lastSectionId) {
                    counter = start;
                    lastSectionId = sectionId;
                }
                
                // Only fill if empty
                if (!$input.val().trim()) {
                    $input.val(counter);
                    $input.removeClass('empty').addClass('assigned');
                    generatedCount++;
                    counter += increment;
                }
            });
            
            Swal.fire({
                icon: 'success',
                title: 'Auto Generated!',
                text: 'Generated ' + generatedCount + ' symbol number(s)',
                timer: 2000,
                showConfirmButton: false
            });
            
            // Update summary
            updateTableSummary();
        });
        
        // Clear all symbol inputs
        $('#clearAllBtn').click(function() {
            Swal.fire({
                title: 'Clear All?',
                text: "This will clear all symbol number inputs. Are you sure?",
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#3085d6',
                cancelButtonColor: '#d33',
                confirmButtonText: 'Yes, clear all!',
                cancelButtonText: 'Cancel'
            }).then((result) => {
                if (result.isConfirmed) {
                    $('.symbol-input').val('').removeClass('assigned').addClass('empty');
                    Swal.fire({
                        icon: 'success',
                        title: 'Cleared!',
                        text: 'All symbol numbers have been cleared.',
                        timer: 1500,
                        showConfirmButton: false
                    });
                    updateTableSummary();
                }
            });
        });
        
       // Save all symbol numbers - UPDATED VERSION
$('#saveAllBtn').click(function() {
    var examId = $('#exam_type').val();
    var classId = $('#class_id').val();
    
    if (!examId || !classId) {
        Swal.fire({
            icon: 'warning',
            title: 'Missing Information',
            text: 'Please select exam and class first.',
        });
        return;
    }
    
    // Collect data
    var symbolData = [];
    var emptyCount = 0;
    
    $('.symbol-input').each(function() {
        var $input = $(this);
        var symbolNumber = $input.val().trim();
        
        if (!symbolNumber) {
            emptyCount++;
            $input.addClass('is-invalid');
        } else {
            $input.removeClass('is-invalid');
            
            symbolData.push({
                studentId: $input.data('student-id'),
                classId: $input.data('class-id'),
                sectionId: $input.data('section-id'),
                symbolNumber: symbolNumber
            });
        }
    });
    
    // Check for empty fields
    if (emptyCount > 0) {
        Swal.fire({
            icon: 'warning',
            title: 'Incomplete Data',
            html: 'Please fill all symbol numbers before saving.<br>' +
                  'Found ' + emptyCount + ' empty field(s).',
        });
        return;
    }
    
    // Check for duplicates
    var symbolNumbers = symbolData.map(item => item.symbolNumber);
    var uniqueSymbols = [...new Set(symbolNumbers)];
    if (uniqueSymbols.length !== symbolNumbers.length) {
        Swal.fire({
            icon: 'warning',
            title: 'Duplicate Symbols Found',
            text: 'Some symbol numbers appear more than once. Please ensure all symbols are unique.',
            showCancelButton: true,
            confirmButtonText: 'Continue Anyway',
            cancelButtonText: 'Cancel'
        }).then((result) => {
            if (result.isConfirmed) {
                proceedWithSave(examId, symbolData);
            }
        });
    } else {
        proceedWithSave(examId, symbolData);
    }
});

// Separate function for the save operation
function proceedWithSave(examId, symbolData) {
    Swal.fire({
        title: 'Save Symbol Numbers?',
        html: 'This will save ' + symbolData.length + ' symbol number(s).<br>' +
              '<strong>This action cannot be undone!</strong>',
        icon: 'question',
        showCancelButton: true,
        confirmButtonColor: '#3085d6',
        cancelButtonColor: '#d33',
        confirmButtonText: 'Yes, save them!',
        cancelButtonText: 'Cancel',
        showLoaderOnConfirm: true,
        allowOutsideClick: () => !Swal.isLoading()
    }).then((result) => {
        if (result.isConfirmed) {
            // Show loading state
            Swal.fire({
                title: 'Saving...',
                text: 'Please wait while we save the symbol numbers',
                allowOutsideClick: false,
                didOpen: () => {
                    Swal.showLoading();
                }
            });
            
            // Create FormData for sending
            var formData = new FormData();
            formData.append('symbolData', JSON.stringify(symbolData));
            formData.append('exam_id', examId);
            
            // Send AJAX request
            $.ajax({
                url: 'ajax/save_symbol_number.php',
                type: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                dataType: 'json',
                success: function(response) {
                    console.log('Save response:', response);
                    
                    if (response.success) {
                        Swal.fire({
                            icon: 'success',
                            title: 'Success!',
                            html: '<strong>' + response.message + '</strong><br><br>' +
                                  'Total Records: ' + response.total_records + '<br>' +
                                  'Successfully Saved: ' + response.success_count + '<br>' +
                                  (response.error_count > 0 ? 'Errors: ' + response.error_count + '<br>' : '') +
                                  (response.duplicate_count > 0 ? 'Duplicates: ' + response.duplicate_count + '<br>' : ''),
                            showConfirmButton: true,
                            confirmButtonText: 'OK'
                        }).then(() => {
                            // Refresh the table
                            if (typeof studentsTable !== 'undefined' && studentsTable) {
                                studentsTable.destroy();
                            }
                            $('#fetchStudents').click();
                        });
                    } else {
                        var errorMsg = response.message || 'Unknown error occurred';
                        if (response.errors && response.errors.length > 0) {
                            errorMsg += '<br><br>Errors:<br>' + 
                                        response.errors.slice(0, 5).join('<br>');
                            if (response.errors.length > 5) {
                                errorMsg += '<br>... and ' + (response.errors.length - 5) + ' more';
                            }
                        }
                        
                        Swal.fire({
                            icon: 'error',
                            title: 'Save Failed',
                            html: errorMsg,
                            showConfirmButton: true
                        });
                    }
                },
                error: function(xhr, status, error) {
                    console.error('AJAX Error:', error, xhr.responseText);
                    Swal.fire({
                        icon: 'error',
                        title: 'Request Failed',
                        html: 'Failed to save symbol numbers.<br>' +
                              'Error: ' + error + '<br>' +
                              'Status: ' + xhr.status,
                        showConfirmButton: true
                    });
                }
            });
        }
    });
}
        
        // Update table summary function
        function updateTableSummary() {
            var assigned = 0;
            var total = $('.symbol-input').length;
            
            $('.symbol-input').each(function() {
                if ($(this).val().trim()) {
                    assigned++;
                }
            });
            
            $('#assignedCount').text(assigned);
            $('#pendingCount').text(total - assigned);
        }
        
        // Real-time input validation
        $(document).on('input', '.symbol-input', function() {
            var $input = $(this);
            var value = $input.val().trim();
            
            if (value === '') {
                $input.removeClass('assigned is-valid is-invalid').addClass('empty');
            } else if (/^\d+$/.test(value)) {
                $input.removeClass('empty is-invalid').addClass('assigned is-valid');
            } else {
                $input.removeClass('assigned is-valid').addClass('empty is-invalid');
            }
            
            updateTableSummary();
        });
    });
    </script>
</body>
</html>