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

// Button status
$btnQ = $conn->query("SELECT feature,status FROM button_setting");
$buttonStatus = [];
while($b = $btnQ->fetch_assoc()){
    $buttonStatus[$b['feature']] = $b['status'];
}

// Get current teacher if logged in as teacher
$teacher_id = $_SESSION['teacher_id'] ?? '';
$teacher_name = $_SESSION['teacher_name'] ?? '';
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Enter Marks</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/select2/select2.min.css">
<link rel="stylesheet" href="css/main.css" media="screen">
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<style>
    /* Minimal CSS */
    body {
        background-color: #f5f7fa;
        font-size: 13px;
        padding: 10px 0;
    }
    
    .card {
        border: none;
        border-radius: 8px;
        box-shadow: 0 2px 4px rgba(0,0,0,0.08);
    }
    
    .card-header {
        background: #4e73df;
        color: white;
        padding: 12px 15px;
        border-radius: 8px 8px 0 0 !important;
    }
    
    .card-header h4 {
        font-size: 16px;
        margin: 0;
        font-weight: 600;
    }
    
    .form-label {
        font-size: 12px;
        font-weight: 600;
        color: #4a5568;
        margin-bottom: 4px;
    }
    
    .form-control, .form-select, .select2-container .select2-selection--single {
        height: 34px !important;
        font-size: 13px !important;
        border: 1px solid #d2d6dc;
        border-radius: 4px;
    }
    
    .form-control:focus, .form-select:focus {
        border-color: #4e73df;
        box-shadow: 0 0 0 2px rgba(78, 115, 223, 0.1);
    }
    
    .form-group {
        margin-bottom: 10px;
    }
    
    .marks-input {
        width: 100%;
        height: 32px;
        font-size: 13px;
        text-align: center;
        border: 1px solid #d2d6dc;
        border-radius: 4px;
        padding: 4px 8px;
        transition: all 0.2s;
    }
    
    .marks-input:focus {
        border-color: #4e73df;
        box-shadow: 0 0 0 2px rgba(78, 115, 223, 0.1);
        background-color: #f8fafc;
    }
    
    .marks-input.locked {
        background-color: #f0f9ff;
        border-color: #93c5fd;
        color: #1e40af;
        cursor: not-allowed;
        font-weight: 600;
    }
    
    .marks-input.highlight {
        background-color: #fef3c7;
        border-color: #f59e0b;
        box-shadow: 0 0 0 2px rgba(245, 158, 11, 0.1);
    }
    
    #loading {
        display: none;
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background: rgba(255,255,255,0.9);
        z-index: 9999;
        text-align: center;
        padding-top: 20%;
    }
    
    .badge {
        font-size: 11px;
        padding: 3px 8px;
        font-weight: 500;
    }
    
    .table th {
        font-size: 12px;
        padding: 8px 6px;
        background: #f8f9fc;
        color: #4a5568;
        font-weight: 600;
        border-bottom: 1px solid #e2e8f0;
        cursor: pointer;
        user-select: none;
        position: relative;
    }
    
    .table th:hover {
        background-color: #edf2f7;
    }
    
    .table th.sorted {
        background-color: #e2e8f0;
    }
    
    .table th.sorted-asc::after {
        content: " ▲";
        font-size: 10px;
        color: #4e73df;
    }
    
    .table th.sorted-desc::after {
        content: " ▼";
        font-size: 10px;
        color: #4e73df;
    }
    
    .table td {
        font-size: 12px;
        padding: 8px 6px;
        vertical-align: middle;
    }
    
    .table tbody tr:hover {
        background-color: #f8fafc;
    }
    
    .btn {
        padding: 6px 12px;
        font-size: 12px;
        height: 32px;
        border-radius: 4px;
        display: inline-flex;
        align-items: center;
        gap: 5px;
    }
    
    .btn-sm {
        padding: 4px 8px;
        font-size: 11px;
        height: 28px;
    }
    
    .action-buttons {
        display: flex;
        gap: 8px;
        flex-wrap: wrap;
        margin-top: 15px;
        padding-top: 15px;
        border-top: 1px solid #e2e8f0;
    }
    
    .table-controls {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 10px;
        flex-wrap: wrap;
        gap: 10px;
    }
    
    .filter-controls {
        display: flex;
        gap: 8px;
        flex-wrap: wrap;
    }
    
    .filter-input {
        width: 150px;
        height: 30px;
        font-size: 12px;
        padding: 4px 8px;
        border: 1px solid #d2d6dc;
        border-radius: 4px;
    }
    
    .section-info {
        background: #f8fafc;
        padding: 10px 12px;
        border-radius: 6px;
        border-left: 3px solid #4e73df;
        margin-bottom: 15px;
    }
    
    .section-info h6 {
        font-size: 13px;
        font-weight: 600;
        color: #2d3748;
        margin-bottom: 5px;
    }
    
    .section-info p {
        margin: 0;
        font-size: 12px;
        color: #718096;
    }
    
    .student-info-compact {
        background: white;
        border: 1px solid #e2e8f0;
        border-radius: 6px;
        padding: 12px;
        margin-bottom: 15px;
        display: flex;
        flex-wrap: wrap;
        gap: 15px;
        align-items: center;
        justify-content: space-between;
    }
    
    .info-header {
        flex: 1;
        min-width: 200px;
    }
    
    .info-header h6 {
        font-size: 13px;
        font-weight: 600;
        margin: 0 0 3px 0;
        color: #2d3748;
    }
    
    .info-header p {
        font-size: 11px;
        margin: 0;
        color: #718096;
    }
    
    .info-grid {
        display: flex;
        flex-wrap: wrap;
        gap: 15px;
    }
    
    .info-item {
        display: flex;
        flex-direction: column;
        min-width: 80px;
    }
    
    .info-item .label {
        font-size: 10px;
        text-transform: uppercase;
        color: #a0aec0;
        font-weight: 600;
        margin-bottom: 1px;
    }
    
    .info-item .value {
        font-size: 12px;
        font-weight: 600;
        color: #4a5568;
    }
    
    .scrollable-table {
        max-height: 400px;
        overflow-y: auto;
        border: 1px solid #e2e8f0;
        border-radius: 6px;
        margin-bottom: 15px;
    }
    
    .scrollable-table table {
        margin: 0;
    }
    
    .scrollable-table thead th {
        position: sticky;
        top: 0;
        background: #f8f9fc;
        z-index: 10;
    }
    
    .shortcut-hint {
        position: fixed;
        bottom: 20px;
        right: 20px;
        background: rgba(0,0,0,0.7);
        color: white;
        padding: 8px 12px;
        border-radius: 6px;
        font-size: 11px;
        display: none;
        z-index: 1000;
    }
    
    .status-badge {
        font-size: 10px;
        padding: 2px 6px;
    }
    
 /* ... keep all existing CSS above ... */

