$(document).ready(function () {

    let lastReportData = null;

    // === Population on Darja change ===
    $('#rpt_darja').on('change', function () {
        const darjaSno = $(this).val();
        if (darjaSno) {
            fetchYears(darjaSno);
        } else {
            $('#rpt_year').html('<option value="">پہلے درجہ منتخب کریں</option>');
            $('#rpt_student').html('<option value="">پہلے سال منتخب کریں</option>');
        }
    });

    // === Population on Year change ===
    $('#rpt_year').on('change', function () {
        const darjaSno = $('#rpt_darja').val();
        const year = $(this).val();
        if (darjaSno && year) {
            fetchStudents(darjaSno, year);
        } else {
            $('#rpt_student').html('<option value="">پہلے سال منتخب کریں</option>');
        }
    });

    // === Fetch Years ===
    function fetchYears(darjaSno) {
        $('#rpt_year').html('<option value="">لوڈنگ...</option>');
        $.ajax({
            url: 'APIs/get_years_by_darja.php',
            method: 'POST',
            contentType: 'application/json',
            data: JSON.stringify({ darja_sno: darjaSno }),
            dataType: 'json',
            success: function (res) {
                if (res.success && res.years.length > 0) {
                    let options = '<option value="">سال منتخب کریں</option>';
                    res.years.forEach(y => {
                        options += `<option value="${y.year}">${y.year}</option>`;
                    });
                    $('#rpt_year').html(options);
                } else {
                    $('#rpt_year').html('<option value="">کوئی سال نہیں ملا</option>');
                }
            }
        });
    }

    // === Fetch Students by Year ===
    function fetchStudents(darjaSno, year) {
        $('#rpt_student').html('<option value="">لوڈنگ ہو رہی ہے...</option>');
        $.ajax({
            url: 'APIs/get_students_by_darja_year.php',
            method: 'POST',
            contentType: 'application/json',
            data: JSON.stringify({
                darja_sno: darjaSno,
                year: year
            }),
            dataType: 'json',
            success: function (res) {
                if (res.success && res.students.length > 0) {
                    let options = '<option value="">طالب علم منتخب کریں</option>';
                    res.students.forEach(s => {
                        options += `<option value="${s.sno}" data-start="${s.promotionDate}" data-end="${s.dateEnd}">${s.stdName}</option>`;
                    });
                    $('#rpt_student').html(options);
                } else {
                    $('#rpt_student').html('<option value="">کوئی طالبعلم نہیں ملا</option>');
                }
            }
        });
    }

    // === Show Report Action ===
    $('#btnShowReport').on('click', function () {
        const darjaSno = $('#rpt_darja').val();
        const studentOption = $('#rpt_student option:selected');
        const regSno = $('#rpt_student').val();

        const dateStart = studentOption.data('start');
        const dateEnd = studentOption.data('end');

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

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

    // === Fetch Report Data ===
    function fetchReport(darjaSno, dateStart, dateEnd, regSno) {
        $('#rpt-results').html(
            '<div class="col-12 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/result_sheet_single_std_all.php',
            method: 'POST',
            contentType: 'application/json',
            data: JSON.stringify({
                darja_sno: darjaSno,
                date_start: dateStart,
                date_end: dateEnd,
                reg_sno: regSno
            }),
            dataType: 'json',
            success: function (res) {
                if (res.success) {
                    lastReportData = res;
                    renderReport(res);
                } else {
                    $('#rpt-results').html(
                        '<div class="col-12 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="col-12 alert alert-danger urdu-regular text-end fs-5 mt-4"><i class="bi bi-x-circle ms-2"></i>سرور سے رابطہ کرنے میں ناکامی</div>'
                );
            }
        });
    }

    // === Render Report (Screen) ===
    function renderReport(res) {
        const terms = [
            { id: 1, name: 'سہ ماہی', status: 'غیر حاضری', statusKey: 'غ' },
            { id: 2, name: 'ششماہی', status: 'رخصت', statusKey: 'ر' },
            { id: 3, name: 'سالانہ', status: 'بیمار', statusKey: 'ب' }
        ];

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

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

        let rowsHtml = '';
        const s = res.student;
        const totalMax = res.totalDarjaMarks;

        terms.forEach((term, index) => {
            const result = res.term_results[term.id];
            const marks = result ? result.marks : {};
            const totalObt = result ? result.total_obt : '-';
            const avg = result ? result.avg : '-';
            const grade = result ? result.grade : '-';
            const gradeClass = grade === 'راسب' ? 'text-danger fw-bold' : (grade === 'ممتاز' ? 'text-success fw-bold' : 'fw-bold');

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

            rowsHtml += `
                <tr class="urdu-regular text-center">
                    ${index === 0 ? `<td rowspan="3" class="align-middle fw-bold">1</td>` : ''}
                    ${index === 0 ? `<td rowspan="3" class="align-middle text-start ps-3 fw-bold">${s.stdName} ولد ${s.fatherName}</td>` : ''}
                    <td class="bg-light align-middle">${term.name}</td>
                    ${res.subjects.map(sub => `<td>${marks[sub.sno] || '-'}</td>`).join('')}
                    <td class="fw-bold align-middle">${totalMax}</td>
                    <td class="fw-bold align-middle text-primary">${totalObt}</td>
                    <td class="align-middle">${avg}</td>
                    <td class="align-middle"><span class="${gradeClass}">${grade}</span></td>
                    <td class="bg-light align-middle">${term.status}</td>
                    ${attRowCells}
                    ${index === 0 ? `
                        <td rowspan="3" class="align-middle px-3">
                            <span class="badge ${res.is_sahib_tarteeb ? 'bg-success' : 'bg-secondary'} rounded-pill p-2" style="font-size:14px;">
                                ${res.is_sahib_tarteeb ? 'صاحب ترتیب' : '-'}
                            </span>
                        </td>
                        <td rowspan="3" class="align-middle p-2" style="width:85px;">
                            ${s.stdPhoto ? `<img src="uploaded/${s.stdPhoto}" class="rounded shadow-sm border" style="width:75px; height:85px; object-fit:cover; margin:0 auto; display:block;">` : '<div class="text-muted small">No Photo</div>'}
                        </td>
                    ` : ''}
                </tr>
            `;
        });

        $('#rpt-results').html(`
            <div class="col-12 mt-4">
                <div class="card border-0 shadow-sm mb-4 animate__animated animate__fadeIn">
                    <div class="card-body p-0 overflow-auto">
                        <div class="p-4 bg-white text-center border-bottom">
                            <h3 class="urdu-bold text-primary mb-1">${res.madrasaName}</h3>
                            ${res.madrasaAddressL && res.madrasaAddressL !== 'مزید پتہ یہاں لکھیں' ? `<p class="urdu-regular text-muted mb-0">${res.madrasaAddressL}</p>` : ''}
                            <div class="mt-3 d-flex justify-content-between align-items-center">
                                <span class="badge bg-primary fs-6 urdu-regular">درجہ: ${res.darjaName}</span>
                                <h4 class="urdu-bold mb-0">کشف النتائج (انفرادی)</h4>
                                <span class="text-muted urdu-regular">نام طالب علم: ${s.stdName} <strong>ولد</strong> ${s.fatherName}</span>
                            </div>
                        </div>
                        <div class="table-responsive">
                            <table class="table table-bordered table-hover mb-0" style="min-width:1200px; direction:rtl;">
                                <thead class="bg-light text-center urdu-regular">
                                    <tr>
                                        <th rowspan="2" class="align-middle">الرقم</th>
                                        <th rowspan="2" class="align-middle" style="min-width:150px;">اسم طالب مع <br> ولدیت</th>
                                        <th rowspan="2" class="align-middle">سالانہ نتائج</th>
                                        <th colspan="${res.subjects.length}">مضامین</th>
                                        <th rowspan="2" class="align-middle">مجموع</th>
                                        <th rowspan="2" class="align-middle">محصلہ</th>
                                        <th rowspan="2" class="align-middle">الاوسط</th>
                                        <th rowspan="2" class="align-middle">التقدیر</th>
                                        <th rowspan="2" class="align-middle">کشف الحضور</th>
                                        <th colspan="${res.att_months.length}">ماہانہ حاضری (${res.year_start_hijri} - ${res.year_end_hijri})</th>
                                        <th rowspan="2" class="align-middle">میزان</th>
                                        <th rowspan="2" class="align-middle">تصویر</th>
                                    </tr>
                                    <tr>
                                        ${subjectsHeaderHtml}
                                        ${monthsHeaderHtml}
                                    </tr>
                                </thead>
                                <tbody>
                                    ${rowsHtml}
                                </tbody>
                            </table>
                        </div>
                        <div class="p-4 bg-light border-top">
                            <div class="row urdu-regular">
                                <div class="col-md-4"><strong>سہ ماہی ملاحظات:</strong> <span class="text-muted">${res.remarks[1] || '---'}</span></div>
                                <div class="col-md-4"><strong>ششماہی ملاحظات:</strong> <span class="text-muted">${res.remarks[2] || '---'}</span></div>
                                <div class="col-md-4"><strong>سالانہ ملاحظات:</strong> <span class="text-muted">${res.remarks[3] || '---'}</span></div>
                            </div>
                        </div>
                    </div>
                    <div class="card-footer bg-white border-0 text-center p-3 d-print-none">
                        <button id="btnPrint" class="btn btn-primary px-5 shadow-sm urdu-regular">
                            <i class="bi bi-printer me-2"></i> رپورٹ پرنٹ کریں
                        </button>
                    </div>
                </div>
            </div>
        `);

        // Attach Print Event
        $('#btnPrint').on('click', function () {
            printReport(res);
        });
    }

    // === Print Report (New Window) ===
    function printReport(res) {
        const terms = [
            { id: 1, name: 'سہ ماہی', status: 'غیر حاضری', statusKey: 'غ' },
            { id: 2, name: 'ششماہی', status: 'رخصت', statusKey: 'ر' },
            { id: 3, name: 'سالانہ', status: 'بیمار', statusKey: 'ب' }
        ];

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

        const s = res.student;
        const totalMax = res.totalDarjaMarks;

        let rowsHtml = '';
        terms.forEach((term, index) => {
            const result = res.term_results[term.id];
            const marks = result ? result.marks : {};
            const totalObt = result ? result.total_obt : '-';
            const avg = result ? result.avg : '-';
            const grade = result ? result.grade : '-';

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

            rowsHtml += `
                <tr class="urdu-regular">
                    ${index === 0 ? `<td rowspan="3" class="text-center" style="font-weight:bold;">1</td>` : ''}
                    ${index === 0 ? `<td rowspan="3" style="font-weight:bold; padding-right:5px;">${s.stdName} <br><strong>ولد</strong> <br>${s.fatherName}</td>` : ''}
                    <td class="text-center" style="background:#f9f9f9;">${term.name}</td>
                    ${res.subjects.map(sub => `<td class="text-center">${marks[sub.sno] || '-'}</td>`).join('')}
                    <td class="text-center" style="font-weight:bold;">${totalMax}</td>
                    <td class="text-center" style="font-weight:bold;">${totalObt}</td>
                    <td class="text-center">${avg}</td>
                    <td class="text-center" style="font-weight:bold;">${grade}</td>
                    <td class="text-center" style="background:#f9f9f9;">${term.status}</td>
                    ${attSumHtml}
                    ${index === 0 ? `<td rowspan="3" class="text-center" style="font-weight:bold; width:80px;">${res.is_sahib_tarteeb ? 'صاحب ترتیب' : '-'}</td>` : ''}
                    ${index === 0 ? `<td rowspan="3" class="text-center" style="width:75px;">
                        ${s.stdPhoto ? `<img src="uploaded/${s.stdPhoto}" style="width:70px; height:85px; object-fit:cover; margin:0 auto; display:block;">` : '-'}
                    </td>` : ''}
                </tr>
            `;
        });

        const printWin = window.open('', '_blank');
        printWin.document.write(`
            <html>
                <head>
                    <title>Print Report - ${s.stdName}</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');
                        }
                        body { 
                            direction: rtl; 
                            font-family: 'Jameel Noori Nastaleeq', 'Urdu Typesetting', Arial, sans-serif; 
                            padding: 10px; 
                            color: #000; 
                            font-size: 14px;
                        }
                        .header { text-align: center; border-bottom: 2px solid #000; padding-bottom: 10px; margin-bottom: 15px; }
                        .header h1 { margin: 0; font-size: 30px; }
                        .header p { margin: 2px 0; font-size: 16px; }
                        .info-bar { display: flex; justify-content: space-between; margin-bottom: 10px; font-weight: bold; font-size: 18px; border-bottom:1px solid #ddd; padding-bottom:5px; }
                        table { width: 100%; border-collapse: collapse; table-layout: fixed; }
                        table, th, td { border: 1px solid #000; }
                        th { background: #eee; font-size: 13px; height: 35px; text-align:center; }
                        td { height: 32px; overflow: hidden; vertical-align:middle; }
                        .text-center { text-align: center; }
                        .footer { margin-top: 30px; display: flex; justify-content: space-around; font-weight: bold; }
                        @media print {
                            body { padding: 0.5cm; }
                            @page { size: landscape; margin: 0; }
                        }
                    </style>
                </head>
                <body>
                    <div class="header">
                        <h1>${res.madrasaName}</h1>
                        ${res.madrasaAddressL && res.madrasaAddressL !== 'مزید پتہ یہاں لکھیں' ? `<p>${res.madrasaAddressL}</p>` : ''}
                        <h2 style="margin-top:5px; font-size:22px;">انفرادی کشف النتائج (نتائج الاختبارات)</h2>
                    </div>
                    <div class="info-bar">
                        <div>درجہ: ${res.darjaName}</div>
                        <div>نام الطالب: ${s.stdName} <strong>ولد</strong> ${s.fatherName}</div>
                    </div>
                    <table>
                        <thead>
                            <tr>
                                <th rowspan="2" style="width:30px;">#</th>
                                <th rowspan="2" style="width:130px;">اسم الطالب <br>مع ولدیت</th>
                                <th rowspan="2" style="width:60px;">نتائج</th>
                                <th colspan="${res.subjects.length}">مضامین</th>
                                <th rowspan="2" style="width:50px;">مجموع</th>
                                <th rowspan="2" style="width:50px;">محصلہ</th>
                                <th rowspan="2" style="width:40px;">الاوسط</th>
                                <th rowspan="2" style="width:50px;">التقدیر</th>
                                <th rowspan="2" style="width:60px;">کشف الحضور</th>
                                <th colspan="${res.att_months.length}">ماہانہ حاضری (${res.year_start_hijri} - ${res.year_end_hijri})</th>
                                <th rowspan="2" style="width:80px;">میزان</th>
                                <th rowspan="2" style="width:75px;">تصویر</th>
                            </tr>
                            <tr>
                                ${res.subjects.map(sub => `<th>${sub.name}</th>`).join('')}
                                ${res.att_months.map(m => `<th>${monthNames[m]}</th>`).join('')}
                            </tr>
                        </thead>
                        <tbody>
                            ${rowsHtml}
                        </tbody>
                    </table>
                    <div style="margin-top:10px; font-size:15px;">
                        <p><strong>ملاحظات:</strong></p>
                        <table style="border:none;">
                            <tr style="border:none;">
                                <td style="border:none; width:33%;">سہ ماہی: ${res.remarks[1] || '---'}</td>
                                <td style="border:none; width:33%;">ششماہی: ${res.remarks[2] || '---'}</td>
                                <td style="border:none; width:33%;">سالانہ: ${res.remarks[3] || '---'}</td>
                            </tr>
                        </table>
                    </div>
                    <div class="footer">
                        <div>دستخط نگرانِ تعلیم</div>
                        <div>دستخط ممتحن</div>
                        <div>دستخط مہتمم</div>
                    </div>
                </body>
            </html>
        `);
        printWin.document.close();
        setTimeout(() => { printWin.print(); }, 800);
    }
});
