$(document).ready(function () {
    const $searchForm = $('#searchForm');
    const $resultsSection = $('#resultsSection');
    const $resultsTableBody = $('#resultsTableBody');
    const $editModal = new bootstrap.Modal(document.getElementById('editAttendanceModal'));
    const $editForm = $('#editAttendanceForm');
    const $formAlert = $('#formAlert');

    let currentRecords = [];

    // Initialize Datepickers (if any others remain, like on other pages, but for this ID we use native date)
    // Removed jQuery datepick for #attendanceDateSearch to use native browser date picker

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

        const darja = $('#darja').val();
        const aDate = $('#attendanceDateSearch').val();

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

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

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

    function renderTable() {
        let html = '';
        if (currentRecords.length === 0) {
            html = '<tr><td colspan="5" class="text-center text-muted">کوئی ریکارڈ نہیں ملا</td></tr>';
        } else {
            currentRecords.forEach((record, index) => {
                const statusLabel = getStatusLabel(record.stdStatus);
                html += `
                    <tr id="row_${record.attSno}">
                        <td class="text-center">${index + 1}</td>
                        <td class="fw-bold ps-3">
                            ${record.stdName} <span class="text-muted small mx-1">ولد</span> ${record.fatherName}
                            <div class="text-muted small opacity-75">${record.registrationNo}</div>
                        </td>
                        <td class="text-center">
                            <span class="badge ${getStatusClass(record.stdStatus)} fs-6 fw-normal">
                                ${statusLabel}
                            </span>
                        </td>
                        <td class="text-center">
                            <button class="btn btn-outline-primary btn-sm rounded-pill px-3 me-2 btn-edit" 
                                    data-sno="${record.attSno}" 
                                    data-stdsno="${record.regSno}"
                                    data-name="${record.stdName}"
                                    data-status="${record.stdStatus}">
                                <i class="bi bi-pencil me-1"></i>تبدیل کریں
                            </button>
                        </td>
                        <td class="text-center">
                            <button class="btn btn-outline-danger btn-sm rounded-pill px-3 btn-delete" 
                                    data-sno="${record.attSno}">
                                <i class="bi bi-trash me-1"></i>حذف کریں
                            </button>
                        </td>
                    </tr>
                `;
            });
        }
        $resultsTableBody.html(html);
    }

    function getStatusLabel(status) {
        switch (status) {
            case 'ح': return 'حاضر';
            case 'غ': return 'غیر حاضر';
            case 'ر': return 'رخصت';
            case 'ب': return 'بیمار';
            default: return status;
        }
    }

    function getStatusClass(status) {
        switch (status) {
            case 'ح': return 'bg-success bg-opacity-10 text-success border border-success border-opacity-25';
            case 'غ': return 'bg-danger bg-opacity-10 text-danger border border-danger border-opacity-25';
            case 'ر': return 'bg-primary bg-opacity-10 text-primary border border-primary border-opacity-25';
            case 'ب': return 'bg-warning bg-opacity-10 text-warning border border-warning border-opacity-25';
            default: return 'bg-secondary bg-opacity-10 text-secondary';
        }
    }

    // Open Edit Modal
    $(document).on('click', '.btn-edit', function () {
        const sno = $(this).data('sno');
        const name = $(this).data('name');
        const status = $(this).data('status');

        $('#editAttSno').val(sno);
        $('#editStudentName').text(name);
        $(`input[name="editStatus"][value="${status}"]`).prop('checked', true);

        $editModal.show();
    });

    // Handle Edit Form Submit
    $editForm.on('submit', function (e) {
        e.preventDefault();
        const sno = $('#editAttSno').val();
        const status = $('input[name="editStatus"]:checked').val();

        $.ajax({
            url: 'APIs/updateAttendanceRecord.php',
            method: 'POST',
            data: JSON.stringify({ attSno: sno, status: status }),
            contentType: 'application/json',
            success: function (response) {
                if (response.success) {
                    $editModal.hide();
                    Swal.fire('کامیابی', response.message, 'success');
                    // Update the local record and re-render or just update the row
                    const record = currentRecords.find(r => r.attSno == sno);
                    if (record) record.stdStatus = status;
                    renderTable();
                } else {
                    Swal.fire('توجہ', response.message, 'warning');
                }
            },
            error: function () {
                Swal.fire('خرابی', 'حاضری تبدیل کرنے میں خرابی آئی', 'error');
            }
        });
    });

    // Handle Delete
    $(document).on('click', '.btn-delete', function () {
        const sno = $(this).data('sno');

        Swal.fire({
            title: 'کیا آپ واقعی اس حاضری کو حذف کرنا چاہتے ہیں؟',
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#d33',
            cancelButtonColor: '#3085d6',
            confirmButtonText: 'جی ہاں، حذف کریں',
            cancelButtonText: 'منسوخ کریں'
        }).then((result) => {
            if (result.isConfirmed) {
                $.ajax({
                    url: 'APIs/deleteAttendanceRecord.php',
                    method: 'POST',
                    data: JSON.stringify({ attSno: sno }),
                    contentType: 'application/json',
                    success: function (response) {
                        if (response.success) {
                            $(`#row_${sno}`).fadeOut(300, function () {
                                $(this).remove();
                                currentRecords = currentRecords.filter(r => r.attSno != sno);
                                if (currentRecords.length === 0) renderTable();
                            });
                            Swal.fire('حذف کر دی گئی!', response.message, 'success');
                        } else {
                            Swal.fire('غلطی', response.message, 'error');
                        }
                    },
                    error: function () {
                        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>`);
    }
});