/* Mobile responsive */
@media (max-width: 768px) {
    .container-fluid {
        padding: 5px;
    }
    
    .row > [class*="col-"] {
        margin-bottom: 8px;
    }
    
    .selection-row {
        flex-direction: column;
    }
    
    .selection-row .form-group {
        min-width: 100%;
    }
    
    .student-info-compact {
        flex-direction: column;
        align-items: flex-start;
        gap: 10px;
    }
    
    .info-grid {
        width: 100%;
        justify-content: space-between;
    }
    
    .info-item {
        flex: 1;
        min-width: auto;
    }
    
    .table-controls {
        flex-direction: column;
        align-items: stretch;
    }
    
    .filter-controls {
        width: 100%;
        justify-content: space-between;
    }
    
    .filter-input {
        flex: 1;
        min-width: 120px;
    }
    
    .action-buttons {
        flex-direction: column;
    }
    
    .btn {
        width: 100%;
        justify-content: center;
    }
    
    /* Hide Symbol No. column (column 2) on mobile */
    .table td:nth-child(2),
    .table th:nth-child(2) {
        display: none;
    }
    
    /* Adjust column widths after hiding symbol column */
    .table td:nth-child(1),
    .table th:nth-child(1) {
        width: 8%;
    }
    
    .table td:nth-child(3),
    .table th:nth-child(3) {
        width: 15%;
    }
    
    .table td:nth-child(4),
    .table th:nth-child(4) {
        width: 45%;
    }
    
    .table td:nth-child(5),
    .table th:nth-child(5) {
        width: 20%;
    }
    
    .table td:nth-child(6),
    .table th:nth-child(6) {
        width: 12%;
    }
    
    /* Also hide the Symbol No. filter on mobile */
    #searchSymbol {
        display: none;
    }
    
    .shortcut-hint {
        bottom: 10px;
        right: 10px;
        font-size: 10px;
        padding: 6px 10px;
    }
}

    
    /* Loading animation */
    .loading-spinner {
        display: inline-block;
        width: 14px;
        height: 14px;
        border: 2px solid rgba(255,255,255,.3);
        border-radius: 50%;
        border-top-color: #fff;
        animation: spin 1s ease-in-out infinite;
        margin-right: 5px;
    }
    
    @keyframes spin {
        to { transform: rotate(360deg); }
    }
    
    /* Selection row optimization */
    .selection-row {
        display: flex;
        flex-wrap: wrap;
        gap: 8px;
        margin-bottom: 10px;
    }
    
    .selection-row .form-group {
        flex: 1;
        min-width: 140px;
        margin-bottom: 0;
    }
    
    /* Tooltip for locked fields */
    .tooltip-inner {
        font-size: 11px;
        padding: 4px 8px;
    }
</style>
</head>

