<?php
// ajax/get_students_for_marks.php
include('../includes/db.php');
header('Content-Type: text/html');

// Get POST data
$class_id = isset($_POST['class_id']) ? intval($_POST['class_id']) : 0;
$section_id = isset($_POST['section_id']) ? intval($_POST['section_id']) : 0;
$exam_id = isset($_POST['exam_id']) ? intval($_POST['exam_id']) : 0;
$subject_id = isset($_POST['subject_id']) ? intval($_POST['subject_id']) : 0;
$mark_type = isset($_POST['mark_type']) ? $_POST['mark_type'] : 'theory';
$teacher_id = isset($_POST['teacher_id']) ? intval($_POST['teacher_id']) : 0;

// Validate required fields
if (!$class_id || !$section_id || !$exam_id || !$subject_id || !$mark_type || !$teacher_id) {
    echo '<div class="alert alert-danger">
            <i class="fa fa-exclamation-circle"></i> 
            Please select all required fields: Class, Section, Exam, Subject, Marks Type, and Teacher.
          </div>';
    exit;
}

// Get current academic year
$academic_year_query = "SELECT year_id, ay_ad FROM academic_years WHERE status = 'active' LIMIT 1";
$academic_year_result = $conn->query($academic_year_query);
$academic_year = $academic_year_result->fetch_assoc();
$academic_year_id = $academic_year['year_id'] ?? 1;
$current_academic_year = $academic_year['ay_ad'] ?? '2024-2025';

// Get subject details for full marks and subject code
$subject_query = "SELECT subject_name, subject_code, theory_full_marks, internal_full_marks 
                  FROM subjects 
                  WHERE id = ?";
$subject_stmt = $conn->prepare($subject_query);
$subject_stmt->bind_param("i", $subject_id);
$subject_stmt->execute();
$subject_result = $subject_stmt->get_result();

if (!$subject_result || $subject_result->num_rows === 0) {
    echo '<div class="alert alert-danger">
            <i class="fa fa-exclamation-circle"></i> 
            Subject not found.
          </div>';
    exit;
}

$subject = $subject_result->fetch_assoc();
$subject_stmt->close();

// Get the subject code from the subject
$subject_code = $subject['subject_code'];

// Determine full marks based on mark type
$full_marks = 0;
if ($mark_type === 'theory') {
    $full_marks = $subject['theory_full_marks'] ?: 100;
} elseif ($mark_type === 'practical') {
    $full_marks = $subject['internal_full_marks'] ?: 50;
} elseif ($mark_type === 'internal') {
    $full_marks = $subject['internal_full_marks'] ?: 30;
} else {
    $full_marks = 100; // Default for assignment, project, oral
}

// Get exam details
$exam_query = "SELECT id, exam_type, exm_year FROM examination_type WHERE id = ?";
$exam_stmt = $conn->prepare($exam_query);
$exam_stmt->bind_param("i", $exam_id);
$exam_stmt->execute();
$exam_result = $exam_stmt->get_result();
$exam = $exam_result->fetch_assoc();
$exam_stmt->close();

if (!$exam) {
    echo '<div class="alert alert-danger">
            <i class="fa fa-exclamation-circle"></i> 
            Exam not found.
          </div>';
    exit;
}

$exam_type_display = $exam['exam_type'] ?? '';
$exam_year = $exam['exm_year'] ?? '';

// Get class name
$class_query = "SELECT class FROM classes WHERE class_id = ?";
$class_stmt = $conn->prepare($class_query);
$class_stmt->bind_param("i", $class_id);
$class_stmt->execute();
$class_result = $class_stmt->get_result();
$class_row = $class_result->fetch_assoc();
$class_name = $class_row['class'] ?? '';
$class_stmt->close();

// Get section name
$section_query = "SELECT section_name FROM sections WHERE section_id = ?";
$section_stmt = $conn->prepare($section_query);
$section_stmt->bind_param("i", $section_id);
$section_stmt->execute();
$section_result = $section_stmt->get_result();
$section_row = $section_result->fetch_assoc();
$section_name = $section_row['section_name'] ?? '';
$section_stmt->close();

