$(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/rpt_resultSheet.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) {
        const monthNames = {
            '10': 'شوّال', '11': 'ذی القعدہ', '12': 'ذی الحجہ',
            '01': 'المحرم', '02': 'صفر', '03': 'ربیع الاول',
            '04': 'ربیع الثانی', '05': 'جمادی الاول', '06': 'جمادی الثانیہ', '07': 'رجب',
            '08': 'شعبان', '09': 'رمضان'
        };

        const terms = [
            { id: 1, name: 'سہ ماہی', status: 'غیر حاضری', statusKey: 'غ' },
            { id: 2, name: 'ششماہی', status: 'رخصت', statusKey: 'ر' },
            { id: 3, name: 'سالانہ', status: 'بیمار', statusKey: 'ب' }
        ];

        let subjectsHeader = res.subjects.map(s => `<th class="text-center small py-2" style="min-width:45px;">${s.name.replace(/ /g, '<br>')}</th>`).join('');
        let monthsHeader = res.att_months.map(m => `<th class="text-center small py-2">${monthNames[m]}</th>`).join('');

        let rows = '';
        res.students.forEach((s, i) => {
            terms.forEach((term, index) => {
                const termData = s.terms[term.id];
                const marks = termData ? termData.marks : [];
                const totalObt = termData ? termData.total_obt : '-';
                const avg = termData ? termData.avg + '%' : '-';
                const grade = termData ? termData.grade : '-';
                const gradeClass = (grade === 'راسب') ? 'text-danger fw-bold' : (grade === 'ممتاز' ? 'text-success fw-bold' : 'fw-bold');

                let marksCols = '';
                if (termData) {
                    marks.forEach(m => {
                        const failClass = (m < 40) ? 'bg-danger bg-opacity-10 text-danger fw-bold' : '';
                        marksCols += `<td class="text-center ${failClass}">${m}</td>`;
                    });
                } else {
                    marksCols = `<td colspan="${res.subjects.length}" class="text-center text-muted small">---</td>`;
                }

                let attRowCells = '';
                res.att_months.forEach(m => {
                    const count = (s.monthly_attendance[m] && s.monthly_attendance[m][term.statusKey] !== undefined)
                        ? s.monthly_attendance[m][term.statusKey] : '-';
                    attRowCells += `<td class="text-center">${count}</td>`;
                });

                rows += `
                    <tr class="urdu-regular text-center ${index === 2 ? 'border-bottom-dark' : ''}">
                        ${index === 0 ? `<td rowspan="3" class="align-middle fw-bold border-start">${i + 1}</td>` : ''}
                        ${index === 0 ? `<td rowspan="3" class="align-middle text-end ps-2 fw-bold border-start" style="min-width:160px; font-size:12px;">${s.name} <br> <strong>ولد</strong> ${s.father}</td>` : ''}
                        <td class="bg-light align-middle border-start" style="font-size:18px;">${term.name}</td>
                        ${marksCols}
                        <td class="bg-light align-middle fw-bold">${termData ? res.totalDarjaMarks : '---'}</td>
                        <td class="align-middle fw-bold text-primary">${totalObt}</td>
                        <td class="align-middle">${termData ? Number(termData.avg).toFixed(2) + '%' : '-'}</td>
                        <td class="align-middle"><span class="${gradeClass}">${grade}</span></td>
                        <td class="bg-light align-middle border-start" style="font-size:18px;">${term.status}</td>
                        ${attRowCells}
                        ${index === 0 ? `
                            <td rowspan="3" class="align-middle px-3 border-end">
                                <span class="badge ${s.is_sahib_tarteeb ? 'bg-success' : 'bg-secondary'} rounded-pill p-1" style="font-size:11px;">
                                    ${s.is_sahib_tarteeb ? 'صاحب ترتیب' : (s.total_absence > 0 ? s.total_absence : '-')}
                                </span>
                            </td>
                        ` : ''}
                    </tr>
                `;
            });
        });

        const html = `
            <style>
                #rpt-results table.rpt-table { font-size: 12px !important; }
                #rpt-results table.rpt-table th, #rpt-results table.rpt-table td { padding: 4px 2px !important; }
                .border-bottom-dark { border-bottom: 2px solid #555 !important; }
            </style>
            <div class="card border-0 shadow-sm rounded-4 overflow-hidden mt-4 text-end">
                <div class="card-header bg-white border-bottom py-2 px-4 d-flex justify-content-between align-items-center">
                    <div>
                        <h5 class="fw-bold text-primary mb-0 urdu-regular fs-5">${res.madrasaName}</h5>
                        ${res.madrasaAddressL && res.madrasaAddressL !== 'مزید پتہ یہاں لکھیں' ? `<p class="urdu-regular text-muted mb-0 x-small" style="font-size:11px;">${res.madrasaAddressL}</p>` : ''}
                    </div>
                    <div class="text-start">
                        <h4 class="fw-bold mb-0 urdu-regular fs-5">مکتب نتائج الاختبارات</h4>
                        <p class="mb-0 urdu-regular fs-6">تعلیمی سال: <strong>${res.date_start} تا ${res.date_end}</strong></p>
                        <p class="mb-0 urdu-regular" style="font-size:13px;">درجہ: <strong>${res.darjaName}</strong></p>
                    </div>
                </div>
                <div class="card-body p-0">
                    <div class="table-responsive">
                        <table class="table table-bordered table-sm align-middle mb-0 text-end rpt-table fs-5" style="min-width: 1100px;">
                            <thead class="table-primary text-center fs-6">
                                <tr>
                                    <th rowspan="2" class="align-middle">الرقم</th>
                                    <th rowspan="2" class="align-middle">اسم طالب مع <br> ولدیت</th>
                                    <th rowspan="2" class="align-middle">سالانہ نتائج</th>
                                    <th colspan="${res.subjects.length}" class="align-middle">مضامین</th>
                                    <th rowspan="2" class="align-middle" style="width:50px;">مجموع</th>
                                    <th rowspan="2" class="align-middle" style="width:50px;">محصلہ</th>
                                    <th rowspan="2" class="align-middle" style="width:60px;">الاوسط</th>
                                    <th rowspan="2" class="align-middle" style="width:60px;">التقدیر</th>
                                    <th rowspan="2" class="align-middle" style="width:80px;">کشف الحضور</th>
                                    <th colspan="${res.att_months.length}" class="align-middle">ماہانہ حاضری (${res.year_start_hijri} - ${res.year_end_hijri})</th>
                                    <th rowspan="2" class="align-middle" style="width:70px;">میزان</th>
                                </tr>
                                <tr>
                                    ${subjectsHeader}
                                    ${monthsHeader}
                                </tr>
                            </thead>
                            <tbody>${rows}</tbody>
                        </table>
                    </div>
                </div>
                ${renderPositions(res.positions, res.remarks)}
            </div>`;

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

    function renderPositions(pos, remarks) {
        let html = '<div class="card-footer bg-light py-4 px-4">';
        html += '<div class="row g-4 text-center urdu-regular">';

        [1, 2, 3].forEach(term => {
            const p = pos[term];
            const termLabel = (term === 1 ? 'سہ ماہی' : (term === 2 ? 'ششماہی' : 'سالانہ'));
            const termClass = (term === 1 ? 'primary' : (term === 2 ? 'success' : 'info'));

            if (p) {
                html += `
                <div class="col-md-4">
                    <div class="p-3 border rounded-4 shadow-sm bg-white h-100">
                        <div class="badge bg-${termClass} mb-2 fs-6 px-3">پوزیشن برائے ${termLabel}</div>
                        <div class="text-muted small mb-2">تاریخ اجراء: ${remarks[term] || '---'}</div>
                        <div class="row g-2">
                            <div class="col-12 border-bottom pb-2">
                                <span class="text-warning small fw-bold"><i class="bi bi-trophy-fill"></i> اول (پہلی)</span><br>
                                <strong>${p.first.name}</strong> <small class="text-muted">(${p.first.total_obt})</small>
                            </div>
                            <div class="col-6 border-start border-end pt-2">
                                <span class="text-secondary small">الثانی (دوسری)</span><br>
                                <strong>${p.second ? p.second.name : '-'}</strong> <br><small class="text-muted">${p.second ? '(' + p.second.total_obt + ')' : ''}</small>
                            </div>
                            <div class="col-6 pt-2">
                                <span class="text-secondary small">الثالث (تیسری)</span><br>
                                <strong>${p.third ? p.third.name : '-'}</strong> <br><small class="text-muted">${p.third ? '(' + p.third.total_obt + ')' : ''}</small>
                            </div>
                        </div>
                    </div>
                </div>`;
            }
        });

        html += '</div></div>';
        return html;
    }

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

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

        const monthNames = {
            '10': 'شوّال', '11': 'ذی القعدہ', '12': 'ذی الحجہ',
            '01': 'المحرم', '02': 'صفر', '03': 'ربیع الاول',
            '04': 'ربیع الثانی', '05': 'جمادی الاول', '06': 'جمادی الثانیہ', '07': 'رجب',
            '08': 'شعبان', '09': 'رمضان'
        };

        const terms = [
            { id: 1, name: 'سہ ماہی', status: 'غیر حاضری', statusKey: 'غ' },
            { id: 2, name: 'ششماہی', status: 'رخصت', statusKey: 'ر' },
            { id: 3, name: 'سالانہ', status: 'بیمار', statusKey: 'ب' }
        ];

        let subjectsTh = subjects.map(s => `<th style="border:1px solid #444; padding:5px; text-align:center; background:#eee; font-size:10px;">${s.name}</th>`).join('');
        let monthsTh = res.att_months.map(m => `<th style="border:1px solid #444; padding:5px; text-align:center; background:#eee; font-size:10px;">${monthNames[m]}</th>`).join('');

        let rows = '';
        students.forEach((s, i) => {
            terms.forEach((term, index) => {
                const termData = s.terms[term.id];
                const marks = termData ? termData.marks : [];
                const totalObt = termData ? termData.total_obt : '-';
                const avg = termData ? termData.avg + '%' : '-';
                const grade = termData ? termData.grade : '-';

                let marksCols = '';
                if (termData) {
                    marks.forEach(m => {
                        const bg = (m < 40) ? '#f8d7da' : '#fff';
                        marksCols += `<td style="border:1px solid #777; padding:4px; text-align:center; font-size:11px; background:${bg}">${m}</td>`;
                    });
                } else {
                    marksCols = `<td colspan="${subjects.length}" style="border:1px solid #777; padding:4px; text-align:center; font-size:11px; color:#999;">---</td>`;
                }

                let attRowCells = '';
                res.att_months.forEach(m => {
                    const count = (s.monthly_attendance[m] && s.monthly_attendance[m][term.statusKey] !== undefined)
                        ? s.monthly_attendance[m][term.statusKey] : '-';
                    attRowCells += `<td style="border:1px solid #777; padding:4px; text-align:center; font-size:11px;">${count}</td>`;
                });

                rows += `
                    <tr style="${index === 2 ? 'border-bottom: 2px solid #000;' : ''} font-family: 'Jameel Noori Nastaleeq';">
                        ${index === 0 ? `<td rowspan="3" style="border:1px solid #777; padding:4px; text-align:center; font-size:11px; font-weight:bold; vertical-align:middle;">${i + 1}</td>` : ''}
                        ${index === 0 ? `<td rowspan="3" style="border:1px solid #777; padding:8px; text-align:right; font-size:14px; font-weight:bold; vertical-align:middle; width:150px;">${s.name} <br> <strong>ولد</strong> ${s.father}</td>` : ''}
                        <td style="border:1px solid #777; padding:4px; text-align:center; font-size:11px; background:#f9f9f9;">${term.name}</td>
                        ${marksCols}
                        <td style="border:1px solid #777; padding:4px; text-align:center; font-size:11px; background:#f9f9f9; font-weight:bold;">${termData ? res.totalDarjaMarks : '---'}</td>
                        <td style="border:1px solid #777; padding:4px; text-align:center; font-size:12px; font-weight:bold; color:#0d6efd;">${totalObt}</td>
                        <td style="border:1px solid #777; padding:4px; text-align:center; font-size:11px;">${avg}</td>
                        <td style="border:1px solid #777; padding:4px; text-align:center; font-size:11px; font-weight:bold;">${grade}</td>
                        <td style="border:1px solid #777; padding:4px; text-align:center; font-size:11px; background:#f9f9f9;">${term.status}</td>
                        ${attRowCells}
                        ${index === 0 ? `<td rowspan="3" style="border:1px solid #777; padding:4px; text-align:center; font-size:11px; vertical-align:middle; width:70px;">${s.is_sahib_tarteeb ? 'صاحب ترتیب' : (s.total_absence > 0 ? s.total_absence : '-')}</td>` : ''}
                    </tr>`;
            });
        });

        let posHtml = '<div style="margin-top:20px;"><table style="width:100%; border-collapse:collapse; text-align:center;" class="fs-5"><tr>';
        [1, 2, 3].forEach(term => {
            const p = res.positions[term];
            const termLabel = (term === 1 ? 'سہ ماہی' : (term === 2 ? 'ششماہی' : 'سالانہ'));
            if (p) {
                posHtml += `
                <td style="width:33%; vertical-align:top; border:1px solid #444; padding:10px; background:#fafafa; font-family: 'Jameel Noori Nastaleeq';">
                    <div style="font-weight:bold; border-bottom:1px solid #999; margin-bottom:10px; font-size:14px;">پوزیشن برائے ${termLabel}</div>
                    <div style="font-size:10px; margin-bottom:8px;">تاریخ اجراء: ${res.remarks[term]}</div>
                    <table style="width:100%; font-size:11px;">
                        <tr><td style="padding:4px;"><strong>اول:</strong> ${p.first.name} (${p.first.total_obt})</td></tr>
                        <tr><td style="padding:4px;"><strong>دوئم:</strong> ${p.second ? p.second.name : '-'} ${p.second ? '(' + p.second.total_obt + ')' : ''}</td></tr>
                        <tr><td style="padding:4px;"><strong>سوئم:</strong> ${p.third ? p.third.name : '-'} ${p.third ? '(' + p.third.total_obt + ')' : ''}</td></tr>
                    </table>
                </td>`;
            }
        });
        posHtml += '</tr></table></div>';

        const printWindow = window.open('', '_blank', 'width=1200,height=900');
        printWindow.document.open();
        printWindow.document.write(`
<!DOCTYPE html>
<html dir="rtl" lang="ur">
<head>
    <meta charset="UTF-8">
    <title>سالانہ رزلٹ شیٹ - ${res.darjaName}</title>
    <style>
        @font-face {
            font-family: 'Jameel Noori Nastaleeq';
            src: url('fonts/jameel_noori_nastaleeq_regular.woff2') format('woff2'),
                 url('fonts/jameel_noori_nastaleeq_regular.ttf') format('truetype');
        }
        @page { margin: 8mm; 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 #000; padding-bottom: 10px; margin-bottom: 15px; text-align:center; }
        table { width: 100%; border-collapse: collapse; background:#fff; margin-bottom:20px; }
        .footer { margin-top: 15px; font-size: 11px; color: #444; text-align:right; font-family: 'Jameel Noori Nastaleeq'; }
    </style>
</head>
<body onload="window.print();">
    <div class="header">
        <h1 style="margin:0; font-size:28px;">${res.madrasaName}</h1>
        ${res.madrasaAddressL && res.madrasaAddressL !== 'مزید پتہ یہاں لکھیں' ? `<p style="margin:4px 0 0; font-size:14px;">${res.madrasaAddressL}</p>` : ''}
        <h2 style="margin:10px 0 0; font-size:20px;">مکتب نتائج الاختبارات (سالانہ رپورٹ)</h2>
        <div style="display:flex; justify-content:space-between; margin-top:10px; font-size:15px; font-weight:bold; padding:0 20px; font-family: 'Jameel Noori Nastaleeq';">
            <div>المرحلۃ: ${res.darjaName}</div>
            <div>تعلیمی سال: ${res.year_start_hijri} - ${res.year_end_hijri} (${new Date(res.date_start).toLocaleDateString('ur-PK')} - ${new Date(res.date_end).toLocaleDateString('ur-PK')})</div>
            <div>تاریخ پرنٹ: ${new Date().toLocaleDateString('ur-PK')}</div>
        </div>
    </div>
    <table>
        <thead>
            <tr>
                <th rowspan="2" style="border:1px solid #444; padding:5px; text-align:center; background:#eee; font-size:11px;">الرقم</th>
                <th rowspan="2" style="border:1px solid #444; padding:5px; text-align:center; background:#eee; font-size:11px; width:150px;">اسم طالب مع <br> ولدیت</th>
                <th rowspan="2" style="border:1px solid #444; padding:5px; text-align:center; background:#eee; font-size:11px;">نتائج</th>
                <th colspan="${res.subjects.length}" style="border:1px solid #444; padding:5px; text-align:center; background:#eee; font-size:11px;">مضامین</th>
                <th rowspan="2" style="border:1px solid #444; padding:5px; text-align:center; background:#eee; font-size:11px;">مجموع</th>
                <th rowspan="2" style="border:1px solid #444; padding:5px; text-align:center; background:#eee; font-size:11px;">محصلہ</th>
                <th rowspan="2" style="border:1px solid #444; padding:5px; text-align:center; background:#eee; font-size:11px;">الاوسط</th>
                <th rowspan="2" style="border:1px solid #444; padding:5px; text-align:center; background:#eee; font-size:11px;">التقدیر</th>
                <th rowspan="2" style="border:1px solid #444; padding:5px; text-align:center; background:#eee; font-size:11px;">کشف الحضور</th>
                <th colspan="${res.att_months.length}" style="border:1px solid #444; padding:5px; text-align:center; background:#eee; font-size:11px;">ماہانہ حاضری (${res.year_start_hijri} - ${res.year_end_hijri})</th>
                <th rowspan="2" style="border:1px solid #444; padding:5px; text-align:center; background:#eee; font-size:11px; width:70px;">میزان</th>
            </tr>
            <tr>
                ${subjectsTh}
                ${monthsTh}
            </tr>
        </thead>
        <tbody>${rows}</tbody>
    </table>
    ${posHtml}
    <div class="footer">
        <p>* حاصل کردہ اوسط اگر 40 فیصد سے کم ہو تو طالب "راسب" قرار دیا جاتا ہے۔ "صاحب الترتیب" وہ طالب ہے جو تمام دنوں میں حاضر رہا۔</p>
    </div>
</body>
</html>`);
        printWindow.document.close();
    }

});
