<?php
// marksentry_all.php
include('includes/db.php');
session_start();

$message = '';
$student_list = [];

// Get current teacher if logged in as teacher
$current_teacher_id = $_SESSION['teacher_id'] ?? 0;
$current_teacher_name = $_SESSION['teacher_name'] ?? '';
$current_user_id = $_SESSION['user_id'] ?? $current_teacher_id;

// Get all classes for dropdown
$classes_query = "SELECT class_id, class FROM classes WHERE status = 1 ORDER BY class_numeric";
$classes_result = $conn->query($classes_query);

// Get all sections for checkbox display
$sections_query = "SELECT section_id, section_name FROM sections WHERE status = 1 ORDER BY section_name";
$sections_result = $conn->query($sections_query);

// Get exams for dropdown
$exams_query = "SELECT id, exam_type, exm_year FROM examination_type ORDER BY id DESC";
$exams_result = $conn->query($exams_query);
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes">
    <title>Student Marks Entry</title>
    <link rel="stylesheet" href="css/bootstrap.min.css">
    <link rel="stylesheet" href="css/font-awesome.min.css">
    <link rel="stylesheet" href="css/select2/select2.min.css">
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <script src="js/jquery/jquery-2.2.4.min.js"></script>
    <script src="js/bootstrap/bootstrap.min.js"></script>
    <script src="js/select2/select2.min.js"></script>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body { background-color: #f0f2f5; font-size: 14px; font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; padding: 15px; }
        .container-fluid { max-width: 1600px; margin: 0 auto; }
        .card { border: none; border-radius: 12px; box-shadow: 0 2px 8px rgba(0,0,0,0.08); background: white; margin-bottom: 20px; }
        .card-header { background: linear-gradient(135deg, #2c3e50, #1a4d8c); color: white; padding: 15px 20px; border-radius: 12px 12px 0 0; }
        .card-header h4 { margin: 0; font-size: 18px; font-weight: 600; }
        .card-body { padding: 25px; }
        .form-label { font-size: 13px; font-weight: 600; color: #2c3e50; margin-bottom: 6px; display: block; }
        .form-control, .form-select { height: 40px; font-size: 14px; border: 1px solid #d2d6dc; border-radius: 8px; padding: 6px 12px; width: 100%; }
        .select2-container { width: 100% !important; }
        .select2-container .select2-selection--single { height: 40px !important; border: 1px solid #d2d6dc !important; border-radius: 8px !important; }
        .sections-grid { display: flex; flex-wrap: wrap; gap: 12px; background: #f8f9fa; padding: 12px 15px; border-radius: 8px; border: 1px solid #e9ecef; min-height: 50px; }
        .section-checkbox { display: inline-flex; align-items: center; gap: 6px; background: white; padding: 6px 12px; border-radius: 20px; border: 1px solid #d2d6dc; cursor: pointer; transition: all 0.2s; }
        .section-checkbox.selected { background: #3498db; border-color: #3498db; }
        .section-checkbox.selected label { color: white; }
        .selection-row { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 15px; margin-bottom: 20px; }
        .stats-grid { display: grid; grid-template-columns: repeat(4, 1fr); gap: 15px; margin-bottom: 20px; }
        .stat-card { background: white; border: 1px solid #e9ecef; border-radius: 12px; padding: 15px; text-align: center; transition: all 0.2s; }
        .stat-card:hover { transform: translateY(-2px); box-shadow: 0 4px 12px rgba(0,0,0,0.1); }
        .stat-number { font-size: 28px; font-weight: 700; color: #2c3e50; }
        .stat-label { font-size: 12px; color: #7f8c8d; text-transform: uppercase; margin-top: 5px; }
        .search-controls { display: flex; flex-wrap: wrap; gap: 15px; margin-bottom: 20px; align-items: center; }
        .search-input { flex: 2; min-width: 250px; }
        .search-input input { width: 100%; height: 38px; padding: 8px 12px; border: 1px solid #d2d6dc; border-radius: 8px; }
        .btn { padding: 8px 16px; font-size: 13px; font-weight: 500; border-radius: 8px; display: inline-flex; align-items: center; gap: 6px; cursor: pointer; transition: all 0.2s; border: none; }
        .btn-primary { background: #3498db; color: white; }
        .btn-primary:hover:not(:disabled) { background: #2980b9; transform: translateY(-1px); }
        .btn-primary:disabled { background: #bdc3c7; cursor: not-allowed; }
        .btn-outline-danger { background: white; border: 1px solid #e74c3c; color: #e74c3c; }
        .btn-outline-danger:hover { background: #e74c3c; color: white; }
        .btn-outline-secondary { background: white; border: 1px solid #95a5a6; color: #7f8c8d; }
        .btn-outline-secondary:hover { background: #95a5a6; color: white; }
        .table-container { overflow-x: auto; border-radius: 12px; border: 1px solid #e9ecef; background: white; margin-bottom: 20px; max-height: 60vh; overflow-y: auto; }
        .table { width: 100%; border-collapse: collapse; font-size: 13px; min-width: 600px; }
        .table th { background: #f8f9fa; padding: 12px 10px; font-weight: 600; border-bottom: 2px solid #e9ecef; cursor: pointer; position: sticky; top: 0; z-index: 10; }
        .table td { padding: 10px; border-bottom: 1px solid #e9ecef; vertical-align: middle; }
        .marks-input { width: 85px; text-align: center; padding: 6px 8px; border: 1px solid #d2d6dc; border-radius: 6px; }
        .marks-input.locked { background: #e8f4fd; border-color: #3498db; color: #2c3e50; cursor: not-allowed; }
        .badge { display: inline-block; padding: 4px 10px; border-radius: 20px; font-size: 11px; font-weight: 500; }
        .badge-success { background: #d4edda; color: #155724; }
        .badge-warning { background: #fff3cd; color: #856404; }
        .badge-info { background: #d1ecf1; color: #0c5460; }
        .loading-overlay { position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(255,255,255,0.95); z-index: 9999; display: none; justify-content: center; align-items: center; flex-direction: column; }
        .loading-spinner { width: 50px; height: 50px; border: 4px solid #e9ecef; border-top-color: #3498db; border-radius: 50%; animation: spin 0.8s linear infinite; }
        @keyframes spin { to { transform: rotate(360deg); } }
        .pagination { display: flex; justify-content: center; gap: 5px; margin-top: 20px; flex-wrap: wrap; }
        .pagination button { padding: 6px 12px; border: 1px solid #d2d6dc; background: white; border-radius: 6px; cursor: pointer; }
        .pagination button.active { background: #3498db; color: white; border-color: #3498db; }
        @media (max-width: 768px) { .stats-grid { grid-template-columns: repeat(2, 1fr); } .selection-row { grid-template-columns: 1fr; } .marks-input { width: 70px; } }
    </style>
</head>
<body>

<div class="container-fluid">
    <div id="loadingOverlay" class="loading-overlay">
        <div class="loading-spinner"></div>
        <p style="margin-top: 15px;">Processing...</p>
    </div>
    
    <div class="card">
        <div class="card-header">
            <h4><i class="fa fa-edit"></i> Student Marks Entry</h4>
        </div>
        <div class="card-body">
            
            <!-- Selection Form -->
            <div class="selection-row">
                <div class="form-group">
                    <label class="form-label">Marks Type *</label>
                    <select id="mark_type" class="form-select" required>
                        <option value="">Select Type</option>
                        <option value="theory">Theory</option>
                        <option value="practical">Practical/Internal</option>
                    </select>
                </div>

                <div class="form-group">
                    <label class="form-label">Class *</label>
                    <select id="class_id" class="form-select" required>
                        <option value="">Select Class</option>
                        <?php while($row = $classes_result->fetch_assoc()): ?>
                            <option value="<?= $row['class_id'] ?>"><?= htmlspecialchars($row['class']) ?></option>
                        <?php endwhile; ?>
                    </select>
                </div>
                
                <div class="form-group">
                    <label class="form-label">Exam *</label>
                    <select id="exam_id" class="form-select" disabled required>
                        <option value="">Select Exam</option>
                        <?php while($row = $exams_result->fetch_assoc()): ?>
                            <option value="<?= $row['id'] ?>"><?= htmlspecialchars($row['exam_type']) ?> (<?= $row['exm_year'] ?>)</option>
                        <?php endwhile; ?>
                    </select>
                </div>
                
                <div class="form-group">
                    <label class="form-label">Subject *</label>
                    <select id="subject_id" class="form-select" disabled required>
                        <option value="">Select Subject</option>
                    </select>
                </div>
                
                <div class="form-group">
                    <label class="form-label">Teacher *</label>
                    <select id="teacher_id" class="form-select" required>
                        <option value="">Select Teacher</option>
                        <?php 
                        $tQ = $conn->query("SELECT teacher_id, name FROM teachers WHERE role = 'Teacher' AND status='Active' ORDER BY name");
                        while($t = $tQ->fetch_assoc()){
                            $selected = ($current_teacher_id == $t['teacher_id']) ? 'selected' : '';
                            echo "<option value='{$t['teacher_id']}' $selected>{$t['name']}</option>";
                        }
                        ?>
                    </select>
                </div>
            </div>
            
            <!-- Sections Section with Checkboxes -->
            <div class="form-group mb-3">
                <label class="form-label">Select Sections <small>(Check to include, leave all unchecked for ALL sections)</small></label>
                <div id="sectionsContainer" class="sections-grid">
                    <?php 
                    $sections_result->data_seek(0);
                    while($row = $sections_result->fetch_assoc()): ?>
                        <div class="section-checkbox" data-section-id="<?= $row['section_id'] ?>">
                            <input type="checkbox" id="section_<?= $row['section_id'] ?>" value="<?= $row['section_id'] ?>">
                            <label for="section_<?= $row['section_id'] ?>"><?= htmlspecialchars($row['section_name']) ?></label>
                        </div>
                    <?php endwhile; ?>
                </div>
                <small class="text-muted mt-1 d-block">Leave all unchecked to load students from ALL sections</small>
            </div>
            
            <!-- Load Button -->
            <div class="text-center mb-4">
                <button type="button" id="loadStudentsBtn" class="btn btn-primary btn-lg px-5" disabled>
                    <i class="fa fa-search"></i> Load Students
                </button>
            </div>
            
            <!-- Student List Section -->
            <div id="studentSection" style="display: none;">
                <div class="stats-grid" id="statsGrid">
                    <div class="stat-card"><div class="stat-number" id="totalStudents">0</div><div class="stat-label">Total Students</div></div>
                    <div class="stat-card"><div class="stat-number" id="enteredCount">0</div><div class="stat-label">Marks Entered</div></div>
                    <div class="stat-card"><div class="stat-number" id="pendingCount">0</div><div class="stat-label">Pending</div></div>
                    <div class="stat-card"><div class="stat-number" id="fullMarks">0</div><div class="stat-label">Full Marks</div></div>
                </div>
                
                <div class="search-controls">
                    <div class="search-input"><input type="text" id="searchInput" placeholder="Search by name, symbol..."></div>
                    <div class="filter-select"><select id="sectionFilter" class="form-select"><option value="">All Sections</option></select></div>
                    <div class="action-buttons">
                        <button type="button" id="clearAllBtn" class="btn btn-outline-danger btn-sm"><i class="fa fa-trash"></i> Clear All</button>
                        <button type="button" id="reloadBtn" class="btn btn-outline-secondary btn-sm"><i class="fa fa-refresh"></i> Reload</button>
                    </div>
                </div>
                
                <form method="POST" id="marksForm" action="process_marks.php">
                    <div class="table-container">
                        <table class="table" id="studentsTable">
                            <thead>
                                 <tr>
                                    <th data-sort="sn" width="5%">S.N.</th>
                                    <th data-sort="symbol" width="12%">Symbol No.</th>
                                    <th data-sort="section" width="10%">Section</th>
                                    <th data-sort="name" width="40%">Student Name</th>
                                    <!-- <th data-sort="regd" width="12%">Regd No.</th> -->
                                    <th data-sort="marks" width="12%">Marks</th>
                                    <th data-sort="status" width="8%">Status</th>
                                    <th width="11%">Remarks</th>
                                   </tr>
                            </thead>
                            <tbody id="studentsBody">
                                 <tr><td colspan="8" class="text-center text-muted">Select parameters and click Load</td></tr>
                            </tbody>
                        </table>
                    </div>
                    <input type="hidden" name="class_id" id="hidden_class_id">
                    <input type="hidden" name="exam_id" id="hidden_exam_id">
                    <input type="hidden" name="subject_id" id="hidden_subject_id">
                    <input type="hidden" name="mark_type" id="hidden_mark_type">
                    <input type="hidden" name="teacher_id" id="hidden_teacher_id">
                    <input type="hidden" name="entered_by" id="hidden_entered_by">
                    <input type="hidden" name="full_marks" id="hidden_full_marks">
                    <input type="hidden" name="section_ids" id="hidden_section_ids">
                    <div class="text-center mt-4"><button type="submit" name="save_marks" class="btn btn-primary btn-lg px-5"><i class="fa fa-save"></i> Save Marks</button></div>
                </form>
                <div id="pagination" class="pagination"></div>
            </div>
        </div>
    </div>
</div>

<script>
$(document).ready(function() {
    // Initialize select2
    $('select').select2({ theme: 'bootstrap', width: '100%', placeholder: 'Select', allowClear: true });
    
    let allStudents = [];
    let filteredStudents = [];
    let rowsPerPage = 50;
    let currentPage = 1;
    let currentSort = { column: 'symbol', direction: 'asc' };
    let currentSectionFilter = '';
    let currentSearchTerm = '';
    
    // Section checkbox styling
    $('.section-checkbox input').on('change', function() {
        $(this).closest('.section-checkbox').toggleClass('selected', $(this).is(':checked'));
        checkLoadButton();
    });
    
    function getSelectedSections() { 
        let selected = []; 
        $('.section-checkbox input:checked').each(function() { 
            selected.push($(this).val()); 
        }); 
        return selected; 
    }
    
    // Load subjects based on class
    $('#class_id').change(function() {
        let classId = $(this).val();
        let subjectSelect = $('#subject_id');
        
        subjectSelect.html('<option value="">Loading...</option>').prop('disabled', true);
        if(classId) {
            $.ajax({
                url: 'ajax/get_all_subjects_by_class.php', 
                type: 'POST', 
                data: { class_id: classId }, 
                dataType: 'json',
                success: function(data) {
                    let options = '<option value="">Select Subject</option>';
                    if(data.success && data.subjects.length > 0) {
                        data.subjects.forEach(function(subject) {
                            options += `<option value="${subject.id}" data-code="${subject.subject_code}" data-theory="${subject.theory_full_marks}" data-internal="${subject.internal_full_marks}">${subject.subject_name} (${subject.subject_code})</option>`;
                        });
                    }
                    subjectSelect.html(options).prop('disabled', false);
                },
                error: function() { 
                    subjectSelect.html('<option value="">Error loading subjects</option>').prop('disabled', false);
                    Swal.fire('Error', 'Failed to load subjects', 'error');
                }
            });
            $('#exam_id').prop('disabled', false);
        } else { 
            subjectSelect.html('<option value="">Select Subject</option>').prop('disabled', true); 
            $('#exam_id').prop('disabled', true); 
        }
        checkLoadButton();
    });
    
    function checkLoadButton() {
        let enabled = $('#class_id').val() && $('#exam_id').val() && $('#subject_id').val() && $('#mark_type').val() && $('#teacher_id').val();
        $('#loadStudentsBtn').prop('disabled', !enabled);
    }
    
    $('#exam_id, #subject_id, #mark_type, #teacher_id').change(checkLoadButton);
    
    // Load students
    $('#loadStudentsBtn').click(function() {
        let classId = $('#class_id').val();
        let sectionIds = getSelectedSections();
        let examId = $('#exam_id').val();
        let subjectId = $('#subject_id').val();
        let markType = $('#mark_type').val();
        let teacherId = $('#teacher_id').val();
        
        if(!classId || !examId || !subjectId || !markType || !teacherId) {
            Swal.fire('Error', 'Please select all required fields', 'warning');
            return;
        }
        
        // Set hidden fields
        $('#hidden_class_id').val(classId);
        $('#hidden_exam_id').val(examId);
        $('#hidden_subject_id').val(subjectId);
        $('#hidden_mark_type').val(markType);
        $('#hidden_teacher_id').val(teacherId);
        $('#hidden_entered_by').val(teacherId); // Set entered_by to teacher_id
        $('#hidden_section_ids').val(sectionIds.join(','));
        
        let selectedSubject = $('#subject_id option:selected');
        let fullMarks = (markType === 'theory') ? (selectedSubject.data('theory') || 0) : (selectedSubject.data('internal') || 0);
        $('#fullMarks').text(fullMarks);
        $('#hidden_full_marks').val(fullMarks);
        window.fullMarks = fullMarks;
        
        $('#loadingOverlay').show(); 
        $('#studentSection').hide();
        
        $.ajax({
            url: 'ajax/get_all_students_list.php', 
            type: 'POST',
            data: { 
                class_id: classId, 
                section_ids: sectionIds, 
                exam_id: examId, 
                subject_id: subjectId, 
                subject_code: selectedSubject.data('code'), 
                mark_type: markType 
            },
            dataType: 'json',
            success: function(response) {
                $('#loadingOverlay').hide();
                console.log('Response received:', response);
                
                if(response.success) {
                    allStudents = response.students;
                    filteredStudents = [...allStudents];
                    
                    $('#totalStudents').text(allStudents.length); 
                    $('#studentSection').show();
                    
                    // Show success message
                    Swal.fire({
                        icon: 'success',
                        title: 'Success!',
                        text: `Loaded ${allStudents.length} students successfully`,
                        timer: 2000,
                        showConfirmButton: false
                    });
                    
                    updateSectionFilter();
                    sortData('symbol', 'asc');
                    renderTable();
                } else { 
                    Swal.fire('Error', response.message || 'Failed to load students', 'error');
                }
            },
            error: function(xhr, status, error) { 
                $('#loadingOverlay').hide(); 
                console.error('AJAX Error:', error, xhr.responseText);
                Swal.fire('Error', 'Failed to load students. Please try again.', 'error');
            }
        });
    });
    
    // Update section filter dropdown
    function updateSectionFilter() {
        let sections = {};
        allStudents.forEach(student => {
            if(student.section_name && student.section_name !== 'N/A') {
                sections[student.section_name] = student.section_name;
            }
        });
        
        let options = '<option value="">All Sections</option>';
        Object.keys(sections).sort().forEach(section => {
            options += `<option value="${section}">${section}</option>`;
        });
        $('#sectionFilter').html(options);
        currentSectionFilter = '';
        $('#sectionFilter').val('');
    }
    
    // Sort data
    function sortData(column, direction) {
        filteredStudents.sort((a, b) => {
            let aVal, bVal;
            switch(column) {
                case 'symbol': aVal = a.symbol_no || ''; bVal = b.symbol_no || ''; break;
                case 'name': aVal = a.name || ''; bVal = b.name || ''; break;
                case 'regd': aVal = a.registration_no || a.regd_id || ''; bVal = b.registration_no || b.regd_id || ''; break;
                case 'marks': aVal = parseFloat(a.existing_mark) || 0; bVal = parseFloat(b.existing_mark) || 0; break;
                default: aVal = a.symbol_no || ''; bVal = b.symbol_no || '';
            }
            if(typeof aVal === 'number') return direction === 'asc' ? aVal - bVal : bVal - aVal;
            aVal = String(aVal).toLowerCase(); bVal = String(bVal).toLowerCase();
            if(aVal < bVal) return direction === 'asc' ? -1 : 1;
            if(aVal > bVal) return direction === 'asc' ? 1 : -1;
            return 0;
        });
    }
    
    // Render table
    function renderTable() {
        let filtered = [...filteredStudents];
        
        // Apply section filter
        if(currentSectionFilter) {
            filtered = filtered.filter(student => student.section_name === currentSectionFilter);
        }
        
        // Apply search
        if(currentSearchTerm) {
            filtered = filtered.filter(student => 
                student.name.toLowerCase().includes(currentSearchTerm) ||
                (student.symbol_no && student.symbol_no.toString().toLowerCase().includes(currentSearchTerm)) ||
                (student.registration_no && student.registration_no.toString().toLowerCase().includes(currentSearchTerm))
            );
        }
        
        // Pagination
        let totalPages = Math.ceil(filtered.length / rowsPerPage);
        if(totalPages === 0) totalPages = 1;
        if(currentPage > totalPages) currentPage = 1;
        let start = (currentPage - 1) * rowsPerPage;
        let pageStudents = filtered.slice(start, start + rowsPerPage);
        
        // Build table HTML
        let html = '';
        if(pageStudents.length === 0) {
            html = '<tr><td colspan="8" class="text-center text-muted">No students found</td></tr>';
        } else {
            pageStudents.forEach((student, idx) => {
                let globalIndex = start + idx + 1;
                let markValue = (student.existing_mark !== null && student.existing_mark !== undefined && student.existing_mark !== '') ? student.existing_mark : '';
                let hasMarks = markValue !== '' && !isNaN(parseFloat(markValue)) && parseFloat(markValue) > 0;
                
                html += `<tr data-student-id="${student.student_id}">`;
                html += `<td class="text-center">${globalIndex}</td>`;
                html += `<td class="text-center">${escapeHtml(student.symbol_no || '-')}</td>`;
                html += `<td class="text-center"><span class="badge badge-info">${escapeHtml(student.section_name || '-')}</span></td>`;
                html += `<td><strong>${escapeHtml(student.name)}</strong><br><small class="text-muted">Sym. No.: ${escapeHtml(student.symbol_no || '')}</small></td>`;
          
                html += `<td class="text-center">
                            <input type="number" name="marks[${student.student_id}]" 
                                   class="marks-input ${hasMarks ? 'locked' : ''}" 
                                   value="${escapeHtml(markValue)}" 
                                   step="0.01" min="0" max="${window.fullMarks}" 
                                   data-student-id="${student.student_id}" 
                                   ${hasMarks ? 'readonly' : ''} 
                                   style="width:85px;text-align:center;">
                            <div><small class="text-muted">Max: ${window.fullMarks}</small></div>
                           </td>`;
                html += `<td class="text-center">`;
                if(hasMarks) {
                    html += `<span class="badge badge-success"><i class="fa fa-check"></i> Entered</span>`;
                } else {
                    html += `<span class="badge badge-warning"><i class="fa fa-clock-o"></i> Pending</span>`;
                }
                html += `</td>`;
                html += `<td class="text-center">
                            <input type="text" name="remarks[${student.student_id}]" 
                                   class="form-control form-control-sm" 
                                   placeholder="Remark" 
                                   style="width:100px;" 
                                   value="${escapeHtml(student.remarks || '')}">
                           </td>`;
                html += `</tr>`;
            });
        }
        
        $('#studentsBody').html(html);
        
        // Add input event listeners for unlocked fields
        $('.marks-input:not([readonly])').on('input', function() {
            let value = $(this).val();
            let $row = $(this).closest('tr');
            let $badge = $row.find('.badge');
            
            if(value === '') {
                $badge.removeClass('badge-success').addClass('badge-warning')
                      .html('<i class="fa fa-clock-o"></i> Pending');
            } else if(!isNaN(value) && parseFloat(value) >= 0 && parseFloat(value) <= window.fullMarks) {
                if(parseFloat(value) === 0) {
                    $badge.removeClass('badge-success').addClass('badge-warning')
                          .html('<i class="fa fa-user-times"></i> Absent');
                } else {
                    $badge.removeClass('badge-warning').addClass('badge-success')
                          .html('<i class="fa fa-check"></i> Entered');
                }
            } else {
                $badge.removeClass('badge-success badge-warning').addClass('badge-secondary')
                      .html('<i class="fa fa-exclamation-triangle"></i> Invalid');
            }
            updateStats();
        });
        
        // Update statistics
        updateStats();
        
        // Update pagination
        updatePagination(totalPages);
    }
    
    // Update statistics
    function updateStats() {
        let entered = 0, pending = 0;
        $('.marks-input').each(function() {
            let val = $(this).val();
            if(val && !isNaN(val) && parseFloat(val) >= 0 && parseFloat(val) <= window.fullMarks) {
                if(parseFloat(val) > 0) entered++; else pending++;
            } else pending++;
        });
        $('#enteredCount').text(entered); 
        $('#pendingCount').text(pending);
    }
    
    // Update pagination
    function updatePagination(totalPages) {
        if(totalPages <= 1) { 
            $('#pagination').empty(); 
            return; 
        }
        let html = `<button onclick="changePage(${currentPage-1})" ${currentPage===1?'disabled':''}>&laquo; Prev</button>`;
        let startPage = Math.max(1, currentPage-2), endPage = Math.min(totalPages, startPage+4);
        for(let i=startPage; i<=endPage; i++) {
            html += `<button onclick="changePage(${i})" class="${i===currentPage?'active':''}">${i}</button>`;
        }
        html += `<button onclick="changePage(${currentPage+1})" ${currentPage===totalPages?'disabled':''}>Next &raquo;</button>`;
        $('#pagination').html(html);
    }
    
    window.changePage = function(page) { 
        currentPage = page; 
        renderTable(); 
    };
    
    // Search functionality
    $('#searchInput').on('input', function() { 
        currentSearchTerm = $(this).val().toLowerCase(); 
        currentPage = 1; 
        renderTable(); 
    });
    
    // Section filter
    $('#sectionFilter').on('change', function() { 
        currentSectionFilter = $(this).val(); 
        currentPage = 1; 
        renderTable(); 
    });
    
    // Table sorting
    $('th[data-sort]').click(function() {
        let col = $(this).data('sort');
        if(currentSort.column === col) {
            currentSort.direction = currentSort.direction === 'asc' ? 'desc' : 'asc';
        } else { 
            currentSort.column = col; 
            currentSort.direction = 'asc'; 
        }
        sortData(currentSort.column, currentSort.direction); 
        currentPage = 1; 
        renderTable();
    });
    
    // Clear all marks
    $('#clearAllBtn').click(function() {
        Swal.fire({
            title: 'Clear All Marks?',
            text: 'This will clear all entered marks in this form.',
            icon: 'warning',
            showCancelButton: true,
            confirmButtonText: 'Yes, clear all',
            cancelButtonText: 'Cancel'
        }).then((result) => {
            if(result.isConfirmed) {
                $('.marks-input:not([readonly])').val('').trigger('input');
                $('input[name^="remarks"]').val('');
                Swal.fire('Cleared!', 'All marks have been cleared.', 'success');
            }
        });
    });
    
    // Reload students
    $('#reloadBtn').click(() => $('#loadStudentsBtn').click());
    
    // Escape HTML
    function escapeHtml(text) {
        if(text === null || text === undefined || text === '') return '-';
        return String(text).replace(/[&<>]/g, function(m) {
            if(m === '&') return '&amp;';
            if(m === '<') return '&lt;';
            if(m === '>') return '&gt;';
            return m;
        });
    }
    
    // Form submission with SweetAlert2
$('#marksForm').submit(function(e) {
    e.preventDefault();
    
    // Make sure teacher_id is set
    let teacherId = $('#teacher_id').val();
    if(!teacherId) {
        Swal.fire('Error', 'Please select a teacher', 'warning');
        return;
    }
    
    // Update hidden fields
    $('#hidden_teacher_id').val(teacherId);
    $('#hidden_entered_by').val(teacherId);
    
    // Check if any marks entered
    let hasMarks = false;
    $('.marks-input').each(function() {
        if($(this).val() !== '') hasMarks = true;
    });
    
    if(!hasMarks) {
        Swal.fire('Warning', 'No marks entered to save', 'warning');
        return;
    }
    
    // Validate all marks
    let invalidMarks = [];
    $('.marks-input').each(function() {
        let val = $(this).val();
        if(val !== '' && (isNaN(val) || parseFloat(val) < 0 || parseFloat(val) > window.fullMarks)) {
            let studentName = $(this).closest('tr').find('td:eq(3)').text().trim();
            invalidMarks.push(studentName);
        }
    });
    
    if(invalidMarks.length > 0) {
        Swal.fire({
            icon: 'error',
            title: 'Invalid Marks',
            html: `Invalid marks for:<br>${invalidMarks.slice(0, 5).join('<br>')}${invalidMarks.length > 5 ? '<br>... and ' + (invalidMarks.length - 5) + ' more' : ''}`,
            confirmButtonText: 'OK'
        });
        return;
    }
    
    // Show loading
    Swal.fire({
        title: 'Saving Marks...',
        text: 'Please wait while we save the marks',
        allowOutsideClick: false,
        showConfirmButton: false,
        willOpen: () => { Swal.showLoading(); }
    });
    
    // Submit form via AJAX
    $.ajax({
        url: 'process_marks.php',
        type: 'POST',
        data: $(this).serialize(),
        dataType: 'json',
        success: function(response) {
            Swal.close();
            
            // Handle the response with appropriate icon
            let icon = response.icon || (response.success ? 'success' : 'error');
            let title = response.title || (response.success ? 'Success!' : 'Error!');
            let message = response.message;
            
            // If there are details, add them
            if(response.details) {
                let details = [];
                if(response.details.inserted > 0) details.push(`${response.details.inserted} inserted`);
                if(response.details.updated > 0) details.push(`${response.details.updated} updated`);
                if(response.details.skipped > 0) details.push(`${response.details.skipped} unchanged`);
                if(response.details.duplicates > 0) details.push(`${response.details.duplicates} duplicates`);
                if(details.length) message += ` (${details.join(', ')})`;
            }
            
            Swal.fire({
                icon: icon,
                title: title,
                text: message,
                confirmButtonText: 'OK',
                timer: icon === 'success' ? 3000 : null,
                showConfirmButton: true
            });
            
            // Reload students to reflect changes
            if(response.success) {
                setTimeout(() => { $('#loadStudentsBtn').click(); }, 1000);
            }
        },
        error: function(xhr, status, error) {
            Swal.close();
            Swal.fire({
                icon: 'error',
                title: 'Error',
                text: 'Failed to save marks. Please try again.',
                confirmButtonText: 'OK'
            });
            console.error('AJAX Error:', error, xhr.responseText);
        }
    });
});
    // Keyboard navigation
    let currentInputIndex = -1;
    
    $(document).on('keydown', function(e) {
        if(e.key === 'w' || e.key === 'W') { e.preventDefault(); navigateInput('up'); }
        else if(e.key === 's' || e.key === 'S') { e.preventDefault(); navigateInput('down'); }
    });
    
    function navigateInput(d) {
        let inputs = $('.marks-input:not([readonly]):visible');
        if(inputs.length === 0) return;
        
        inputs.removeClass('highlight');
        if(currentInputIndex === -1) currentInputIndex = 0;
        else currentInputIndex = d === 'up' ? Math.max(0, currentInputIndex-1) : Math.min(inputs.length-1, currentInputIndex+1);
        
        let target = inputs.eq(currentInputIndex);
        target.focus().addClass('highlight');
        
        let pos = target.offset().top, scroll = $(window).scrollTop();
        if(pos < scroll || pos > scroll + $(window).height() - 100) {
            $('html, body').animate({ scrollTop: pos - 100 }, 200);
        }
    }
});
</script>
</body>
</html>