// Get students for this class and section who have this subject in their subject list
$student_query = "SELECT 
                    DISTINCT s.student_id,
                    s.name,
                    s.regd_id,
                    s.symbol_no,
                    s.registration_no,
                    sn.symbol_no as exam_symbol_no,
                    ss.academic_year
                 FROM students s
                 INNER JOIN student_class_section_data scsd ON s.student_id = scsd.student_id
                 INNER JOIN studentsub ss ON s.student_id = ss.student_id
                 LEFT JOIN symbolno_data sn ON s.student_id = sn.student_id AND sn.exam_id = ?
                 WHERE scsd.class_id = ? 
                 AND scsd.section_id = ?
                 AND ss.class_id = ? 
                 AND ss.section_id = ?
                 AND ss.academic_year = ?
                 AND ss.status = 'active'
                 AND (
                     ss.sub1 = ? OR 
                     ss.sub2 = ? OR 
                     ss.sub3 = ? OR 
                     ss.sub4 = ? OR 
                     ss.sub5 = ? OR 
                     ss.sub6 = ? OR 
                     ss.sub7 = ?
                 )
                 AND scsd.status = 'active'
                 AND s.status = 'active'
                 ORDER BY s.registration_no ASC, s.regd_id ASC";

$student_stmt = $conn->prepare($student_query);
if (!$student_stmt) {
    echo '<div class="alert alert-danger">Error preparing query: ' . $conn->error . '</div>';
    exit;
}

// Bind parameters: exam_id, class_id, section_id, studentsub_class_id, studentsub_section_id, academic_year, subject_code (7 times)
$student_stmt->bind_param("iiiiissssssss", 
    $exam_id, 
    $class_id, 
    $section_id,
    $class_id, // studentsub.class_id
    $section_id, // studentsub.section_id
    $current_academic_year,
    $subject_code, $subject_code, $subject_code, $subject_code, $subject_code, $subject_code, $subject_code
);

$student_stmt->execute();
$student_result = $student_stmt->get_result();

if (!$student_result || $student_result->num_rows === 0) {
    // Try with different academic year if no results
    $student_query2 = "SELECT 
                        DISTINCT s.student_id,
                        s.name,
                        s.regd_id,
                        s.symbol_no,
                        s.registration_no,
                        sn.symbol_no as exam_symbol_no,
                        ss.academic_year
                     FROM students s
                     INNER JOIN student_class_section_data scsd ON s.student_id = scsd.student_id
                     INNER JOIN studentsub ss ON s.student_id = ss.student_id
                     LEFT JOIN symbolno_data sn ON s.student_id = sn.student_id AND sn.exam_id = ?
                     WHERE scsd.class_id = ? 
                     AND scsd.section_id = ?
                     AND ss.class_id = ? 
                     AND ss.section_id = ?
                     AND ss.status = 'active'
                     AND (
                         ss.sub1 = ? OR 
                         ss.sub2 = ? OR 
                         ss.sub3 = ? OR 
                         ss.sub4 = ? OR 
                         ss.sub5 = ? OR 
                         ss.sub6 = ? OR 
                         ss.sub7 = ?
                     )
                     AND scsd.status = 'active'
                     AND s.status = 'active'
                     ORDER BY s.registration_no ASC, s.regd_id ASC";
    
    $student_stmt2 = $conn->prepare($student_query2);
    if (!$student_stmt2) {
        echo '<div class="alert alert-danger">Error preparing query: ' . $conn->error . '</div>';
        exit;
    }
    
    $student_stmt2->bind_param("iiiiissssssss", 
        $exam_id, 
        $class_id, 
        $section_id,
        $class_id, // studentsub.class_id
        $section_id, // studentsub.section_id
        $subject_code, $subject_code, $subject_code, $subject_code, $subject_code, $subject_code, $subject_code
    );
    
    $student_stmt2->execute();
    $student_result = $student_stmt2->get_result();
    
    if (!$student_result || $student_result->num_rows === 0) {
        echo '<div class="alert alert-warning">
                <i class="fa fa-exclamation-triangle"></i> 
                No students found for this subject. 
                <br><small>Class: ' . $class_name . ' (ID: ' . $class_id . '), Section: ' . $section_name . ' (ID: ' . $section_id . ')</small>
                <br><small>Subject: ' . $subject['subject_name'] . ' (Code: ' . $subject_code . ')</small>
                <br><small>Please make sure students have this subject assigned in their subject list.</small>
              </div>';
        exit;
    }
    $student_stmt = $student_stmt2;
}

