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

    let currentStudents = [];


    // Step 1: Search for Students
    $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/getAttendanceData.php',
            method: 'GET',
            data: { darja: darja, promotionDate: pDate, dateEnd: dEnd },
            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="3" 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}
                            <div class="text-muted small opacity-75">${student.registrationNo}</div>
                        </td>
                        <td>
                            <div class="d-flex flex-wrap gap-3 justify-content-center">
                                <div class="form-check">
                                    <input class="form-check-input" type="radio" name="att_${student.sno}" 
                                           id="att_h_${student.sno}" value="ح" checked>
                                    <label class="form-check-label" for="att_h_${student.sno}">حاضر (P)</label>
                                </div>
                                <div class="form-check text-danger">
                                    <input class="form-check-input" type="radio" name="att_${student.sno}" 
                                           id="att_g_${student.sno}" value="غ">
                                    <label class="form-check-label" for="att_g_${student.sno}">غیر حاضر (A)</label>
                                </div>
                                <div class="form-check text-primary">
                                    <input class="form-check-input" type="radio" name="att_${student.sno}" 
                                           id="att_r_${student.sno}" value="ر">
                                    <label class="form-check-label" for="att_r_${student.sno}">رخصت (L)</label>
                                </div>
                                <div class="form-check text-warning">
                                    <input class="form-check-input" type="radio" name="att_${student.sno}" 
                                           id="att_b_${student.sno}" value="ب">
                                    <label class="form-check-label" for="att_b_${student.sno}">بیمار (S)</label>
                                </div>
                            </div>
                        </td>
                    </tr>
                `;
            });
        }
        $resultsTableBody.html(html);
        $btnSaveAttendance.prop('disabled', currentStudents.length === 0);
    }

    // Step 2: Save Attendance
    $btnSaveAttendance.on('click', function () {
        const aDate = $('#attendanceDate').val();
        const darja = $('#darja').val();

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

        const attendanceData = [];
        currentStudents.forEach(student => {
            const status = $(`input[name="att_${student.sno}"]:checked`).val();
            attendanceData.push({
                regSno: student.sno,
                status: status
            });
        });

        $btnSaveAttendance.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: aDate,
                darja: darja,
                attendance: attendanceData
            }),
            contentType: 'application/json',
            success: function (response) {
                $btnSaveAttendance.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 () {
                $btnSaveAttendance.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>`);
    }
});
