$(document).ready(function () {
    let lastReportData = null;


    // Handle Darja change
    $('#darja').on('change', function () {
        updateStudentList();
    });

    // Handle Date changes (if manually typed)
    $('#promotionDate, #dateEnd').on('change', function () {
        updateStudentList();
    });

    // Fetch Student List
    function updateStudentList() {
        const darja = $('#darja').val();
        const promotionDate = $('#promotionDate').val();
        const dateEnd = $('#dateEnd').val();

        if (!darja || !promotionDate || !dateEnd) {
            $('#regSno').html('<option value="">پہلے درجہ منتخب کریں</option>');
            return;
        }

        $.ajax({
            url: 'APIs/getDMCstudents.php',
            method: 'POST',
            contentType: 'application/json',
            data: JSON.stringify({ darja: darja, promotionDate: promotionDate, dateEnd: dateEnd }),
            success: function (res) {
                if (res.success) {
                    let options = '<option value="">طالب علم منتخب کریں</option>';
                    res.data.forEach(function (std) {
                        options += `<option value="${std.sno}">${std.name}</option>`;
                    });
                    $('#regSno').html(options);
                } else {
                    $('#regSno').html('<option value="">کوئی طالب علم نہیں ملا</option>');
                }
            },
            error: function () {
                console.error("Failed to fetch students");
            }
        });
    }

    // Handle Form Submission (Search)
    $('#btnSearch').on('click', function (e) {
        e.preventDefault();
        const regSno = $('#regSno').val();
        const darja = $('#darja').val();
        const promotionDate = $('#promotionDate').val();
        const dateEnd = $('#dateEnd').val();

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

        fetchDMC(regSno, darja, promotionDate, dateEnd);
    });

    function fetchDMC(regSno, darja, pDate, dEnd) {
        $('#dmc-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>'
        );
        lastReportData = null;

        $.ajax({
            url: 'APIs/getDMCreport.php',
            method: 'POST',
            contentType: 'application/json',
            data: JSON.stringify({ regSno: regSno, darja: darja, promotionDate: pDate, dateEnd: dEnd }),
            success: function (res) {
                if (res.success || res.data) {
                    lastReportData = res.data;
                    renderDMC(res.data, res.success);
                } else {
                    $('#dmc-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 () {
                $('#dmc-results').html(
                    '<div class="alert alert-danger urdu-regular text-end fs-5"><i class="bi bi-x-circle ms-2"></i>سرور سے رابطہ کرنے میں ناکامی</div>'
                );
            }
        });
    }

    function renderDMC(data, isSuccess) {
        const std = data.student;
        const subjects = data.subjects;
        const totals = data.totals;

        let rows = '';
        subjects.forEach(function (sub) {
            rows += `
                <tr>
                    <td>${sub.name}</td>
                    <td class="text-center">${sub.obtained !== null ? sub.obtained : '-'}</td>
                    <td class="text-center">${sub.total}</td>
                </tr>`;
        });

        const statusHtml = isSuccess
            ? `<div class="badge bg-success fs-6 urdu-regular p-2 px-3">تقدیر: ${data.grade || '-'}</div>`
            : `<div class="alert alert-info urdu-regular mt-3">اس طالب علم کا رزلٹ ابھی دستیاب نہیں ہے</div>`;

        const html = `
            <div class="card border-0 shadow-sm rounded-4 overflow-hidden mb-4">
                <div class="card-header bg-white border-bottom py-3 px-4 d-flex justify-content-between align-items-center flex-row-reverse">
                    <div class="text-end">
                        <h5 class="fw-bold text-primary mb-1 urdu-regular fs-4">${std.name}</h5>
                        <p class="text-muted mb-0 urdu-regular small">${std.darjaName} | رول نمبر: ${std.rollNo}</p>
                    </div>
                    <div>
                        <button id="btnPrintDMC" class="btn btn-outline-primary btn-sm rounded-3 px-3 urdu-regular">
                            <i class="bi bi-printer ms-2"></i> پرنٹ ڈی ایم سی
                        </button>
                    </div>
                </div>
                <div class="card-body p-4">
                    <div class="row g-3 mb-4 text-end urdu-regular fs-5">
                        <div class="col-md-6 border-start">
                            <p class="mb-1"><strong>والد کا نام:</strong> ${std.father}</p>
                            <p class="mb-1"><strong>رجسٹریشن نمبر:</strong> ${std.regNo}</p>
                        </div>
                        <div class="col-md-6">
                            <p class="mb-1"><strong>تاریخ پیدائش:</strong> ${std.dob}</p>
                            <p class="mb-1"><strong>ضلع/پتہ:</strong> ${std.address}</p>
                        </div>
                    </div>
                    
                    <div class="table-responsive">
                        <table class="table table-bordered table-hover align-middle mb-0 text-end urdu-regular fs-5">
                            <thead class="table-light">
                                <tr>
                                    <th>المادۃ (مضمون)</th>
                                    <th class="text-center">الدرجات (حاصل کردہ)</th>
                                    <th class="text-center">مجموعہ الدرجات (کل نمبر)</th>
                                </tr>
                            </thead>
                            <tbody>${rows}</tbody>
                            <tfoot class="table-primary fw-bold">
                                <tr>
                                    <td>مجموع الدرجات (حاصل کردہ کل نمبرات)</td>
                                    <td class="text-center">${totals.obtained}</td>
                                    <td class="text-center">${totals.possible}</td>
                                </tr>
                            </tfoot>
                        </table>
                    </div>
                    <div class="mt-4 text-start">
                        ${statusHtml}
                    </div>
                </div>
            </div>`;

        $('#dmc-results').html(html);

        $('#btnPrintDMC').on('click', function () {
            printDMC();
        });
    }

    function printDMC() {
        if (!lastReportData) return;
        const data = lastReportData;
        const std = data.student;
        const subjects = data.subjects;
        const totals = data.totals;

        let rows = '';
        subjects.forEach(function (sub) {
            rows += `
                <tr>
                    <td style="border:1px solid #999; padding:8px; text-align:right;">${sub.name}</td>
                    <td style="border:1px solid #999; padding:8px; text-align:center;">${sub.obtained !== null ? sub.obtained : '-'}</td>
                    <td style="border:1px solid #999; padding:8px; text-align:center;">${sub.total}</td>
                </tr>`;
        });

        const printWindow = window.open('', '_blank', 'width=800,height=900');
        printWindow.document.open();
        printWindow.document.write(`<!DOCTYPE html>
<html dir="rtl" lang="ur">
<head>
    <meta charset="UTF-8">
    <title>DMC - ${std.name}</title>
    <style>
        @page { margin: 0; size: legal portrait; }
        body {
            font-family: 'Jameel Noori Nastaleeq', 'Noto Nastaliq Urdu', Tahoma, sans-serif;
            background: #fff;
            margin: 0;
            padding: 0;
            direction: rtl;
        }
        .dmc-container {
            width: 8.5in;
            height: 14in;
            padding: 40px;
            box-sizing: border-box;
            position: relative;
            background-image: url('images/dmc/bg.png');
            background-size: 100% 100%;
            background-position: center;
            background-repeat: no-repeat;
            margin: 0 auto;
        }
        .header { width:93%; text-align: center; border-bottom: 2px solid #140a5a;margin:0 auto;margin-top:60px; margin-bottom: 20px; }
        .school-name { font-size: 28px; font-weight: bold; color: #1a4fa0; margin-bottom: 5px; }
        .school-info { font-size: 14px; color: #555; margin-bottom: 10px; }
        .report-title { font-size: 22px; font-weight: bold; margin-top: 15px; color: #333; }
        
        .std-meta { display: flex; flex-wrap: wrap;width: 90%;margin: 0 auto;margin-bottom: 20px;}
        .meta-item { width: 50%; margin-bottom: 8px; font-size: 16px; }
        
        table { width: 90%; border-collapse: collapse; margin: 0 auto; }
        th { background: #f0f4f8; padding: 10px; border: 1px solid #999; }
        .grade-box { margin-top: 25px;margin-left:90px; font-size: 20px; font-weight: bold; text-align: left; }
        .footer { margin:0 auto;margin-top: 50px; width:75%;display: flex; justify-content: space-between; font-weight: bold; }
        
        @media print {
            body { -webkit-print-color-adjust: exact; }
            .dmc-container { border: 2px solid #1a4fa0 !important; }
        }
    </style>
</head>
<body>
    <div class="dmc-container">
        <div class="header">
            <div class="school-name">${data.madrasa.name}</div>
            ${data.madrasa.l_address && data.madrasa.l_address !== 'مزید پتہ یہاں لکھیں' ? `<div class="school-info">${data.madrasa.l_address}</div>` : ''}
            <div class="school-info">${data.madrasa.address} | الحاق نمبر: ${data.madrasa.elhaq}</div>
            <div class="report-title">کشف الدرجات (DMC) - سالانہ امتحان ${data.session} ھ</div>
        </div>

        <div class="std-meta">
            <div class="meta-item"><strong>نام:</strong> ${std.name}</div>
            <div class="meta-item"><strong>والد کا نام:</strong> ${std.father}</div>
            <div class="meta-item"><strong>درجہ:</strong> ${std.darjaName}</div>
            <div class="meta-item"><strong>رول نمبر:</strong> ${std.rollNo}</div>
            <div class="meta-item"><strong>رجسٹریشن:</strong> ${std.regNo}</div>
            <div class="meta-item"><strong>تاریخ پیدائش:</strong> ${std.dob}</div>
        </div>

        <table>
            <thead>
                <tr>
                    <th>المادۃ (مضمون)</th>
                    <th>الدرجات (حاصل کردہ)</th>
                    <th>مجموعہ الدرجات (کل)</th>
                </tr>
            </thead>
            <tbody>
                ${rows}
                <tr style="background:#f0f4f8; font-weight:bold;">
                    <td style="border:1px solid #999; padding:8px;">مجموع الدرجات (کل نمبرات)</td>
                    <td style="border:1px solid #999; padding:8px; text-align:center;">${totals.obtained}</td>
                    <td style="border:1px solid #999; padding:8px; text-align:center;">${totals.possible}</td>
                </tr>
            </tbody>
        </table>

        <div class="grade-box">
             تقدیر: ${data.grade || '-'}
        </div>

        <div class="footer">
            <div>دستخط مہتمم/ناظمِ تعلیمات</div>
            <div>المہر (Stamp)</div>
        </div>
    </div>
    <script>
        window.onload = function() { window.print(); setTimeout(function() { window.close(); }, 500); }
    </script>
</body>
</html>`);
        printWindow.document.close();
        // printWindow.print();
    }

    // Initial check (if Darja is pre-selected)
    if ($('#darja').val()) {
        updateStudentList();
    }
});
