$(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();
        const resultTerm = $('#rpt_result_term').val();

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

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

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

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

        $.ajax({
            url: 'APIs/result_sheet_by_exam_type.php',
            method: 'POST',
            contentType: 'application/json',
            data: JSON.stringify({
                darja_sno: darjaSno,
                date_start: dateStart,
                date_end: dateEnd,
                result_term: resultTerm
            }),
            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 subjectsHeader = '';
        res.subjects.forEach(s => {
            subjectsHeader += `<th class="text-center small" style="min-width:65px">${s.name}</th>`;
        });

        let rows = '';
        res.students.forEach((s, i) => {
            let marksHtml = '';
            s.marks.forEach(m => {
                const failClass = (m < 40) ? 'bg-danger bg-opacity-10 text-danger fw-bold' : '';
                marksHtml += `<td class="text-center ${failClass}">${m}</td>`;
            });

            rows += `
                <tr>
                    <td class="text-center">${i + 1}</td>
                    <td class="fw-bold">${s.name}</td>
                    <td class="text-muted small">${s.father}</td>
                    ${marksHtml}
                    <td class="text-center bg-light fw-bold">${res.totalDarjaMarks}</td>
                    <td class="text-center fw-bold text-primary">${s.total_obt}</td>
                    <td class="text-center">${s.avg}%</td>
                    <td class="text-center"><span class="badge ${s.grade === 'راسب' ? 'bg-danger' : 'bg-success'} urdu-regular fs-6">${s.grade}</span></td>
                </tr>`;
        });

        const html = `
            <div class="card border-0 shadow-sm rounded-4 overflow-hidden mt-4 text-end">
                <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-success 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">
                        <h5 class="mb-1 urdu-regular">مکتب نتائج الاختبار (${res.examTypeLabel})</h5>
                        <p class="mb-0 urdu-regular small">المرحلۃ: <strong>${res.darjaName}</strong> | تعلیمی سال: <strong>${res.eduYearRemarks}</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-success">
                                <tr>
                                    <th rowspan="2" class="text-center align-middle">نمبر</th>
                                    <th rowspan="2" class="align-middle">اسم طالب</th>
                                    <th rowspan="2" class="align-middle">اسم الاب</th>
                                    <th colspan="${res.subjects.length}" class="text-center">مضامین</th>
                                    <th rowspan="2" class="text-center align-middle">کل نمبر</th>
                                    <th rowspan="2" class="text-center align-middle text-primary">حاصل کردہ</th>
                                    <th rowspan="2" class="text-center align-middle">اوسط</th>
                                    <th rowspan="2" class="text-center align-middle">تقدیر</th>
                                </tr>
                                <tr>
                                    ${subjectsHeader}
                                </tr>
                            </thead>
                            <tbody class="fs-5">${rows}</tbody>
                        </table>
                    </div>
                </div>
                ${renderPositions(res.positions)}
            </div>`;

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

    function renderPositions(pos) {
        if (!pos.first) return '';
        return `
            <div class="card-footer bg-light py-3 px-4">
                <div class="row g-3 text-center urdu-regular">
                    <div class="col-md-4">
                        <div class="p-2 border rounded shadow-sm bg-white">
                            <span class="text-muted small">الاول (پہلی پوزیشن)</span><br>
                            <strong class="text-success fs-4">${pos.first.name}</strong><br>
                            <small class="text-muted">${pos.first.total_obt} نمبر</small>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="p-2 border rounded shadow-sm bg-white">
                            <span class="text-muted small">الثانی (دوسری پوزیشن)</span><br>
                            <strong class="text-primary fs-4">${pos.second ? pos.second.name : '-'}</strong><br>
                            <small class="text-muted">${pos.second ? pos.second.total_obt + ' نمبر' : ''}</small>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="p-2 border rounded shadow-sm bg-white">
                            <span class="text-muted small">الثالث (تیسری پوزیشن)</span><br>
                            <strong class="text-info fs-4">${pos.third ? pos.third.name : '-'}</strong><br>
                            <small class="text-muted">${pos.third ? pos.third.total_obt + ' نمبر' : ''}</small>
                        </div>
                    </div>
                </div>
            </div>`;
    }

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

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

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

        let subjectsTh = '';
        subjects.forEach(s => subjectsTh += `<th style="${thStyle}">${s.name}</th>`);

        let rows = '';
        students.forEach((s, i) => {
            let marksTd = '';
            s.marks.forEach(m => {
                const bg = (m < 40) ? '#eeeeee' : '';
                marksTd += `<td style="${tdCtrStyle} background:${bg}">${m}</td>`;
            });

            rows += `
                <tr>
                    <td style="${tdCtrStyle}">${i + 1}</td>
                    <td style="${tdStyle} font-weight:bold;">${s.name}</td>
                    <td style="${tdStyle}">${s.father}</td>
                    ${marksTd}
                    <td style="${tdCtrStyle} background:#fafafa;">${res.totalDarjaMarks}</td>
                    <td style="${tdCtrStyle} font-weight:bold; color:#1a5fb4;">${s.total_obt}</td>
                    <td style="${tdCtrStyle}">${s.avg}%</td>
                    <td style="${tdCtrStyle} font-weight:bold;">${s.grade}</td>
                </tr>`;
        });

        const posHtml = res.positions.first ? `
            <div style="margin-top:20px; border:1px solid #999; padding:15px; background:#fafafa;">
                <table style="width:100%; border-collapse:collapse; text-align:center;">
                    <tr>
                        <th style="padding:5px; border-bottom:1px solid #999; color:#444;">الاول (پہلی پوزیشن)</th>
                        <th style="padding:5px; border-bottom:1px solid #999; color:#444;">الثانی (دوسری پوزیشن)</th>
                        <th style="padding:5px; border-bottom:1px solid #999; color:#444;">الثالث (تیسری پوزیشن)</th>
                    </tr>
                    <tr>
                        <td style="padding:15px; font-size:16px;"><strong>${res.positions.first.name}</strong> <br> <span style="font-size:12px;">مجموعی نمبر: ${res.positions.first.total_obt}</span></td>
                        <td style="padding:15px; font-size:16px;"><strong>${res.positions.second ? res.positions.second.name : '-'}</strong> <br> <span style="font-size:12px;">${res.positions.second ? 'مجموعی نمبر: ' + res.positions.second.total_obt : ''}</span></td>
                        <td style="padding:15px; font-size:16px;"><strong>${res.positions.third ? res.positions.third.name : '-'}</strong> <br> <span style="font-size:12px;">${res.positions.third ? 'مجموعی نمبر: ' + res.positions.third.total_obt : ''}</span></td>
                    </tr>
                </table>
            </div>` : '';

        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; background:#fff; }
        .header { border-bottom: 2px solid #333; padding-bottom: 12px; margin-bottom: 15px; }
        table { width: 100%; border-collapse: collapse; }
        .footer { margin-top: 20px; font-size: 11px; color: #666; text-align: right; }
        h1, h2, h3 { margin: 0; }
    </style>
</head>
<body onload="window.print(); window.close();">
    <div class="header">
        <table style="border:0">
            <tr>
                <td style="text-align:right">
                    <h1 style="font-size:26px; color:#1a5fb4;">${res.madrasaName}</h1>
                    <p style="margin:5px 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="font-size:22px;">رزلٹ شیٹ (${res.examTypeLabel})</h2>
                    <p style="margin:8px 0 0; font-size:18px;">المرحلۃ: <strong>${res.darjaName}</strong></p>
                </td>
                <td style="text-align:left">
                    <p style="font-size:14px;">تعلیمی سال: <strong>${res.eduYearRemarks}</strong></p>
                    <p style="margin:5px 0 0; font-size:12px; color:#555;">تاریخ پرنٹ: ${new Date().toLocaleDateString('ur-PK')}</p>
                </td>
            </tr>
        </table>
    </div>
    <table>
        <thead>
            <tr>
                <th rowspan="2" style="${thStyle}">الرقم</th>
                <th rowspan="2" style="${thStyle}">اسم طالب</th>
                <th rowspan="2" style="${thStyle}">اسم الاب</th>
                <th colspan="${res.subjects.length}" style="${thStyle}">مضامین</th>
                <th rowspan="2" style="${thStyle}">کل نمبر</th>
                <th rowspan="2" style="${thStyle}">حاصل کردہ</th>
                <th rowspan="2" style="${thStyle}">الاوسط</th>
                <th rowspan="2" style="${thStyle}">التقدیر</th>
            </tr>
            <tr>
                ${subjectsTh}
            </tr>
        </thead>
        <tbody>${rows}</tbody>
    </table>
    ${posHtml}
    <div class="footer">
        * حاصل کردہ اوسط اگر 40 فیصد سے کم ہو تو طالب "راسب" قرار دیا جاتا ہے۔
    </div>
</body>
</html>`);
        printWindow.document.close();
    }

});