// Check for existing marks for these students
$existing_marks = array();
$check_marks_query = "SELECT student_id, marks 
                      FROM marks 
                      WHERE class_id = ? 
                      AND section_id = ? 
                      AND subject_id = ? 
                      AND exam_type = ?
                      AND academic_year_id = ?
                      AND mark_type = ?";
$check_stmt = $conn->prepare($check_marks_query);
$check_stmt->bind_param("iiiiis", $class_id, $section_id, $subject_id, $exam_id, $academic_year_id, $mark_type);
$check_stmt->execute();
$check_result = $check_stmt->get_result();

while ($row = $check_result->fetch_assoc()) {
    $existing_marks[$row['student_id']] = $row['marks'];
}
$check_stmt->close();

// Total student count
$total_students = $student_result->num_rows;

// Output table with responsive columns and pagination controls
$output = '<div class="table-info mb-2">
              <div class="d-flex justify-content-between align-items-center">
                  <div>
                      <small class="text-muted">
                          <i class="fa fa-users"></i> Total Students: <strong>' . $total_students . '</strong> | 
                          <i class="fa fa-book"></i> ' . htmlspecialchars($subject['subject_name']) . ' (Code: ' . $subject_code . ') | 
                          <i class="fa fa-trophy"></i> Max Marks: ' . $full_marks . '
                      </small>
                  </div>
                  <div class="table-controls">
                      <div class="input-group input-group-sm" style="width: 150px;">
                          <div class="input-group-prepend">
                              <span class="input-group-text"><i class="fa fa-search"></i></span>
                          </div>
                          <input type="text" class="form-control form-control-sm" id="studentSearch" placeholder="Search...">
                      </div>
                      <select class="form-control form-control-sm ml-2" id="rowsPerPage" style="width: 80px;">
                          <option value="10">10 rows</option>
                          <option value="25" selected>25 rows</option>
                          <option value="50">50 rows</option>
                          <option value="100">100 rows</option>
                          <option value="500">All</option>
                      </select>
                  </div>
              </div>
          </div>';

$output .= '<div class="table-responsive">';
$output .= '<table class="table table-bordered table-hover" id="studentsTable">';
$output .= '<thead>';
$output .= '<tr>';
$output .= '<th width="5%" class="text-center" data-sort="sn">S.N.</th>';
$output .= '<th width="15%" class="text-center d-none d-md-table-cell" data-sort="regd">Regd/EMIS No.</th>';
$output .= '<th width="25%" data-sort="name">Student Name</th>';
$output .= '<th width="10%" class="text-center d-none d-sm-table-cell" data-sort="symbol">Symbol No.</th>';
$output .= '<th width="15%" class="text-center" data-sort="marks">Marks</th>';
$output .= '<th width="20%" class="d-none d-sm-table-cell">Remarks</th>';
$output .= '<th width="10%" class="text-center" data-sort="status">Status</th>';
$output .= '</tr>';
$output .= '</thead>';
$output .= '<tbody id="tableBody">';

$sn = 1;
$students_data = []; // Store data for JavaScript

