$(document).ready(function () {
    const $searchForm = $('#searchForm');
    const $resultsSection = $('#resultsSection');
    const $resultsTableBody = $('#resultsTableBody');
    const $subjectSelect = $('#subjects');
    const $totalMarksDisplay = $('#totalMarksDisplay');
    const $btnSaveResults = $('#btnSaveResults');
    const $formAlert = $('#formAlert');

    let currentStudents = [];
    let currentTotalMarks = 0;


    // Step 1: Search for Students and populate Subjects
    $searchForm.on('submit', function (e) {
        e.preventDefault();

        const darja = $('#darja').val();
        const pDate = $('#promotionDate').val();
        const dEnd = $('#dateEnd').val();

        if (!darja || !pDate || !dEnd) {
            showAlert('تمام معلومات منتخب کریں', 'danger');
            return;
        }

        $resultsSection.addClass('d-none');
        showAlert('ڈیٹا لوڈ ہو رہا ہے...', 'info');

        $.ajax({
            url: 'APIs/getResultData.php',
            method: 'GET',
            data: { darja: darja, promotionDate: pDate, dateEnd: dEnd },
            dataType: 'json',
            success: function (response) {
                if (response.success) {
                    currentStudents = response.students;
                    populateSubjects(response.subjects);
                    $resultsSection.removeClass('d-none');
                    showAlert('', ''); // Clear alert
                } else {
                    showAlert(response.message, 'warning');
                }
            },
            error: function () {
                showAlert('سرور سے رابطہ کرنے میں ناکامی آئی', 'danger');
            }
        });
    });

    function populateSubjects(subjects) {
        let html = '<option value=""></option>';
        subjects.forEach(sub => {
            html += `<option value="${sub.sno}">${sub.subjectName}</option>`;
        });
        $subjectSelect.html(html);
        $totalMarksDisplay.text('0');
        renderTable(); // Clear table
    }

    // Step 2: Handle Subject Selection
    $subjectSelect.on('change', function () {
        const subjectSno = $(this).val();
        if (!subjectSno) {
            currentTotalMarks = 0;
            $totalMarksDisplay.text('0');
            renderTable();
            return;
        }

        $.ajax({
            url: 'APIs/getSubjectDetails.php',
            method: 'GET',
            data: { subject_sno: subjectSno },
            success: function (response) {
                if (response.success) {
                    currentTotalMarks = response.totalMarks;
                    $totalMarksDisplay.text(currentTotalMarks);
                    renderTable();
                } else {
                    Swal.fire('غلطی', 'مضمون کی تفصیلات نہیں مل سکیں', 'error');
                }
            }
        });
    });

    function renderTable() {
        let html = '';
        if (currentStudents.length === 0) {
            html = '<tr><td colspan="4" class="text-center text-muted">کوئی طالب علم نہیں ملا</td></tr>';
        } else {
            currentStudents.forEach((student, index) => {
                html += `
                    <tr>
                        <td class="text-center">${index + 1}</td>
                        <td class="fw-bold ps-3">${student.stdName} <span class="text-muted small mx-1">ولد</span> ${student.fatherName}</td>
                        <td class="text-center">
                            <input type="number" 
                                   class="form-control form-control-sm mx-auto mark-input text-center" 
                                   style="width: 80px;" 
                                   min="0" 
                                   max="${currentTotalMarks}" 
                                   data-std="${student.sno}" 
                                   value="0" 
                                   ${currentTotalMarks === 0 ? 'disabled' : ''}>
                        </td>
                        <td class="text-center text-primary fw-bold">${currentTotalMarks}</td>
                    </tr>
                `;
            });
        }
        $resultsTableBody.html(html);
        $btnSaveResults.prop('disabled', currentStudents.length === 0 || currentTotalMarks === 0);
    }

    // Step 3: Save Results
    $btnSaveResults.on('click', function () {
        const resultTerm = $('#resultTerm').val();
        const eduRemarks = $('#edu_year_remarks').val();
        const darja = $('#darja').val();
        const subjectSno = $subjectSelect.val();
        const pDate = $('#promotionDate').val();
        const dEnd = $('#dateEnd').val();

        if (!subjectSno || !resultTerm) {
            Swal.fire('توجہ', 'مضمون اور امتحان کی قسم منتخب کریں', 'warning');
            return;
        }

        const marks = [];
        $('.mark-input').each(function () {
            marks.push({
                stdSno: $(this).data('std'),
                obtMarks: $(this).val()
            });
        });

        $btnSaveResults.prop('disabled', true).html('<span class="spinner-border spinner-border-sm me-2"></span>محفوظ ہو رہا ہے...');

        $.ajax({
            url: 'APIs/saveResultBySubject.php',
            method: 'POST',
            data: JSON.stringify({
                darja: darja,
                subjectSno: subjectSno,
                promotionDate: pDate,
                dateEnd: dEnd,
                resultTerm: resultTerm,
                edu_year_remarks: eduRemarks,
                marks: marks
            }),
            contentType: 'application/json',
            success: function (response) {
                $btnSaveResults.prop('disabled', false).html('<i class="bi bi-save me-2"></i>محفوظ کیجیے');
                if (response.success) {
                    Swal.fire({
                        title: 'اطلاع',
                        text: response.message,
                        icon: response.message.includes('چھوڑ دیا گیا') ? 'warning' : 'success'
                    });
                } else {
                    Swal.fire('توجہ', response.message, 'warning');
                }
            },
            error: function () {
                $btnSaveResults.prop('disabled', false).html('<i class="bi bi-save me-2"></i>محفوظ کیجیے');
                Swal.fire('خرابی', 'محفوظ کرنے میں خرابی آئی', 'error');
            }
        });
    });

    function showAlert(message, type) {
        if (!message) {
            $formAlert.html('');
            return;
        }
        $formAlert.html(`<div class="alert alert-${type} alert-dismissible fade show" role="alert">
            ${message}
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>`);
    }

    // Validation for marks
    $(document).on('change', '.mark-input', function () {
        let val = parseFloat($(this).val());
        if (val > currentTotalMarks) {
            $(this).val(currentTotalMarks);
            Swal.fire('توجہ', `حاصل کردہ نمبر ${currentTotalMarks} سے زیادہ نہیں ہو سکتے`, 'warning');
        } else if (val < 0 || isNaN(val)) {
            $(this).val(0);
        }
    });
});
