$(document).ready(function () {

    let lastReportData = null;

    // === Show Report ===
    $('#btnShowReport').on('click', function () {
        const darjaSno = $('#rpt_darja').val();
        const dateStart = $('#rpt_date_start').val();
        const dateEnd = $('#rpt_date_end').val();

        if (!darjaSno) {
            Swal.fire({ icon: 'warning', title: 'توجہ', text: 'برائے مہربانی درجہ منتخب کریں', confirmButtonText: 'ٹھیک ہے' });
            return;
        }

        fetchReport(darjaSno, dateStart, dateEnd);
    });

    // === Print Report ===
    $('#btnPrintReport').on('click', function () {
        printReport();
    });

    // === Fetch Report Data ===
    function fetchReport(darjaSno, dateStart, dateEnd) {
        $('#rpt-results').html(
            '<div class="text-center p-5">' +
            '<div class="spinner-border text-primary" role="status"></div>' +
            '<p class="mt-3 urdu-regular fs-5">رپورٹ تیار ہو رہی ہے...</p>' +
            '</div>'
        );
        $('#btnPrintReport').addClass('d-none');
        lastReportData = null;

        $.ajax({
            url: 'APIs/registered_student_report.php',
            method: 'POST',
            contentType: 'application/json',
            data: JSON.stringify({
                darja_sno: darjaSno,
                date_start: dateStart,
                date_end: dateEnd
            }),
            dataType: 'json',
            success: function (res) {
                if (res.success) {
                    lastReportData = res;
                    renderReport(res);
                    $('#btnPrintReport').removeClass('d-none');
                } else {
                    $('#rpt-results').html(
                        '<div class="alert alert-warning urdu-regular text-end fs-5 mt-4"><i class="bi bi-exclamation-triangle ms-2"></i>' + res.message + '</div>'
                    );
                }
            },
            error: function () {
                $('#rpt-results').html(
                    '<div class="alert alert-danger urdu-regular text-end fs-5 mt-4"><i class="bi bi-x-circle ms-2"></i>سرور سے رابطہ کرنے میں ناکامی</div>'
                );
            }
        });
    }

    // === Render Report Table (Screen UI) ===
    function renderReport(res) {
        let rows = '';
        res.students.forEach((s, i) => {
            rows += `
                <tr>
                    <td class="text-center">${i + 1}</td>
                    <td class="fw-bold">${s.stdName}</td>
                    <td class="fw-bold">${s.fatherName}</td>
                    <td class="text-center">${s.registrationNo}</td>
                    <td class="text-center">${s.dob}</td>
                    <td class="text-center">${s.RollNumber}</td>
                    <td class="small urdu-regular">${s.permanentAddress}</td>
                    <td class="text-center">
                        <a href="reportAdmissionForm?sno=${s.sno}" target="_blank" class="btn btn-sm btn-outline-info rounded-pill">
                            <i class="bi bi-file-earmark-text"></i> داخلہ فارم
                        </a>
                    </td>
                </tr>`;
        });

        const html = `
            <div class="card border-0 shadow-sm rounded-4 overflow-hidden mt-4 text-end animate__animated animate__fadeIn">
                <div class="card-header bg-white border-bottom py-3 px-4 d-flex justify-content-between align-items-center">
                    <div>
                        <h5 class="fw-bold text-primary mb-1 urdu-regular fs-4">${res.madrasaName}</h5>
                        <p class="text-muted mb-0 urdu-regular small">
                            ${res.madrasaAddress} ${res.madrasaAddressL}
                            ${res.madrasaPhone ? ' | فون: <span dir="ltr">' + res.madrasaPhone + '</span>' : ''}
                        </p>
                    </div>
                    <div class="text-start">
                        <h4 class="fw-bold mb-1 urdu-regular">داخل شدہ طلباء کی لسٹ</h4>
                        <p class="mb-0 urdu-regular fs-5">المرحلۃ: <strong>${res.darjaName}</strong></p>
                    </div>
                </div>
                <div class="card-body p-0">
                    <div class="table-responsive">
                        <table class="table table-bordered table-hover align-middle mb-0 text-end urdu-regular">
                            <thead class="table-light">
                                <tr class="text-center">
                                    <th style="width:50px">الرقم</th>
                                    <th>اسم الطالب</th>
                                    <th>اسم الاب</th>
                                    <th>رجسٹریشن نمبر</th>
                                    <th>تاریخِ پیدائش</th>
                                    <th>رول نمبر</th>
                                    <th>مستقل پتہ</th>
                                    <th>داخلہ فارم</th>
                                </tr>
                            </thead>
                            <tbody class="fs-5">${rows}</tbody>
                        </table>
                    </div>
                </div>
            </div>`;

        $('#rpt-results').html(html);
    }

    // === Professional Print Function ===
    function printReport() {
        if (!lastReportData) return;

        const res = lastReportData;
        const students = res.students;

        const tdStyle = 'border:1px solid #999; padding:8px; text-align:right; font-size:18px;';
        const tdCtrStyle = 'border:1px solid #999; padding:8px; text-align:center; font-size:18px;';
        const thStyle = 'border:1px solid #777; padding:10px; text-align:center; background:#f4f4f4; font-size:18px; font-weight:bold;';

        let rows = '';
        students.forEach((s, i) => {
            rows += `
                <tr>
                    <td style="${tdCtrStyle}">${i + 1}</td>
                    <td style="${tdStyle} font-weight:bold;">${s.stdName}</td>
                    <td style="${tdStyle}">${s.fatherName}</td>
                    <td style="${tdCtrStyle}">${s.registrationNo}</td>
                    <td style="${tdCtrStyle}">${s.dob}</td>
                    <td style="${tdCtrStyle}">${s.RollNumber}</td>
                    <td style="${tdStyle} font-size:11px;">${s.permanentAddress}</td>
                </tr>`;
        });

        const printWindow = window.open('', '_blank', 'width=1150,height=850');
        printWindow.document.open();
        printWindow.document.write(`
<!DOCTYPE html>
<html dir="rtl" lang="ur">
<head>
    <meta charset="UTF-8">
    <title>داخل شدہ طلباء - ${res.darjaName}</title>
    <style>
        @page { margin: 10mm; size: A4 landscape; }
        body { font-family: 'Jameel Noori Nastaleeq', 'Noto Nastaliq Urdu', Tahoma, Arial; direction: rtl; margin: 0; padding: 0; }
        .header { border-bottom: 2px solid #333; padding-bottom: 12px; margin-bottom: 20px; }
        table { width: 100%; border-collapse: collapse; background:#fff; }
        .footer { margin-top: 25px; font-size: 11px; color: #555; text-align: center; border-top: 1px solid #ccc; padding-top: 10px; }
    </style>
</head>
<body onload="window.print(); window.close();">
    <div class="header">
        <table style="border:0">
            <tr>
                <td style="text-align:right">
                    <h1 style="margin:0; font-size:26px;">${res.madrasaName}</h1>
                    <p style="margin:6px 0 0; font-size:14px;">${res.madrasaAddress} ${res.madrasaAddressL}</p>
                    ${res.madrasaPhone ? '<p style="margin:2px 0 0; font-size:12px;">فون: <span dir="ltr">' + res.madrasaPhone + '</span></p>' : ''}
                </td>
                <td style="text-align:center">
                    <h2 style="margin:0; font-size:22px;">داخل شدہ طلباء کی لسٹ</h2>
                    <p style="margin:8px 0 0; font-size:18px;">المرحلۃ: <strong>${res.darjaName}</strong></p>
                </td>
                <td style="text-align:left">
                    <p style="margin:0; font-size:12px;">تاریخ پرنٹ: ${new Date().toLocaleDateString('ur-PK')}</p>
                    <p style="margin:5px 0 0; font-size:12px;">عرصہ: ${res.dateStart} تا ${res.dateEnd}</p>
                </td>
            </tr>
        </table>
    </div>
    <table>
        <thead>
            <tr>
                <th style="${thStyle}">الرقم</th>
                <th style="${thStyle}">اسم الطالب</th>
                <th style="${thStyle}">اسم الاب</th>
                <th style="${thStyle}">رجسٹریشن نمبر</th>
                <th style="${thStyle}">تاریخِ پیدائش</th>
                <th style="${thStyle}">رول نمبر</th>
                <th style="${thStyle}">مستقل پتہ</th>
            </tr>
        </thead>
        <tbody>${rows}</tbody>
    </table>
    <div class="footer">
        ناظم تعلیمات ${res.madrasaName}
    </div>
</body>
</html>`);
        printWindow.document.close();
    }

});
