$(document).ready(function () {
    const $searchForm = $('#searchForm');
    const $resultsSection = $('#resultsSection');
    const $resultsTableBody = $('#resultsTableBody');
    const $attendanceModal = new bootstrap.Modal(document.getElementById('attendanceModal'));
    const $attendanceForm = $('#attendanceForm');
    const $formAlert = $('#formAlert');

    let currentStudents = [];


    // Search for Students
    $searchForm.on('submit', function (e) {
        e.preventDefault();

        const darja = $('#darja').val();
        const year = $('#yearInput').val();

        if (!darja || !year) {
            showAlert('درجہ اور سال منتخب کریں', 'danger');
            return;
        }

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

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

    function renderTable() {
        let html = '';
        if (currentStudents.length === 0) {
            html = '<tr><td colspan="7" 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">
                            <button type="button" class="btn btn-link p-0 text-decoration-none text-primary fs-5 btn-open-attendance" 
                                    data-sno="${student.sno}" 
                                    data-name="${student.stdName}" 
                                    data-father="${student.fatherName}"
                                    data-darja="${student.darjaSno}">
                                ${student.stdName} <span class="text-muted small mx-1">ولد</span> ${student.fatherName}
                            </button>
                        </td>
                        <td class="text-center">${student.registrationNo}</td>
                        <td class="text-center">${student.dob}</td>
                        <td class="text-center">${student.RollNumber}</td>
                        <td><small>${student.permanentAddress}</small></td>
                        <td class="text-center"><span class="badge bg-light text-dark border">${student.darjaName}</span></td>
                    </tr>
                `;
            });
        }
        $resultsTableBody.html(html);
    }

    // Open Attendance Modal
    $(document).on('click', '.btn-open-attendance', function () {
        const sno = $(this).data('sno');
        const name = $(this).data('name');
        const father = $(this).data('father');
        const darja = $(this).data('darja');

        $('#stdSno').val(sno);
        $('#darjaSno').val(darja);
        $('#modalStudentName').text(`${name} ولد ${father}`);

        $attendanceModal.show();
    });

    // Handle Attendance Form Submit
    $attendanceForm.on('submit', function (e) {
        e.preventDefault();

        const stdSno = $('#stdSno').val();
        const darjaSno = $('#darjaSno').val();
        const status = $('input[name="attendanceStatus"]:checked').val();
        const dateAtt = $('#attendanceDate').val();

        if (!dateAtt) {
            Swal.fire('توجہ', 'تاریخ منتخب کریں', 'warning');
            return;
        }

        const $btn = $attendanceForm.find('button[type="submit"]');
        $btn.prop('disabled', true).html('<span class="spinner-border spinner-border-sm me-2"></span>محفوظ ہو رہا ہے...');

        $.ajax({
            url: 'APIs/saveAttendance.php',
            method: 'POST',
            data: JSON.stringify({
                attendanceDate: dateAtt,
                darja: darjaSno,
                attendance: [{ regSno: stdSno, status: status }]
            }),
            contentType: 'application/json',
            success: function (response) {
                $btn.prop('disabled', false).html('<i class="bi bi-save me-2"></i>محفوظ کریں');
                if (response.success) {
                    $attendanceModal.hide();
                    Swal.fire('کامیابی', response.message, 'success');
                } else {
                    Swal.fire('توجہ', response.message, 'warning');
                }
            },
            error: function () {
                $btn.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>`);
    }
});