while ($student = $student_result->fetch_assoc()) {
    $student_id = $student['student_id'];
    $student_name = htmlspecialchars($student['name']);
    
    // Determine symbol number
    $symbol_no = !empty($student['exam_symbol_no']) ? $student['exam_symbol_no'] : $student['symbol_no'];
    
    // Determine Regd/EMIS number
    $regd_no = !empty($student['registration_no']) ? $student['registration_no'] : $student['regd_id'];
    if (empty($regd_no)) {
        $regd_no = 'N/A';
    }
    
    // Check if marks already exist
    $has_existing_marks = isset($existing_marks[$student_id]);
    $existing_mark_value = $has_existing_marks ? $existing_marks[$student_id] : '';
    
    $status_class = $has_existing_marks ? 'success' : 'warning';
    $status_text = $has_existing_marks ? 'Entered' : 'Pending';
    $status_icon = $has_existing_marks ? 'fa-check' : 'fa-clock-o';
    $status_badge = $has_existing_marks ? '<span class="badge badge-success"><i class="fa fa-check"></i> Entered</span>' : 
                                          '<span class="badge badge-warning"><i class="fa fa-clock-o"></i> Pending</span>';
    
    // Store student data for JavaScript
    $students_data[] = [
        'sn' => $sn,
        'regd' => $regd_no,
        'name' => $student_name,
        'symbol' => $symbol_no,
        'student_id' => $student_id,
        'existing_mark' => $existing_mark_value,
        'status' => $has_existing_marks ? 'entered' : 'pending'
    ];
    
    // For initial display, show first 25 rows
    $display_class = $sn <= 25 ? '' : 'd-none';
    
    $output .= '<tr class="student-row ' . $display_class . '" data-student-id="' . $student_id . '" data-sn="' . $sn . '">';
    $output .= '<td class="text-center font-weight-bold">' . $sn . '</td>';
    $output .= '<td class="text-center d-none d-md-table-cell">' . htmlspecialchars($regd_no) . '</td>';
    $output .= '<td>
                   <div class="student-name">' . $student_name . '</div>
                   <div class="small text-muted d-md-none">
                       <span class="mr-2"><i class="fa fa-id-card"></i> ' . htmlspecialchars($regd_no) . '</span>
                       <span><i class="fa fa-hashtag"></i> ' . htmlspecialchars($symbol_no) . '</span>
                   </div>
               </td>';
    $output .= '<td class="text-center d-none d-sm-table-cell text-primary font-weight-bold">' . htmlspecialchars($symbol_no) . '</td>';
    
    // Marks input cell
    $output .= '<td class="text-center">';
    $output .= '<input type="number" 
                         name="marks[' . $student_id . ']" 
                         class="marks-input form-control text-center" 
                         data-max="' . $full_marks . '"
                         data-student-id="' . $student_id . '"
                         step="0.01"
                         min="0"
                         max="' . $full_marks . '"
                         value="' . htmlspecialchars($existing_mark_value) . '"
                         placeholder="Enter"
                         style="width: 80px; display: inline-block; height: 32px; font-size: 13px;">';
    $output .= '<div class="small text-muted mt-1">Max: ' . $full_marks . '</div>';
    $output .= '</td>';
    
    // Remarks input cell - hidden on xs screens
    $output .= '<td class="d-none d-sm-table-cell">';
    $output .= '<input type="text" 
                         name="remarks[' . $student_id . ']" 
                         class="form-control form-control-sm" 
                         placeholder="Optional..."
                         style="height: 32px; font-size: 13px;">';
    $output .= '</td>';
    
    // Status cell
    $output .= '<td class="text-center">' . $status_badge . '</td>';
    
    $output .= '</tr>';
    
    $sn++;
}

$output .= '</tbody>';
$output .= '</table>';
$output .= '</div>';

