$(document).ready(function () {

    // Store last API response for print access
    let lastReportData = null;

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

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

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

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

    // === Fetch Report Data from API ===
    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/rpt_stdList.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"><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"><i class="bi bi-x-circle ms-2"></i>سرور سے رابطہ کرنے میں ناکامی</div>'
                );
            }
        });
    }

    // === Render Report Table (Bootstrap UI for screen) ===
    function renderReport(res) {
        const students = res.data;
        let rows = '';
        students.forEach(function (s, i) {
            rows += `
                <tr>
                    <td class="text-center">${i + 1}</td>
                    <td>${s.stdName}</td>
                    <td>${s.fatherName}</td>
                    <td class="text-center" dir="ltr">${s.registrationNo}</td>
                    <td class="text-center">${s.dob}</td>
                    <td class="text-center">${s.rollNo}</td>
                    <td>${s.address}</td>
                    <td class="text-center">${s.admissionDate}</td>
                    <td class="text-center">${s.cell}</td>
                </tr>`;
        });

        const html = `
            <div id="rpt-print-area" class="card border-0 shadow-sm rounded-4 overflow-hidden">
                <div class="card-header bg-white border-bottom py-3 px-4 text-end">
                    <h5 class="fw-bold text-primary mb-1 urdu-regular fs-4">${res.madrasaName}</h5>
                    <p class="text-muted mb-1 urdu-regular small">${res.madrasaAddress}</p>
                    <p class="text-muted mb-0 urdu-regular small fw-semibold">
                        درجہ: <strong>${res.darjaName}</strong> &nbsp;|&nbsp; کل طلباء: <strong>${students.length}</strong>
                    </p>
                </div>
                <div class="card-body p-0">
                    <div class="table-responsive">
                        <table class="table table-bordered table-hover align-middle mb-0 text-end">
                            <thead class="table-primary">
                                <tr class="urdu-regular fs-5">
                                    <th class="text-center" style="width:40px">نمبر</th>
                                    <th>اسم الطالب</th>
                                    <th>اسم الاب</th>
                                    <th class="text-center">رجسٹریشن نمبر</th>
                                    <th class="text-center">تاریخ پیدائش</th>
                                    <th class="text-center">رول نمبر</th>
                                    <th>پتہ</th>
                                    <th class="text-center">تاریخ داخلہ</th>
                                    <th class="text-center">رابطہ نمبر</th>
                                </tr>
                            </thead>
                            <tbody class="urdu-regular fs-5">${rows}</tbody>
                            <tfoot>
                                <tr class="table-light urdu-regular fw-bold">
                                    <td colspan="9" class="text-end py-2">کل طلباء: ${students.length}</td>
                                </tr>
                            </tfoot>
                        </table>
                    </div>
                </div>
            </div>`;

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

    // === Professional Print Function (Pure Inline CSS — No Bootstrap) ===
    function printReport() {
        if (!lastReportData) return;

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

        // Build pure-CSS table rows
        const tdStyle = 'border:1px solid #aaa; padding:6px 10px; text-align:right; font-size:13px;';
        const tdCtrStyle = 'border:1px solid #aaa; padding:6px 10px; text-align:center; font-size:13px;';

        let rows = '';
        students.forEach(function (s, i) {
            const bg = (i % 2 === 0) ? '#ffffff' : '#f9f9f9';
            rows += `<tr style="background:${bg}">
                <td style="${tdCtrStyle}">${i + 1}</td>
                <td style="${tdStyle}">${s.stdName}</td>
                <td style="${tdStyle}">${s.fatherName}</td>
                <td style="${tdCtrStyle}" dir="ltr">${s.registrationNo}</td>
                <td style="${tdCtrStyle}">${s.dob}</td>
                <td style="${tdCtrStyle}">${s.rollNo}</td>
                <td style="${tdStyle}">${s.address}</td>
                <td style="${tdCtrStyle}">${s.admissionDate}</td>
                <td style="${tdCtrStyle}">${s.cell}</td>
            </tr>`;
        });

        const thStyle = 'border:1px solid #888; padding:7px 10px; text-align:center; background:#c8e6fa; font-size:13px; font-weight:bold;';
        const 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>
            <th style="${thStyle}">تاریخ داخلہ</th>
            <th style="${thStyle}">رابطہ نمبر</th>
        </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>رجسٹرڈ طلباء رپورٹ</title>
    <style>
        @page { margin: 12mm 8mm; size: A4 landscape; }
        * { box-sizing: border-box; margin: 0; padding: 0; }
        body {
            font-family: 'Jameel Noori Nastaleeq', 'Noto Nastaliq Urdu', Tahoma, Arial, sans-serif;
            font-size: 13px;
            background: #fff;
            color: #111;
            direction: rtl;
        }
        .report-header {
            border-bottom: 2px solid #1a6ab0;
            padding: 10px 14px 8px;
            margin-bottom: 10px;
            text-align: right;
        }
        .report-header .madrasa-name {
            font-size: 22px;
            font-weight: bold;
            color: #1a4fa0;
        }
        .report-header .madrasa-address {
            font-size: 13px;
            color: #444;
            margin-top: 2px;
        }
        .report-header .report-meta {
            font-size: 12px;
            color: #333;
            margin-top: 4px;
        }
        table {
            border-collapse: collapse;
            width: 100%;
            margin-top: 6px;
        }
        th, td { border: 1px solid #999; padding: 6px 8px; }
        tfoot td {
            background: #f0f0f0;
            font-weight: bold;
            text-align: right;
            padding: 6px 10px;
            border-top: 2px solid #888;
        }
        @media print {
            body { -webkit-print-color-adjust: exact; print-color-adjust: exact; }
        }
    </style>
</head>
<body>
    <div class="report-header">
        <div class="madrasa-name">${res.madrasaName}</div>
        <div class="madrasa-address">${res.madrasaAddress}</div>
        <div class="report-meta">درجہ: <strong>${res.darjaName}</strong> &nbsp;|&nbsp; کل طلباء: <strong>${students.length}</strong></div>
    </div>
    <table>
        <thead>${thead}</thead>
        <tbody>${rows}</tbody>
        <tfoot>
            <tr><td colspan="9">کل طلباء: ${students.length}</td></tr>
        </tfoot>
    </table>
    <script>
        window.onload = function () {
            window.print();
            // In most browsers, window.print() is blocking, 
            // so we close immediately after or with a tiny delay.
            setTimeout(function() { window.close(); }, 100);
        };
    </script>
</body>
</html>`);
        printWindow.document.close();
    }

});