<body>
<div class="container-fluid">
    <div id="loading">
        <div class="spinner-border text-primary" role="status" style="width: 2rem; height: 2rem;">
            <span class="sr-only">Loading...</span>
        </div>
        <h5 class="mt-2 text-primary">Processing...</h5>
    </div>
    
    <!-- Shortcut Hint -->
    <div class="shortcut-hint" id="shortcutHint">
        <div><strong>W</strong>: Move Up</div>
        <div><strong>S</strong>: Move Down</div>
        <div><strong>ESC</strong>: Close</div>
    </div>

    <div class="card">
        <div class="card-header">
            <h4><i class="fa fa-edit"></i> Enter Marks</h4>
        </div>
        <div class="card-body">
            <form id="marksentry">
                <!-- Selection Section -->
               <!--  <div class="section-info">
                    <h6><i class="fa fa-filter"></i> Selection Parameters</h6>
                    <p>Select parameters to load students</p>
                </div> -->
                
                <!-- Compact Selection Row -->
                <div class="selection-row">
                    <!-- Marks Type -->
                    <div class="form-group">
                        <label for="mark_type" class="form-label">
                            <i class="fa fa-tag"></i> Type *
                        </label>
                        <select id="mark_type" name="mark_type" class="form-control select2" required style="width: 100%">
                            <option value="">Select</option>
                            <option value="theory">Theory</option>
                            <option value="practical">Practical/Internal</option>
                        </select>
                    </div>

                    <!-- Class -->
                    <div class="form-group">
                        <label for="class_id" class="form-label">
                            <i class="fa fa-graduation-cap"></i> Class *
                        </label>
                        <select id="class_id" name="class_id" class="form-control select2" required style="width: 100%">
                            <option value="">Select</option>
                            <?php
                            $queryclass = "SELECT class_id, class 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>
                    </div>

                    <!-- Section -->
                    <div class="form-group">
                        <label for="section_id" class="form-label">
                            <i class="fa fa-columns"></i> Section *
                        </label>
                        <select id="section_id" name="section_id" class="form-control select2" disabled required style="width: 100%">
                            <option value="">Select</option>
                        </select>
                    </div>

                    <!-- Exam -->
                    <div class="form-group">
                        <label for="exam_id" class="form-label">
                            <i class="fa fa-calendar"></i> Exam *
                        </label>
                        <select id="exam_id" name="exam_id" class="form-control select2" disabled required style="width: 100%">
                            <option value="">Select</option>
                        </select>
                    </div>

                    <!-- Subject -->
                    <div class="form-group">
                        <label for="subject_id" class="form-label">
                            <i class="fa fa-book"></i> Subject *
                        </label>
                        <select id="subject_id" name="subject_id" class="form-control select2" disabled required style="width: 100%">
                            <option value="">Select</option>
                        </select>
                    </div>

                    <!-- Teacher -->
                    <div class="form-group">
                        <label for="teacher_id" class="form-label">
                            <i class="fa fa-user"></i> Teacher *
                        </label>
                        <select id="teacher_id" name="teacher_id" class="form-control select2" required style="width: 100%">
                            <option value="">Select</option>
                            <?php 
                            $tQ = $conn->query("SELECT teacher_id, name, email FROM teachers WHERE role = 'Teacher' AND status='Active' ORDER BY name");
                            while($t = $tQ->fetch_assoc()){
                                $selected = ($teacher_id == $t['teacher_id']) ? 'selected' : '';
                                echo "<option value='{$t['teacher_id']}' data-email='{$t['email']}' $selected>{$t['name']}</option>";
                            }
                            ?>
                        </select>
                    </div>
                </div>

                <!-- Student Marks Section -->
                <div id="student-section" style="display: none;">
                    <!-- Student Info Header -->
                    <div class="student-info-compact">
                        <div class="info-header">
                            <h6><i class="fa fa-users"></i> Student Marks</h6>
                            <p id="section-details"></p>
                        </div>
                        
                        <div class="info-grid">
                            <div class="info-item">
                                <span class="label">Students</span>
                                <span class="value" id="total-students">0</span>
                            </div>
                            <div class="info-item">
                                <span class="label">Subject</span>
                                <span class="value" id="subject-name">--</span>
                            </div>
                            <div class="info-item">
                                <span class="label">Exam</span>
                                <span class="value" id="exam-name">--</span>
                            </div>
                            <div class="info-item">
                                <span class="label">Config</span>
                                <span class="value">
                                    <span id="marks-type">--</span>/<span id="full-marks">0</span>
                                </span>
                            </div>
                        </div>
                    </div>

                    <!-- Table Controls -->
                    <div class="table-controls">
                        <div class="filter-controls">
                            <input type="text" id="searchName" class="filter-input" placeholder="Search name..." title="Search student names">
                            <input type="text" id="searchSymbol" class="filter-input" placeholder="Search symbol no..." title="Search symbol numbers">
                            <input type="text" id="searchRoll" class="filter-input" placeholder="Search roll no..." title="Search roll numbers">
                            <select id="filterStatus" class="filter-input">
                                <option value="">All Status</option>
                                <option value="entered">Entered</option>
                                <option value="pending">Pending</option>
                            </select>
                            <button type="button" id="clearFilters" class="btn btn-outline-secondary btn-sm">
                                <i class="fa fa-times"></i> Clear
                            </button>
                        </div>
                        <div>
                            <button type="button" id="toggleSort" class="btn btn-outline-info btn-sm">
                                <i class="fa fa-sort"></i> Sort: Default
                            </button>
                        </div>
                    </div>

                    <!-- Student Marks Table -->
                    <div id="student-marks-list">
                        <!-- Students will be loaded here -->
                    </div>

                    <!-- Action Buttons -->
                    <div class="action-buttons">
                        <button type="submit" class="btn btn-primary" id="submitBtn">
                            <i class="fa fa-check"></i> Submit Marks
                        </button>
                        <button type="button" class="btn btn-secondary" id="clearBtn">
                            <i class="fa fa-times"></i> Clear All
                        </button>
                        <button type="button" class="btn btn-outline-secondary" id="reloadBtn">
                            <i class="fa fa-refresh"></i> Reload
                        </button>
                        <button type="button" class="btn btn-outline-info" id="showShortcuts">
                            <i class="fa fa-keyboard-o"></i> Shortcuts
                        </button>
                        
                        <?php if(!empty($buttonStatus['btnMarksPr']) && $buttonStatus['btnMarksPr'] != 'inactive'): ?>
                            <a href="marksentrypr.php" class="btn btn-info">
                                <i class="fa fa-pencil"></i> Marks [IN]
                            </a>
                        <?php endif; ?>
                        
                        <a href="dashboard.php" class="btn btn-outline-dark">
                            <i class="fa fa-home"></i> Dashboard
                        </a>
                    </div>
                </div>
            </form>
        </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/select2/select2.min.js"></script>