// Pagination controls
$output .= '<div class="pagination-controls mt-3">
              <nav aria-label="Student pagination">
                <div class="d-flex justify-content-between align-items-center">
                  <div>
                    <small class="text-muted" id="pageInfo">Showing 1-25 of ' . $total_students . ' students</small>
                  </div>
                  <ul class="pagination pagination-sm mb-0" id="pagination">
                    <li class="page-item disabled" id="prevPage">
                      <a class="page-link" href="#" aria-label="Previous">
                        <span aria-hidden="true">&laquo;</span>
                      </a>
                    </li>
                    <!-- Page numbers will be inserted here by JavaScript -->
                    <li class="page-item" id="nextPage">
                      <a class="page-link" href="#" aria-label="Next">
                        <span aria-hidden="true">&raquo;</span>
                      </a>
                    </li>
                  </ul>
                  <div>
                    <small class="text-muted">
                      <i class="fa fa-info-circle"></i> Use W/S keys to navigate inputs
                    </small>
                  </div>
                </div>
              </nav>
            </div>';

// Add hidden inputs for form submission
$output .= '<input type="hidden" name="class_id" value="' . $class_id . '">';
$output .= '<input type="hidden" name="section_id" value="' . $section_id . '">';
$output .= '<input type="hidden" name="exam_id" value="' . $exam_id . '">';
$output .= '<input type="hidden" name="subject_id" value="' . $subject_id . '">';
$output .= '<input type="hidden" name="mark_type" value="' . $mark_type . '">';
$output .= '<input type="hidden" name="teacher_id" value="' . $teacher_id . '">';
$output .= '<input type="hidden" name="full_marks" value="' . $full_marks . '">';
$output .= '<input type="hidden" name="academic_year_id" value="' . $academic_year_id . '">';
$output .= '<input type="hidden" name="subject_code" value="' . $subject_code . '">';

