$(document).ready(function () {
    $('#attendanceReportForm').on('submit', function (e) {
        e.preventDefault();

        const btnSubmit = $('#btnShowReport');
        const originalHtml = btnSubmit.html();
        btnSubmit.prop('disabled', true).html('<i class="fa fa-spinner fa-spin"></i> لوڈ ہو رہا ہے...');

        const darja = $('#darja').val();
        const date1 = $('#date1').val();
        const date2 = $('#date2').val();

        if (!darja || !date1 || !date2) {
            Swal.fire('توجہ فرمائیں', 'تمام مطلوبہ معلومات مہیا کریں', 'warning');
            btnSubmit.prop('disabled', false).html(originalHtml);
            return;
        }

        $.ajax({
            url: 'APIs/attendance_report.php',
            type: 'POST',
            data: {
                action: 'fetch',
                darja: darja,
                date1: date1,
                date2: date2
            },
            dataType: 'json',
            success: function (response) {
                if (response.success && response.data.length > 0) {
                    renderAttendanceGrid(response.data, response.meta);
                } else {
                    $('#reportContainer').html('');
                    Swal.fire({
                        icon: 'info',
                        title: 'نتیجہ',
                        text: response.message || 'اس معیار پر کوئی ریکارڈ نہیں ملا'
                    });
                }
            },
            error: function () {
                Swal.fire({ icon: 'error', title: 'Error', text: 'سرور سے رابطہ نہیں ہو سکا' });
            },
            complete: function () {
                btnSubmit.prop('disabled', false).html(originalHtml);
            }
        });
    });
});

function renderAttendanceGrid(students, meta) {
    const dates = meta.dates; // array of objects {greg, hDay, hMonth, hMonthName, hYear}
    const displayDates = [...dates].reverse(); // RTL: newest dates appear leftmost visually

    // Group consecutive dates by Hijri month to build colspan month-name headers
    const monthGroups = [];
    let currentGroup = null;
    displayDates.forEach(d => {
        const key = d.hYear + '-' + d.hMonth;
        if (!currentGroup || currentGroup.key !== key) {
            currentGroup = { key, name: d.hMonthName, count: 0 };
            monthGroups.push(currentGroup);
        }
        currentGroup.count++;
    });

    const totalCols = displayDates.length + 5; // 3 fixed + days + summary + keyifiyat

    let html = `
    <table class="table attendance-grid urdu-regular shadow-sm mb-0" dir="rtl">
        <thead>
            <tr class="table-dark">
                <th colspan="${totalCols}" class="py-2 fs-5">
                    رجسٹر روزانہ حاضری &nbsp;&nbsp;|&nbsp;&nbsp; 
                    درجہ: ${meta.darjaName} &nbsp;&nbsp;|&nbsp;&nbsp; 
                    بابت ماہ: ${meta.dateStart} تا ${meta.dateEnd}
                </th>
            </tr>
            <!-- Row 1: Month names spanning their day columns -->
            <tr>
                <th colspan="3" style="border-bottom: none;"></th>`;

    monthGroups.forEach(group => {
        html += `<th colspan="${group.count}" class="month-header-name text-center">${group.name}</th>`;
    });

    html += `
                <th colspan="2" style="border-bottom: none;"></th>
            </tr>
            <!-- Row 2: Fixed column labels + individual Hijri day numbers -->
            <tr>
                <th style="width: 50px;">سیریل نمبر</th>
                <th style="min-width: 150px;">نام طالب علم</th>
                <th style="min-width: 120px;">ولدیت</th>`;

    displayDates.forEach(d => {
        html += `<th>${d.hDay || ''}</th>`;
    });

    html += `
                <th class="summary-group">
                    <table class="summary-table">
                        <tr class="summary-header"><td colspan="4">میزان</td></tr>
                        <tr class="summary-header">
                            <td>ح</td><td>غ</td><td>ر</td><td>ب</td>
                        </tr>
                    </table>
                </th>
                <th style="width: 100px;">کیفیت</th>
            </tr>
        </thead>
        <tbody>`;

    students.forEach((student, index) => {
        const grid = student.attendanceGrid;
        const counters = student.counters;

        html += `
            <tr data-std-sno="${student.sno}">
                <td>${index + 1}</td>
                <td class="text-end fw-bold">${student.stdName}</td>
                <td class="text-end opacity-75">${student.fatherName}</td>`;

        displayDates.forEach(d => {
            const date = d.greg;
            const status = grid[date] || 'ح';
            let statusClass = '';
            if (status === 'غ') statusClass = 'ghair-hazir';
            else if (status === 'ر') statusClass = 'rokhsat';
            else if (status === 'ب') statusClass = 'bemar';
            else statusClass = 'hazir';

            html += `<td class="day-cell ${statusClass}" 
                        onclick="openUpdateModal('${student.sno}', '${date}', '${status}')"
                        data-date="${date}">
                        ${status}
                    </td>`;
        });

        html += `
                <td class="summary-group">
                    <table class="summary-table h-100">
                        <tr>
                            <td class="summary-val">${counters.hazir}</td>
                            <td class="summary-val text-danger">${counters.ghairHazir}</td>
                            <td class="summary-val text-warning">${counters.rokhsat}</td>
                            <td class="summary-val text-info">${counters.bemar}</td>
                        </tr>
                    </table>
                </td>
                <td class="small urdu-regular">${student.mezaan || ''}</td>
            </tr>`;
    });

    html += `</tbody></table>`;
    $('#reportContainer').html(html);
}

function openUpdateModal(stdSno, date, currentStatus) {
    $('#modalStdSno').val(stdSno);
    $('#modalDate').val(date);

    // Highlight current selection in UI if wanted, but button style change is enough
    $('#updateAttendanceModal .btn').removeClass('active');
    $(`#updateAttendanceModal .btn:contains('${currentStatus}')`).addClass('active');

    $('#updateAttendanceModal').modal('show');
}

function submitAttendance(status) {
    const stdSno = $('#modalStdSno').val();
    const date = $('#modalDate').val();

    if (!stdSno || !date || !status) return;

    // Show loading on buttons
    const modalBtn = $('#updateAttendanceModal .btn');
    modalBtn.prop('disabled', true);

    $.ajax({
        url: 'APIs/attendance_report.php',
        type: 'POST',
        data: {
            action: 'update_attendance',
            stdSno: stdSno,
            date: date,
            status: status,
            darja: $('#darja').val()
        },
        dataType: 'json',
        success: function (response) {
            if (response.success) {
                $('#updateAttendanceModal').modal('hide');
                // Proactively refresh the report to show new totals and highlights
                $('#attendanceReportForm').trigger('submit');
            } else {
                Swal.fire('Error', response.message || 'Update failed', 'error');
            }
        },
        error: function () {
            Swal.fire('Error', 'Communication error', 'error');
        },
        complete: function () {
            modalBtn.prop('disabled', false);
        }
    });
}
