$(document).ready(function () {

    let lastReportData = null;

    // ── Form Submit ──────────────────────────────────────────────────────────
    $('#nonLocalStdForm').on('submit', function (e) {
        e.preventDefault();

        const darja = $('#nls_darja').val();
        const year = $('#nls_year').val();
        const type = $('#nls_type').val(); // 0=Non-Local, 1=Local

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

        fetchReport(darja, year, type);
    });

    // ── Print Button ────────────────────────────────────────────────────────
    $(document).on('click', '#btnNLSPrint', function () {
        if (lastReportData) printReport(lastReportData);
    });

    // ── Fetch Data ──────────────────────────────────────────────────────────
    function fetchReport(darja, year, type) {
        const btn = $('#btnShowNLS');
        const originalHtml = btn.html();
        btn.prop('disabled', true).html('<span class="spinner-border spinner-border-sm ms-2"></span> لوڈ ہو رہا ہے...');

        $('#nlsReportContainer').html(
            '<div class="text-center p-5 card border-0 shadow-sm rounded-4 mt-3">' +
            '<div class="spinner-border text-info" role="status"></div>' +
            '<p class="mt-3 urdu-regular fs-5 text-muted">رپورٹ تیار ہو رہی ہے...</p>' +
            '</div>'
        );
        lastReportData = null;

        $.ajax({
            url: 'APIs/nonLocal_std_list.php',
            method: 'POST',
            contentType: 'application/json',
            data: JSON.stringify({ darja_sno: darja, year: year, is_local: parseInt(type) }),
            dataType: 'json',
            success: function (res) {
                if (res.success) {
                    lastReportData = res;
                    renderReport(res);
                } else {
                    $('#nlsReportContainer').html(
                        '<div class="alert alert-warning urdu-regular text-end fs-5 mt-3 shadow-sm rounded-3">' +
                        '<i class="bi bi-exclamation-triangle ms-2"></i>' + res.message + '</div>'
                    );
                }
            },
            error: function () {
                $('#nlsReportContainer').html(
                    '<div class="alert alert-danger urdu-regular text-end fs-5 mt-3 shadow-sm rounded-3">' +
                    '<i class="bi bi-x-circle ms-2"></i>سرور سے رابطہ کرنے میں ناکامی</div>'
                );
            },
            complete: function () {
                btn.prop('disabled', false).html(originalHtml);
            }
        });
    }

    // ── Render On-Screen ────────────────────────────────────────────────────
    function renderReport(res) {
        const typeLabel = res.isLocal == 1 ? 'رہائشی' : 'غیر رہائشی';

        let rows = '';
        res.students.forEach(function (s, i) {
            let presentAddr = s.presentAddress || '-';
            if (s.permanentAddress && s.presentAddress && s.permanentAddress.trim() === s.presentAddress.trim()) {
                presentAddr = 'الیضاء';
            }

            rows += `
            <tr>
                <td class="text-center fw-bold text-muted fs-4">${i + 1}</td>
                <td class="fw-bold text-primary fs-4">${s.stdName}</td>
                <td class="fs-4">${s.fatherName}</td>
                <td class="text-center small fs-4">${s.dob}</td>
                <td class="text-center small fs-4" dir="ltr">${s.nicValue}<br><span class="text-muted fs-4">${s.nicType}</span></td>
                <td class="fs-4">${s.guirdianName || '-'}</td>
                <td class="small text-muted fs-4">${s.permanentAddress || '-'}</td>
                <td class="text-center fs-4">${presentAddr}</td>
                <td class="text-center small fs-4" dir="ltr">${s.cellNo || '-'}</td>
            </tr>`;
        });

        const html = `
        <div class="card border-0 shadow-sm rounded-4 overflow-hidden mt-3 animate__animated animate__fadeIn">
            <div class="card-header bg-white border-bottom py-4 px-4 d-flex justify-content-between align-items-center flex-wrap gap-3">
                <div class="text-end">
                    <h5 class="fw-bold text-info mb-1 urdu-regular fs-3">نام ${res.madrasaName}</h5>
                    <p class="text-muted mb-0 urdu-regular small">نام مہتمم ${res.mohtamim} صاحب</p>
                </div>
                <div class="text-center">
                    <h3 class="fw-bold mb-1 urdu-regular text-dark">${typeLabel} طلباء کا مکمل لسٹ</h3>
                    <p class="mb-0 urdu-regular fs-5 text-muted">درجہ: <span class="text-dark fw-bold">${res.darjaName}</span> &nbsp;|&nbsp; تعلیمی سال: <span class="text-dark fw-bold">${res.year}</span></p>
                </div>
                <div>
                    <button id="btnNLSPrint" class="btn btn-outline-info urdu-regular px-4 py-2 rounded-3">
                        <i class="bi bi-printer ms-1"></i> پرنٹ کریں
                    </button>
                </div>
            </div>
            <div class="card-body p-0">
                <div class="table-responsive">
                    <table class="table table-hover align-middle mb-0 text-end urdu-regular table-striped">
                        <thead class="bg-light-subtle">
                            <tr class="text-center align-middle">
                                <th class="py-3" style="width:80px">نمبر شمار</th>
                                <th class="py-3">نام طالب علم</th>
                                <th class="py-3">ولدیت</th>
                                <th class="py-3">تاریخِ پیدائش</th>
                                <th class="py-3">شناختی کارڈ نمبر / فارم ب</th>
                                <th class="py-3">سر پرست</th>
                                <th class="py-3">مستقل پتہ</th>
                                <th class="py-3">موجودہ رہائش</th>
                                <th class="py-3">رابطہ نمبر</th>
                            </tr>
                        </thead>
                        <tbody class="fs-6 align-top">${rows}</tbody>
                    </table>
                </div>
            </div>
            <div class="card-footer bg-light-subtle border-top-0 py-3 px-4 text-start">
                <span class="urdu-regular fs-5 text-muted">کل تعداد: <strong class="text-dark">${res.students.length}</strong></span>
            </div>
        </div>`;

        $('#nlsReportContainer').html(html);
    }

    // ── Professional Print Window ──────────────────────────────────────────
    function printReport(res) {
        const typeLabel = res.isLocal == 1 ? 'رہائشی' : 'غیر رہائشی';
        const tdS = 'border:1px solid #111;padding:3px 5px;text-align:right;font-size:13px;';
        const tdCS = 'border:1px solid #111;padding:3px 5px;text-align:center;font-size:13px;';
        const thS = 'border:1px solid #111;padding:5px;text-align:center;background:#fff;font-size:14px;font-weight:bold;';

        let rows = '';
        res.students.forEach(function (s, i) {
            // Handle ditto (الیضاء) if addresses match
            let presentAddr = s.presentAddress || '-';
            if (s.permanentAddress && s.presentAddress && s.permanentAddress.trim() === s.presentAddress.trim()) {
                presentAddr = 'الیضاء';
            }

            rows += `
            <tr>
                <td style="${tdCS}">${i + 1}</td>
                <td style="${tdS}font-weight:bold;">${s.stdName}</td>
                <td style="${tdS}">${s.fatherName}</td>
                <td style="${tdCS}">${s.dob}</td>
                <td style="${tdCS}" dir="ltr">${s.nicValue}<br><small>${s.nicType}</small></td>
                <td style="${tdS}">${s.guirdianName || '-'}</td>
                <td style="${tdS}font-size:13px; line-height:1.2;">${s.permanentAddress || '-'}</td>
                <td style="${tdCS}">${presentAddr}</td>
                <td style="${tdCS}" dir="ltr">${s.cellNo || '-'}</td>
            </tr>`;
        });

        const pw = window.open('', '_blank', 'width=1200,height=900');
        pw.document.open();
        pw.document.write(`<!DOCTYPE html>
<html dir="rtl" lang="ur">
<head>
<meta charset="UTF-8">
<title>${typeLabel} — ${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:10px; color:#000; }
    table { width:100%; border-collapse:collapse; margin-top:5px; transition: none; }
    .header-info { width:100%; border:0 !important; margin-bottom:0; }
    .header-info td { border:0 !important; padding:4px 10px; vertical-align:top; border:0 !important; }
    .title-row { border: 1px solid #000; border-bottom: 0; padding: 10px; text-align: center; font-size: 16px; font-weight: bold; background: #fff; }
    .signature-section { width:100%; margin-top:15px; border:0 !important; }
    .signature-section td { border:0 !important; padding:8px 0; font-size:16px; font-weight:normal; }
    .urdu-font { font-family: 'Jameel Noori Nastaleeq', 'Noto Nastaliq Urdu', serif; }
</style>
</head>
<body onload="window.print();window.close();" class="urdu-font">
    <table class="header-info">
        <tr>
            <!-- Right Section -->
            <td style="text-align:right; width:33%;">
                <h1 style="margin:0;font-size:18px;">نام ${res.madrasaName}</h1>
                <p style="margin:5px 0 0;font-size:16px;">نام مہتمم ${res.mohtamim} صاحب</p>
            </td>
            <!-- Center Section -->
            <td style="text-align:center; width:34%;">
                <p style="margin:0;font-size:14px;">مکمل پتہ ${res.madrasaAddr} ${res.madrasaAdr2}</p>
                <p style="margin:5px 0 0;font-size:14px;">فون: <span dir="ltr">${res.phone}</span></p>
                <p style="margin:3px 0 0;font-size:14px;">موبائل: <span dir="ltr">${res.cell}</span></p>
            </td>
            <!-- Left Section -->
            <td style="text-align:left; width:33%;">
                <p style="margin:0;font-size:14px;">الحاق نمبر ${res.elhaq || '-'}</p>
                <p style="margin:5px 0 0;font-size:14px;">رجسٹریشن نمبر ${res.regNumber || '-'}</p>
                <p style="margin:5px 0 0;font-size:14px;">تعلیمی درجہ ${res.darjaName}</p>
            </td>
        </tr>
    </table>

    <div class="title-row">
        ${typeLabel} طلباء کا مکمل لسٹ
    </div>

    <table>
        <thead>
            <tr>
                <th style="${thS}width:45px">نمبر شمار</th>
                <th style="${thS}width:140px">نام طالب علم</th>
                <th style="${thS}width:120px">ولدیت</th>
                <th style="${thS}width:110px">تاریخِ پیدائش</th>
                <th style="${thS}">شناختی کارڈ نمبر / فارم ب</th>
                <th style="${thS}width:100px">سر پرست</th>
                <th style="${thS}width:180px">مستقل پتہ</th>
                <th style="${thS}width:100px">موجودہ رہائش</th>
                <th style="${thS}width:120px">رابطہ نمبر</th>
            </tr>
        </thead>
        <tbody>${rows}</tbody>
    </table>

    <table class="signature-section">
        <tr>
            <td style="text-align:right; width:33%; font-size:14px;">پاک آرمی یونٹ نمبر </td>
            <td style="text-align:center; width:34%; font-size:18px; font-weight:bold;">F:18</td>
            <td style="text-align:left; width:33%; font-size:14px; padding-left: 20px;">دستخط مہتمم</td>
        </tr>
        <tr>
            <td style="text-align:right; font-size:14px;">پولیس سٹیشن</td>
            <td style="text-align:center; font-size:14px;">مکان باغ مینگورہ</td>
            <td style="text-align:left; font-size:14px; padding-left: 20px;">مہر / مدرسہ</td>
        </tr>
        <tr>
            <td></td>
            <td style="text-align:center; font-size:14px; padding-top:15px;">تارِیخ ________________</td>
            <td></td>
        </tr>
    </table>
</body>
</html>`);
        pw.document.close();
    }

});