// Add JavaScript for table functionality
$output .= '<script>
$(document).ready(function() {
    // Students data from PHP
    const studentsData = ' . json_encode($students_data) . ';
    const totalStudents = ' . $total_students . ';
    const fullMarks = ' . $full_marks . ';
    
    let currentPage = 1;
    let rowsPerPage = 25;
    let filteredStudents = [...studentsData];
    
    // Initialize pagination
    function initPagination() {
        rowsPerPage = parseInt($("#rowsPerPage").val());
        if(rowsPerPage === 500) rowsPerPage = totalStudents;
        
        const totalPages = Math.ceil(filteredStudents.length / rowsPerPage);
        currentPage = Math.min(currentPage, totalPages) || 1;
        
        updatePaginationButtons(totalPages);
        displayPage(currentPage);
        updatePageInfo();
    }
    
    // Display specific page
    function displayPage(page) {
        $(".student-row").addClass("d-none");
        
        const start = (page - 1) * rowsPerPage;
        const end = start + rowsPerPage;
        
        // Show rows for current page
        for(let i = start; i < end && i < filteredStudents.length; i++) {
            const studentId = filteredStudents[i].student_id;
            $(`tr[data-student-id="${studentId}"]`).removeClass("d-none");
        }
    }
    
    // Update pagination buttons
    function updatePaginationButtons(totalPages) {
        const $pagination = $("#pagination");
        $pagination.find(".page-number").remove();
        
        // Add page numbers
        const maxPagesToShow = 5;
        let startPage = Math.max(1, currentPage - Math.floor(maxPagesToShow / 2));
        let endPage = Math.min(totalPages, startPage + maxPagesToShow - 1);
        
        if(endPage - startPage + 1 < maxPagesToShow) {
            startPage = Math.max(1, endPage - maxPagesToShow + 1);
        }
        
        for(let i = startPage; i <= endPage; i++) {
            const active = i === currentPage ? " active" : "";
            $(\'<li class="page-item page-number\' + active + \'"><a class="page-link" href="#" data-page="\' + i + \'">\' + i + \'</a></li>\')
                .insertBefore("#nextPage");
        }
        
        // Update prev/next buttons
        $("#prevPage").toggleClass("disabled", currentPage === 1);
        $("#nextPage").toggleClass("disabled", currentPage === totalPages);
    }
    
    // Update page info text
    function updatePageInfo() {
        const start = (currentPage - 1) * rowsPerPage + 1;
        const end = Math.min(currentPage * rowsPerPage, filteredStudents.length);
        $("#pageInfo").text(`Showing ${start}-${end} of ${filteredStudents.length} students`);
    }
    
    // Search functionality
    $("#studentSearch").on("input", function() {
        const searchTerm = $(this).val().toLowerCase();
        
        if(searchTerm === "") {
            filteredStudents = [...studentsData];
        } else {
            filteredStudents = studentsData.filter(student => 
                student.name.toLowerCase().includes(searchTerm) ||
                student.regd.toLowerCase().includes(searchTerm) ||
                student.symbol.toLowerCase().includes(searchTerm)
            );
        }
        
        currentPage = 1;
        initPagination();
    });
    
    // Rows per page change
    $("#rowsPerPage").change(function() {
        currentPage = 1;
        initPagination();
    });
    
    // Pagination click handlers
    $(document).on("click", ".page-link", function(e) {
        e.preventDefault();
        
        if($(this).parent().hasClass("disabled")) return;
        
        const action = $(this).attr("aria-label");
        const pageNum = $(this).data("page");
        
        if(action === "Previous") {
            currentPage--;
        } else if(action === "Next") {
            currentPage++;
        } else if(pageNum) {
            currentPage = pageNum;
        }
        
        initPagination();
    });
    
    // Initialize
    initPagination();
    
    // Lock existing marks
    $(".marks-input").each(function() {
        const marks = $(this).val().trim();
        if(marks !== "" && !isNaN(marks) && parseFloat(marks) > 0) {
            $(this).addClass("locked")
                   .prop("readonly", true)
                   .css({
                       "background-color": "#f0f9ff",
                       "border-color": "#93c5fd",
                       "color": "#1e40af",
                       "font-weight": "600"
                   })
                   .attr("title", "Marks already entered");
        }
    });
    
    // Marks input validation
    $(".marks-input").on("input", function() {
        const $input = $(this);
        const marks = $input.val().trim();
        const studentId = $input.data("student-id");
        const $row = $(`tr[data-student-id="${studentId}"]`);
        const $badge = $row.find(".badge");
        
        if(marks === "") {
            $input.removeClass("is-invalid is-valid");
            $badge.removeClass("badge-success").addClass("badge-warning")
                  .html(\'<i class="fa fa-clock-o"></i> Pending\');
        } else if(isNaN(marks) || marks < 0) {
            $input.addClass("is-invalid").removeClass("is-valid");
        } else if(parseFloat(marks) > fullMarks) {
            $input.addClass("is-invalid").removeClass("is-valid");
        } else {
            $input.removeClass("is-invalid").addClass("is-valid");
            $badge.removeClass("badge-warning").addClass("badge-success")
                  .html(\'<i class="fa fa-check"></i> Entered\');
        }
    });
    
    // 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(direction) {
        const inputs = $(".marks-input:not(.locked):visible");
        if(inputs.length === 0) return;
        
        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);
            }
        }
        
        const targetInput = inputs.eq(currentInputIndex);
        targetInput.focus().addClass("highlight");
        
        // Scroll to input
        const inputPosition = targetInput.offset().top;
        const scrollPosition = $(window).scrollTop();
        const windowHeight = $(window).height();
        
        if(inputPosition < scrollPosition || inputPosition > scrollPosition + windowHeight - 100) {
            $("html, body").animate({
                scrollTop: inputPosition - 100
            }, 200);
        }
    }
    
    // Table sorting
    $("th[data-sort]").on("click", function() {
        const column = $(this).data("sort");
        const direction = $(this).hasClass("sorted-asc") ? "desc" : "asc";
        
        // Clear previous sorting
        $("th[data-sort]").removeClass("sorted-asc sorted-desc");
        $(this).addClass("sorted-" + direction);
        
        // Sort data
        filteredStudents.sort((a, b) => {
            let aVal = a[column];
            let bVal = b[column];
            
            if(column === "sn" || column === "marks") {
                aVal = parseFloat(aVal) || 0;
                bVal = parseFloat(bVal) || 0;
                return direction === "asc" ? aVal - bVal : bVal - aVal;
            }
            
            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;
        });
        
        // Re-render table
        renderTable();
        initPagination();
    });
    
    function renderTable() {
        const $tbody = $("#tableBody");
        $tbody.empty();
        
        filteredStudents.forEach((student, index) => {
            const statusBadge = student.status === "entered" 
                ? \'<span class="badge badge-success"><i class="fa fa-check"></i> Entered</span>\'
                : \'<span class="badge badge-warning"><i class="fa fa-clock-o"></i> Pending</span>\';
            
            const row = `
                <tr class="student-row d-none" data-student-id="${student.student_id}" data-sn="${index + 1}">
                    <td class="text-center font-weight-bold">${index + 1}</td>
                    <td class="text-center d-none d-md-table-cell">${student.regd}</td>
                    <td>
                        <div class="student-name">${student.name}</div>
                        <div class="small text-muted d-md-none">
                            <span class="mr-2"><i class="fa fa-id-card"></i> ${student.regd}</span>
                            <span><i class="fa fa-hashtag"></i> ${student.symbol}</span>
                        </div>
                    </td>
                    <td class="text-center d-none d-sm-table-cell text-primary font-weight-bold">${student.symbol}</td>
                    <td class="text-center">
                        <input type="number" 
                               name="marks[${student.student_id}]" 
                               class="marks-input form-control text-center" 
                               data-max="${fullMarks}"
                               data-student-id="${student.student_id}"
                               step="0.01"
                               min="0"
                               max="${fullMarks}"
                               value="${student.existing_mark}"
                               placeholder="Enter"
                               style="width: 80px; display: inline-block; height: 32px; font-size: 13px;">
                        <div class="small text-muted mt-1">Max: ${fullMarks}</div>
                    </td>
                    <td class="d-none d-sm-table-cell">
                        <input type="text" 
                               name="remarks[${student.student_id}]" 
                               class="form-control form-control-sm" 
                               placeholder="Optional..."
                               style="height: 32px; font-size: 13px;">
                    </td>
                    <td class="text-center">${statusBadge}</td>
                </tr>
            `;
            
            $tbody.append(row);
        });
        
        // Re-apply locked status
        $(".marks-input").each(function() {
            const marks = $(this).val().trim();
            if(marks !== "" && !isNaN(marks) && parseFloat(marks) > 0) {
                $(this).addClass("locked")
                       .prop("readonly", true)
                       .css({
                           "background-color": "#f0f9ff",
                           "border-color": "#93c5fd",
                           "color": "#1e40af",
                           "font-weight": "600"
                       })
                       .attr("title", "Marks already entered");
            }
        });
        
        // Re-attach event handlers
        $(".marks-input").on("input", function() {
            const $input = $(this);
            const marks = $input.val().trim();
            const studentId = $input.data("student-id");
            const $row = $(`tr[data-student-id="${studentId}"]`);
            const $badge = $row.find(".badge");
            
            if(marks === "") {
                $input.removeClass("is-invalid is-valid");
                $badge.removeClass("badge-success").addClass("badge-warning")
                      .html(\'<i class="fa fa-clock-o"></i> Pending\');
            } else if(isNaN(marks) || marks < 0) {
                $input.addClass("is-invalid").removeClass("is-valid");
            } else if(parseFloat(marks) > fullMarks) {
                $input.addClass("is-invalid").removeClass("is-valid");
            } else {
                $input.removeClass("is-invalid").addClass("is-valid");
                $badge.removeClass("badge-warning").addClass("badge-success")
                      .html(\'<i class="fa fa-check"></i> Entered\');
            }
        });
    }
});
</script>';

echo $output;

// Close statement
if (isset($student_stmt)) {
    $student_stmt->close();
}
$conn->close();
?>