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

    let currentSubjects = [];
    let currentStudents = [];


    $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;
        }

        $btnSaveResults.prop('disabled', true);
        $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) {
                    currentSubjects = response.subjects;
                    currentStudents = response.students;
                    renderTable();
                    $resultsSection.removeClass('d-none');
                    showAlert('', ''); // Clear alert
                } else {
                    showAlert(response.message, 'warning');
                }
            },
            error: function () {
                showAlert('سرور سے رابطہ کرنے میں ناکامی آئی', 'danger');
            }
        });
    });

    function renderTable() {
        // Render Header
        let headerHtml = '<th class="bg-light">#</th><th class="bg-light">طالب علم کا نام</th>';
        currentSubjects.forEach(subject => {
            headerHtml += `<th class="text-center bg-light">${subject.subjectName}</th>`;
        });
        $subjectsHeader.html(headerHtml);

        // Render Body
        let bodyHtml = '';
        currentStudents.forEach((student, index) => {
            bodyHtml += `<tr>
                <td>${index + 1}</td>
                <td class="fw-bold">${student.stdName} <span class="text-muted small">ولد</span> ${student.fatherName}</td>`;

            currentSubjects.forEach(subject => {
                bodyHtml += `<td class="text-center">
                    <input type="number" 
                           class="form-control form-control-sm mx-auto mark-input" 
                           style="width: 70px;" 
                           min="0" max="100" 
                           data-std="${student.sno}" 
                           data-subject="${subject.sno}" 
                           value="0">
                </td>`;
            });
            bodyHtml += '</tr>';
        });
        $resultsTableBody.html(bodyHtml);
        $btnSaveResults.prop('disabled', currentStudents.length === 0);
    }

    $btnSaveResults.on('click', function () {
        const resultTerm = $('#resultTerm').val();
        const eduYearRemarks = $('#edu_year_remarks').val();
        const darja = $('#darja').val();
        const pDate = $('#promotionDate').val();
        const dEnd = $('#dateEnd').val();

        const results = [];
        const studentGroups = {};

        $('.mark-input').each(function () {
            const stdSno = $(this).data('std');
            const subjectSno = $(this).data('subject');
            const mark = parseInt($(this).val()) || 0;

            if (!studentGroups[stdSno]) {
                studentGroups[stdSno] = { stdSno: stdSno, marks: {} };
            }
            studentGroups[stdSno].marks[subjectSno] = mark;
        });

        for (const stdId in studentGroups) {
            results.push(studentGroups[stdId]);
        }

        if (results.length === 0) return;

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

        $.ajax({
            url: 'APIs/saveResults.php',
            method: 'POST',
            data: JSON.stringify({
                darja: darja,
                promotionDate: pDate,
                dateEnd: dEnd,
                resultTerm: resultTerm,
                eduYearRemarks: eduYearRemarks,
                results: results
            }),
            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: 'success',
                        confirmButtonText: 'ٹھیک ہے',
                        customClass: {
                            confirmButton: 'btn btn-success'
                        }
                    });
                } else {
                    Swal.fire({
                        title: 'غلطی',
                        text: response.message,
                        icon: 'error',
                        confirmButtonText: 'ٹھیک ہے',
                        customClass: {
                            confirmButton: 'btn btn-danger'
                        }
                    });
                }
            },
            error: function () {
                $btnSaveResults.prop('disabled', false).html('<i class="bi bi-save me-2"></i>محفوظ کیجیے');
                Swal.fire({
                    title: 'خرابی',
                    text: 'محفوظ کرنے میں خرابی آئی',
                    icon: 'error',
                    confirmButtonText: 'ٹھیک ہے'
                });
            }
        });
    });

    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 = parseInt($(this).val());
        if (val > 100) {
            $(this).val(100);
            alert('حاصل کردہ نمبر 100 سے زیادہ نہیں ہو سکتے');
        } else if (val < 0 || isNaN(val)) {
            $(this).val(0);
        }
    });
});