<script>
$(document).ready(function() {
    // Initialize Select2 with minimal config
    $('.select2').select2({
        width: '100%',
        placeholder: "Select",
        minimumResultsForSearch: 6
    });
    
    // Variables
    let maxMarks = 0;
    let subjectFullMarks = { theory: 0, practical: 0 };
    let teacherEmail = '';
    let currentSort = { column: null, direction: 'asc' };
    let originalStudents = [];
    let currentInputIndex = -1;
    
    // Get teacher email from selected option
    $('#teacher_id').change(function() {
        let selectedOption = $(this).find('option:selected');
        teacherEmail = selectedOption.data('email') || '';
    });
    
    // Submit form with email notification option
    $('#marksentry').submit(function(e){
        e.preventDefault();
        
        if(!validateForm()) return;
        if(!validateMarks()) return;
        
        // Ask for email notification if teacher has email
        if(teacherEmail) {
            Swal.fire({
                title: 'Send Email Notification?',
                text: 'Would you like to send a confirmation email to ' + teacherEmail + '?',
                icon: 'question',
                showCancelButton: true,
                confirmButtonText: 'Yes, send email',
                cancelButtonText: 'No, just save',
                confirmButtonColor: '#3085d6',
                cancelButtonColor: '#6c757d'
            }).then((result) => {
                if (result.isConfirmed) {
                    submitMarks(true);
                } else {
                    submitMarks(false);
                }
            });
        } else {
            submitMarks(false);
        }
    });
    
    function submitMarks(sendEmail) {
        $('#loading').show();
        $('#submitBtn').prop('disabled', true).html('<span class="loading-spinner"></span> Saving...');
        
        let formData = new FormData($('#marksentry')[0]);
        if(sendEmail) {
            formData.append('send_email', '1');
            formData.append('teacher_email', teacherEmail);
        }
        
        $.ajax({
            url: 'process_marksentry.php',
            type: 'POST',
            data: formData,
            contentType: false,
            processData: false,
            success: function(res) {
                $('#loading').hide();
                $('#submitBtn').prop('disabled', false).html('<i class="fa fa-check"></i> Submit Marks');
                
                if(res.includes('Error') || res.includes('Duplicate') || res.includes('failed')) {
                    Swal.fire({
                        icon: 'error',
                        title: 'Error!',
                        text: res,
                        confirmButtonColor: '#dc3545'
                    });
                } else {
                    let successMsg = res;
                    if(sendEmail) {
                        successMsg += ' Email notification sent to teacher.';
                    }
                    
                    Swal.fire({
                        title: 'Success!',
                        text: successMsg,
                        icon: 'success',
                        confirmButtonColor: '#28a745'
                    }).then(() => {
                        fetchStudents();
                    });
                }
            },
            error: function(xhr, status, error) {
                $('#loading').hide();
                $('#submitBtn').prop('disabled', false).html('<i class="fa fa-check"></i> Submit Marks');
                Swal.fire({
                    icon: 'error',
                    title: 'Error',
                    text: 'Submission failed: ' + error,
                    confirmButtonColor: '#dc3545'
                });
            }
        });
    }
    
    // Form validation
    function validateForm() {
        let missingFields = [];
        if(!$('#mark_type').val()) missingFields.push('Marks Type');
        if(!$('#class_id').val()) missingFields.push('Class');
        if(!$('#section_id').val()) missingFields.push('Section');
        if(!$('#exam_id').val()) missingFields.push('Exam');
        if(!$('#subject_id').val()) missingFields.push('Subject');
        if(!$('#teacher_id').val()) missingFields.push('Teacher');
        
        if(missingFields.length > 0) {
            Swal.fire({
                icon: 'warning',
                title: 'Missing Fields',
                html: '<small>Please select: ' + missingFields.join(', ') + '</small>',
                confirmButtonColor: '#ffc107'
            });
            return false;
        }
        return true;
    }
    
    function validateMarks() {
        let marksEntered = false;
        let invalidMarks = [];
        
        $('.marks-input:not(.locked)').each(function(){
            let marks = $(this).val().trim();
            let studentName = $(this).closest('tr').find('.student-name').text().trim();
            
            if(marks !== '') {
                marksEntered = true;
                if(isNaN(marks) || marks < 0) {
                    invalidMarks.push(studentName + ': Invalid number');
                }
                let max = $(this).data('max');
                if(max && parseFloat(marks) > parseFloat(max)) {
                    invalidMarks.push(studentName + ': Exceeds max (' + max + ')');
                }
            }
        });
        
        if(!marksEntered) {
            Swal.fire({
                icon: 'warning',
                title: 'No Marks',
                text: 'Please enter marks for at least one student',
                confirmButtonColor: '#ffc107'
            });
            return false;
        }
        
        if(invalidMarks.length > 0) {
            Swal.fire({
                icon: 'error',
                title: 'Invalid Marks',
                html: '<small>' + invalidMarks.join('<br>') + '</small>',
                confirmButtonColor: '#dc3545'
            });
            return false;
        }
        
        return true;
    }
    
    // Class change
    $('#class_id').change(function () {
        let classId = $(this).val();
        
        if (classId) {
            $('#section_id, #exam_id').prop('disabled', false);
            $('#section_id').html('<option value="">Loading...</option>').trigger('change');
            $('#exam_id').html('<option value="">Loading...</option>').trigger('change');
            $('#subject_id').prop('disabled', true).html('<option value="">Select</option>');
            $('#student-section').hide();
            
            loadSections(classId);
            loadExams(classId);
        } else {
            resetFields();
        }
    });
    
    // Section change
    $('#section_id').change(function () {
        let classId = $('#class_id').val();
        let sectionId = $(this).val();
        
        if (classId && sectionId) {
            $('#subject_id').prop('disabled', false);
            loadSubjects(classId, sectionId);
        } else {
            $('#subject_id').prop('disabled', true).html('<option value="">Select</option>');
            $('#student-section').hide();
        }
    });
    
    // Subject change
    $('#subject_id').change(function(){
        if($(this).val()) {
            let selectedOption = $(this).find('option:selected');
            subjectFullMarks.theory = selectedOption.data('theory') || 0;
            subjectFullMarks.practical = selectedOption.data('internal') || 0;
            
            let markType = $('#mark_type').val();
            maxMarks = markType === 'theory' ? subjectFullMarks.theory : subjectFullMarks.practical;
            $('#full-marks').text(maxMarks);
            
            if($('#exam_id').val() && $('#mark_type').val() && $('#teacher_id').val()) {
                fetchStudents();
            }
        } else {
            $('#student-section').hide();
        }
    });
    
    // Other changes
    $('#mark_type, #exam_id, #teacher_id').change(function(){
        if($('#subject_id').val()) {
            let markTypeText = $('#mark_type option:selected').text();
            $('#marks-type').text(markTypeText);
            
            if($('#subject_id').val()) {
                let markType = $('#mark_type').val();
                maxMarks = markType === 'theory' ? subjectFullMarks.theory : subjectFullMarks.practical;
                $('#full-marks').text(maxMarks);
            }
            
            if($('#class_id').val() && $('#section_id').val() && $('#exam_id').val() && 
               $('#subject_id').val() && $('#mark_type').val() && $('#teacher_id').val()) {
                fetchStudents();
            }
        }
    });
    
    // Load sections
    function loadSections(classId) {
        $.ajax({
            url: 'ajax/get_sections_by_class.php',
            type: 'GET',
            data: { class_id: classId },
            dataType: 'json',
            success: function (sections) {
                let options = '<option value="">Select</option>';
                if (sections && sections.length > 0) {
                    sections.forEach(function (section) {
                        options += '<option value="' + section.section_id + '">' + section.section_name + '</option>';
                    });
                }
                $('#section_id').html(options).trigger('change');
            },
            error: function () {
                $('#section_id').html('<option value="">Error loading</option>').trigger('change');
            }
        });
    }
    
    // Load exams
    function loadExams(classId) {
        $.ajax({
            url: 'ajax/get_exams_by_class.php',
            type: 'GET',
            data: { class_id: classId },
            dataType: 'json',
            success: function (exams) {
                let options = '<option value="">Select</option>';
                if (exams && exams.length > 0) {
                    exams.forEach(function (exam) {
                        options += '<option value="' + exam.id + '">' + exam.exam_type + ' - ' + exam.exm_year + '</option>';
                    });
                }
                $('#exam_id').html(options).trigger('change');
            },
            error: function () {
                $('#exam_id').html('<option value="">Error loading</option>').trigger('change');
            }
        });
    }
    
    // Load subjects
    function loadSubjects(classId, sectionId) {
        $.ajax({
            url: 'ajax/get_subjects_by_class_section.php',
            type: 'GET',
            data: { class_id: classId, section_id: sectionId },
            dataType: 'json',
            success: function (data) {
                let options = '<option value="">Select</option>';
                if (data.success && data.subjects && data.subjects.length > 0) {
                    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 + '</option>';
                    });
                }
                $('#subject_id').html(options).trigger('change');
            },
            error: function () {
                $('#subject_id').html('<option value="">Error loading</option>').trigger('change');
            }
        });
    }
    
    // Fetch students
    function fetchStudents() {
        let classId = $('#class_id').val();
        let sectionId = $('#section_id').val();
        let examId = $('#exam_id').val();
        let subjectId = $('#subject_id').val();
        let markType = $('#mark_type').val();
        let teacherId = $('#teacher_id').val();
        
        if(classId && sectionId && examId && subjectId && markType && teacherId){
            updateSectionDetails();
            $('#loading').show();
            $('#student-section').show();
            
            $.ajax({
                url: 'ajax/get_students_for_marks.php',
                type: 'POST',
                data: {
                    class_id: classId,
                    section_id: sectionId,
                    exam_id: examId,
                    subject_id: subjectId,
                    mark_type: markType,
                    teacher_id: teacherId
                },
                success: function(res) {
                    $('#loading').hide();
                    $('#student-marks-list').html(res);
                    
                    // Store original data
                    storeOriginalData();
                    
                    let studentCount = $('.student-row').length;
                    $('#total-students').text(studentCount);
                    
                    setupMarksValidation();
                    setupMarksCalculation();
                    setupTableSorting();
                    setupFilters();
                    setupShortcutNavigation();
                    lockExistingMarks();
                    
                    // Auto-focus first input
                    setTimeout(function() {
                        let firstInput = $('.marks-input:not(.locked)').first();
                        if(firstInput.length) {
                            firstInput.focus().addClass('highlight');
                            currentInputIndex = $('.marks-input:not(.locked)').index(firstInput);
                        }
                    }, 100);
                    
                    // Check screen width
                    if($(window).width() <= 768) {
                        $('.table').addClass('mobile-view');
                    }
                },
                error: function() {
                    $('#loading').hide();
                    $('#student-marks-list').html('<div class="alert alert-danger">Failed to load students. Please try again.</div>');
                }
            });
        }
    }
    
    // Store original student data
    function storeOriginalData() {
        originalStudents = [];
        $('.student-row').each(function() {
            originalStudents.push({
                name: $(this).find('.student-name').text().trim(),
                symbol: $(this).find('.student-symbol').text().trim(),
                roll: $(this).find('.student-roll').text().trim(),
                marks: $(this).find('.marks-input').val().trim(),
                status: $(this).find('.student-row').hasClass('entered') ? 'entered' : 'pending',
                element: $(this)
            });
        });
    }
    
    // Lock input fields with existing marks > 0
    function lockExistingMarks() {
        $('.marks-input').each(function() {
            let marks = $(this).val().trim();
            if(marks !== '' && !isNaN(marks) && parseFloat(marks) > 0) {
                $(this).addClass('locked')
                      .prop('readonly', true)
                      .attr('title', 'Marks already entered. To edit, contact administrator.')
                      .tooltip({ trigger: 'hover' });
            }
        });
    }
    
    // Setup table sorting
    function setupTableSorting() {
        // Clear previous sorting
        $('th').removeClass('sorted sorted-asc sorted-desc');
        currentSort = { column: null, direction: 'asc' };
        $('#toggleSort').html('<i class="fa fa-sort"></i> Sort: Default');
        
        // Click handler for column headers
        $('th[data-sort]').off('click').on('click', function() {
            let column = $(this).data('sort');
            let direction = 'asc';
            
            if(currentSort.column === column) {
                direction = currentSort.direction === 'asc' ? 'desc' : 'asc';
            }
            
            sortTable(column, direction);
            currentSort = { column: column, direction: direction };
            
            // Update UI
            $('th').removeClass('sorted sorted-asc sorted-desc');
            $(this).addClass('sorted').addClass(direction === 'asc' ? 'sorted-asc' : 'sorted-desc');
            
            // Update sort button
            let columnNames = {
                'sn': 'S.N.',
                'symbol': 'Symbol No.',
                'roll': 'Roll No.',
                'name': 'Name',
                'marks': 'Marks',
                'status': 'Status'
            };
            $('#toggleSort').html(`<i class="fa fa-sort-${direction === 'asc' ? 'asc' : 'desc'}"></i> Sort: ${columnNames[column]} (${direction.toUpperCase()})`);
        });
        
        // Sort button
        $('#toggleSort').off('click').on('click', function() {
            if(currentSort.column) {
                let newDirection = currentSort.direction === 'asc' ? 'desc' : 'asc';
                sortTable(currentSort.column, newDirection);
                currentSort.direction = newDirection;
                
                $('th').removeClass('sorted-asc sorted-desc');
                $(`th[data-sort="${currentSort.column}"]`).addClass(newDirection === 'asc' ? 'sorted-asc' : 'sorted-desc');
                
                let columnNames = {
                    'sn': 'S.N.',
                    'symbol': 'Symbol No.',
                    'roll': 'Roll No.',
                    'name': 'Name',
                    'marks': 'Marks',
                    'status': 'Status'
                };
                $(this).html(`<i class="fa fa-sort-${newDirection === 'asc' ? 'asc' : 'desc'}"></i> Sort: ${columnNames[currentSort.column]} (${newDirection.toUpperCase()})`);
            }
        });
    }
    
    function sortTable(column, direction) {
        let tbody = $('tbody');
        let rows = tbody.find('tr').get();
        
        rows.sort(function(a, b) {
            let aVal = getCellValue(a, column);
            let bVal = getCellValue(b, column);
            
            // Handle numeric values
            if(column === 'sn' || column === 'marks') {
                aVal = parseFloat(aVal) || 0;
                bVal = parseFloat(bVal) || 0;
                return direction === 'asc' ? aVal - bVal : bVal - aVal;
            }
            
            // Handle text values
            aVal = aVal.toString().toLowerCase();
            bVal = bVal.toString().toLowerCase();
            
            if(aVal < bVal) return direction === 'asc' ? -1 : 1;
            if(aVal > bVal) return direction === 'asc' ? 1 : -1;
            return 0;
        });
        
        // Reorder rows
        $.each(rows, function(index, row) {
            tbody.append(row);
        });
        
        // Update S.N. column
        updateSerialNumbers();
    }
    
    function getCellValue(row, column) {
        switch(column) {
            case 'sn': return $(row).find('td:eq(0)').text();
            case 'symbol': return $(row).find('.student-symbol').text();
            case 'roll': return $(row).find('.student-roll').text();
            case 'name': return $(row).find('.student-name').text();
            case 'marks': return $(row).find('.marks-input').val();
            case 'status': return $(row).find('.status-badge').text().toLowerCase();
            default: return '';
        }
    }
    
    function updateSerialNumbers() {
        $('.student-row').each(function(index) {
            $(this).find('td:eq(0)').text(index + 1);
        });
    }
    
    // Setup filters
    function setupFilters() {
        // Name filter
        $('#searchName').off('input').on('input', function() {
            applyFilters();
        });
        
        // Symbol filter
        $('#searchSymbol').off('input').on('input', function() {
            applyFilters();
        });
        
        // Roll filter
        $('#searchRoll').off('input').on('input', function() {
            applyFilters();
        });
        
        // Status filter
        $('#filterStatus').off('change').on('change', function() {
            applyFilters();
        });
        
        // Clear filters
        $('#clearFilters').off('click').on('click', function() {
            $('#searchName, #searchSymbol, #searchRoll').val('');
            $('#filterStatus').val('');
            applyFilters();
        });
    }
    
    function applyFilters() {
        let nameFilter = $('#searchName').val().toLowerCase();
        let symbolFilter = $('#searchSymbol').val().toLowerCase();
        let rollFilter = $('#searchRoll').val().toLowerCase();
        let statusFilter = $('#filterStatus').val();
        
        $('.student-row').each(function() {
            let name = $(this).find('.student-name').text().toLowerCase();
            let symbol = $(this).find('.student-symbol').text().toLowerCase();
            let roll = $(this).find('.student-roll').text().toLowerCase();
            let status = $(this).find('.status-badge').text().toLowerCase();
            let hasMarks = $(this).find('.marks-input').val().trim() !== '';
            
            let show = true;
            
            if(nameFilter && !name.includes(nameFilter)) show = false;
            if(symbolFilter && !symbol.includes(symbolFilter)) show = false;
            if(rollFilter && !roll.includes(rollFilter)) show = false;
            if(statusFilter === 'entered' && !hasMarks) show = false;
            if(statusFilter === 'pending' && hasMarks) show = false;
            
            $(this).toggle(show);
        });
        
        updateSerialNumbers();
        updateStudentCount();
    }
    
    function updateStudentCount() {
        let visibleCount = $('.student-row:visible').length;
        $('#total-students').text(visibleCount);
    }
    
    // Setup keyboard navigation
    function setupShortcutNavigation() {
        $(document).off('keydown.navigation').on('keydown.navigation', function(e) {
            // Only handle when student section is visible
            if($('#student-section').is(':visible')) {
                let inputs = $('.marks-input:not(.locked)');
                
                // W key - move up
                if(e.key === 'w' || e.key === 'W') {
                    e.preventDefault();
                    navigateInput('up', inputs);
                }
                
                // S key - move down
                if(e.key === 's' || e.key === 'S') {
                    e.preventDefault();
                    navigateInput('down', inputs);
                }
                
                // ESC key - hide shortcut hint
                if(e.key === 'Escape') {
                    $('#shortcutHint').fadeOut(200);
                }
            }
        });
        
        // Show shortcuts button
        $('#showShortcuts').off('click').on('click', function() {
            $('#shortcutHint').fadeIn(200);
            setTimeout(function() {
                $('#shortcutHint').fadeOut(2000);
            }, 3000);
        });
    }
    
    function navigateInput(direction, inputs) {
        if(inputs.length === 0) return;
        
        // Remove highlight from current input
        inputs.removeClass('highlight');
        
        if(currentInputIndex === -1) {
            currentInputIndex = 0;
        } else {
            if(direction === 'up') {
                currentInputIndex = Math.max(0, currentInputIndex - 1);
            } else {
                currentInputIndex = Math.min(inputs.length - 1, currentInputIndex + 1);
            }
        }
        
        let targetInput = inputs.eq(currentInputIndex);
        targetInput.focus().addClass('highlight');
        
        // Scroll to input if needed
        let inputPosition = targetInput.offset().top;
        let scrollPosition = $(window).scrollTop();
        let windowHeight = $(window).height();
        
        if(inputPosition < scrollPosition || inputPosition > scrollPosition + windowHeight - 100) {
            $('html, body').animate({
                scrollTop: inputPosition - 100
            }, 200);
        }
    }
    
    // Update section details
    function updateSectionDetails() {
        let className = $('#class_id option:selected').text();
        let sectionName = $('#section_id option:selected').text();
        let examName = $('#exam_id option:selected').text();
        let subjectName = $('#subject_id option:selected').text();
        let teacherName = $('#teacher_id option:selected').text();
        let markType = $('#mark_type option:selected').text();
        
        $('#section-details').html(className + ' - ' + sectionName + ' | ' + examName + ' | ' + subjectName);
        $('#subject-name').text(subjectName);
        $('#exam-name').text(examName);
        $('#teacher-name').text(teacherName);
        $('#marks-type').text(markType);
    }
    
    // Setup marks validation
    function setupMarksValidation() {
        $('.marks-input').off('input').on('input', function(){
            let maxMarks = $(this).data('max');
            let enteredMarks = $(this).val().trim();
            
            if(enteredMarks === '') {
                $(this).removeClass('border-danger border-success');
                $(this).closest('tr').find('.status-badge')
                    .removeClass('badge-success badge-warning')
                    .addClass('badge-warning')
                    .html('<i class="fa fa-clock-o"></i> Pending');
                return;
            }
            
            if(isNaN(enteredMarks)) {
                $(this).addClass('border-danger').removeClass('border-success');
            } else if(maxMarks && parseFloat(enteredMarks) > parseFloat(maxMarks)) {
                $(this).addClass('border-danger').removeClass('border-success');
            } else {
                $(this).removeClass('border-danger').addClass('border-success');
                $(this).closest('tr').find('.status-badge')
                    .removeClass('badge-warning')
                    .addClass('badge-success')
                    .html('<i class="fa fa-check"></i> Entered');
            }
        });
    }
    
    // Setup marks calculation
    function setupMarksCalculation() {
        $('.marks-input').off('blur').on('blur', function(){
            let maxMarks = $(this).data('max');
            let enteredMarks = $(this).val().trim();
            
            if(enteredMarks !== '' && !isNaN(enteredMarks) && maxMarks > 0) {
                let percentage = (parseFloat(enteredMarks) / parseFloat(maxMarks)) * 100;
                // Can display percentage if needed
            }
        });
    }
    
    // Clear marks button
    $('#clearBtn').click(function(){
        Swal.fire({
            title: 'Clear All Marks?',
            text: 'This will clear all entered marks.',
            icon: 'warning',
            showCancelButton: true,
            confirmButtonText: 'Clear All',
            cancelButtonText: 'Cancel'
        }).then((result) => {
            if (result.isConfirmed) {
                $('.marks-input:not(.locked)').val('').removeClass('border-danger border-success');
                $('.status-badge').removeClass('badge-success').addClass('badge-warning')
                    .html('<i class="fa fa-clock-o"></i> Pending');
                Swal.fire('Cleared!', 'All marks cleared.', 'success');
            }
        });
    });
    
    // Reload button
    $('#reloadBtn').click(function(){
        if($('#subject_id').val()) {
            fetchStudents();
        }
    });
    
    // Reset fields
    function resetFields() {
        $('#section_id').html('<option value="">Select</option>').prop('disabled', true).trigger('change');
        $('#exam_id').html('<option value="">Select</option>').prop('disabled', true).trigger('change');
        $('#subject_id').html('<option value="">Select</option>').prop('disabled', true).trigger('change');
        $('#student-section').hide();
        
        $('#section-details').html('');
        $('#subject-name').text('--');
        $('#exam-name').text('--');
        $('#teacher-name').text('--');
        $('#marks-type').text('--');
        $('#full-marks').text('0');
        $('#total-students').text('0');
    }
    
    // Window resize handler
    $(window).resize(function() {
        if($(window).width() <= 768) {
            $('.table').addClass('mobile-view');
        } else {
            $('.table').removeClass('mobile-view');
        }
    });
    
    // Initial setup
    $('#section_id').prop('disabled', true);
    $('#exam_id').prop('disabled', true);
    $('#subject_id').prop('disabled', true);
    
    // Initialize tooltips
    $('[title]').tooltip();
});
</script>
</body>
</html>