$(document).ready(function () {
    const apiBase = 'APIs/fee_api.php';

    // Load common data
    if ($('#feeModule').length) {
        loadFeeTypes();
    }

    function loadFeeTypes() {
        $.getJSON(`${apiBase}?action=get_fee_types`, function (res) {
            if (res.success) {
                let options = '<option value="">منتخب کریں (Select Fee Type)</option>';
                res.data.forEach(type => {
                    options += `<option value="${type.id}">${type.fee_name}</option>`;
                });
                $('#fee_type_id').html(options);
            }
        });
    }

    // === Dependent Student Dropdown (Darja + Year) ===
    function tryLoadStudents() {
        const darja = $('#filter_darja').val();
        const year = $('#filter_year').val();

        if (!darja || !year) {
            $('#student_id')
                .prop('disabled', true)
                .html('<option value="">پہلے درجہ اور سال منتخب کریں</option>');
            $('#studentCount').text('');
            return;
        }

        // Show loading state
        $('#student_id').prop('disabled', true).html('<option value="">طلباء لوڈ ہو رہے ہیں...</option>');
        $('#studentLoadSpinner').removeClass('d-none');
        $('#studentCount').text('');

        $.getJSON(`${apiBase}?action=get_students&darja=${encodeURIComponent(darja)}&start_year=${encodeURIComponent(year)}`, function (res) {
            $('#studentLoadSpinner').addClass('d-none');
            if (res.success && res.data.length > 0) {
                let options = '<option value="">طالب علم منتخب کریں</option>';
                res.data.forEach(std => {
                    options += `<option value="${std.sno}">${std.stdName} بن ${std.fatherName} (${std.registrationNo || 'No Reg'})</option>`;
                });
                $('#student_id').prop('disabled', false).html(options);
                $('#studentCount').html(`<span class="text-success"><i class="bi bi-check-circle me-1"></i>${res.data.length} طالب علم ملے</span>`);
            } else {
                $('#student_id')
                    .prop('disabled', true)
                    .html('<option value="">اس درجہ / سال میں کوئی طالب علم نہیں ملا</option>');
                $('#studentCount').html('<span class="text-warning"><i class="bi bi-exclamation-circle me-1"></i>کوئی نتیجہ نہیں (No students found)</span>');
            }
        }).fail(function () {
            $('#studentLoadSpinner').addClass('d-none');
            $('#student_id').prop('disabled', true).html('<option value="">خرابی (Load Error)</option>');
            $('#studentCount').html('<span class="text-danger"><i class="bi bi-x-circle me-1"></i>ڈیٹا لوڈ نہیں ہو سکا</span>');
        });
    }

    // Trigger on change of either filter field
    $('#filter_darja, #filter_year').on('change', tryLoadStudents);

    // === Fee Assignments Load ===
    window.loadAssignments = function () {
        if (!$('#assignmentsTableBody').length) return;

        $.getJSON(`${apiBase}?action=get_assignments`, function (res) {
            if (res.success) {
                let rows = '';
                res.data.forEach((a, i) => {
                    rows += `
                        <tr class="urdu-regular">
                            <td class="px-4">${i + 1}</td>
                            <td>ID: ${a.student_id}</td>
                            <td>${a.fee_name}</td>
                            <td class="fw-bold">Rs. ${a.amount}</td>
                            <td>${a.due_day} تاریخ</td>
                            <td class="px-4 text-center">
                                <button class="btn btn-sm btn-outline-danger btn-del-assignment" data-id="${a.id}"><i class="bi bi-trash"></i></button>
                            </td>
                        </tr>
                    `;
                });
                $('#assignmentsTableBody').html(rows || '<tr><td colspan="6" class="text-center p-3">کوئی اسائنمنٹ نہیں ملی</td></tr>');
            }
        });
    };

    if ($('#assignmentsTableBody').length) {
        loadAssignments();
    }

    // === Fee Collection Handle ===
    $('#feeCollectionForm').on('submit', function (e) {
        e.preventDefault();
        const data = {
            action: 'collect_fee',
            student_id: $('#student_id').val(),
            fee_type_id: $('#fee_type_id').val(),
            amount: $('#amount').val(),
            payment_date: $('#payment_date').val(),
            payment_method: $('#payment_method').val(),
            month_year: $('#month_year').val()
        };

        const $btn = $('#btnCollect');
        $btn.prop('disabled', true).html('<span class="spinner-border spinner-border-sm"></span>');

        $.ajax({
            url: apiBase,
            method: 'POST',
            contentType: 'application/json',
            data: JSON.stringify(data),
            success: function (res) {
                $btn.prop('disabled', false).text('فیس وصول کریں (Collect Fee)');
                if (res.success) {
                    Swal.fire({
                        title: 'وصولی کامیاب',
                        text: `رسیڈ نمبر: ${res.receipt_no}`,
                        icon: 'success',
                        showCancelButton: true,
                        confirmButtonText: 'پرنٹ رسید',
                        cancelButtonText: 'بند کریں'
                    }).then((result) => {
                        if (result.isConfirmed) {
                            window.open(`fee_receipt_view?receipt_no=${res.receipt_no}`, '_blank');
                        }
                    });
                    $('#feeCollectionForm')[0].reset();
                } else {
                    Swal.fire('خرابی', res.message, 'error');
                }
            }
        });
    });

    // === View Ledger (from fee_collection page) ===
    $('#btnViewLedger').on('click', function () {
        const stdId = $('#student_id').val();
        if (!stdId) {
            Swal.fire('توجہ', 'برائے مہربانی پہلے طالب علم منتخب کریں', 'warning');
            return;
        }
        $('#ledgerTableBody').html('<tr><td colspan="6" class="text-center py-4"><div class="spinner-border text-primary"></div></td></tr>');
        $('#ledgerModal').modal('show');

        $.getJSON(`${apiBase}?action=get_ledger&student_id=${stdId}`, function (res) {
            if (res.success) {
                let rows = '';
                res.collections.forEach((c, i) => {
                    rows += `
                        <tr class="urdu-regular">
                            <td class="px-4">${i + 1}</td>
                            <td>${c.payment_date}</td>
                            <td>${c.fee_name}</td>
                            <td>${c.month_year}</td>
                            <td class="fw-bold">Rs. ${c.amount}</td>
                            <td>${c.payment_method}</td>
                        </tr>
                    `;
                });
                $('#ledgerTableBody').html(rows || '<tr><td colspan="6" class="text-center p-3 urdu-regular">کوئی ریکارڈ نہیں ملا</td></tr>');
            }
        });
    });

    // === Global Ledger / Reports ===
    if ($('#reportTableBody').length) {
        $('#btnRunReport').on('click', function () {
            const start = $('#reportStart').val();
            const end = $('#reportEnd').val();
            const $body = $('#reportTableBody');

            $body.html('<tr><td colspan="7" class="text-center py-4"><div class="spinner-border text-primary"></div></td></tr>');

            $.getJSON(`${apiBase}?action=get_ledger_global&start=${start}&end=${end}`, function (res) {
                if (res.success) {
                    let rows = '';
                    res.data.forEach((c, i) => {
                        rows += `
                            <tr class="urdu-regular">
                                <td class="px-4">${i + 1}</td>
                                <td>${c.payment_date}</td>
                                <td>${c.stdName} بن ${c.fatherName}</td>
                                <td>${c.fee_name}</td>
                                <td class="fw-bold">Rs. ${c.amount}</td>
                                <td>${c.payment_method}</td>
                                <td class="text-center">
                                    <a href="fee_receipt_view?receipt_no=${c.reference_no}" target="_blank" class="btn btn-sm btn-outline-info"><i class="bi bi-printer"></i></a>
                                </td>
                            </tr>
                        `;
                    });
                    $body.html(rows || '<tr><td colspan="7" class="text-center py-4">کوئی ریکارڈ نہیں ملا</td></tr>');
                }
            });
        });
    }

    // === Defaulters Logic ===
    if ($('#defaulterTableBody').length) {
        function loadDefaulters() {
            const $body = $('#defaulterTableBody');
            $.getJSON(`${apiBase}?action=get_defaulters`, function (res) {
                if (res.success) {
                    let rows = '';
                    res.data.forEach((d, i) => {
                        rows += `
                            <tr class="urdu-regular">
                                <td class="px-4">${i + 1}</td>
                                <td>${d.stdName} بن ${d.fatherName} (${d.registrationNo || 'No Reg'})</td>
                                <td>${d.fee_name}</td>
                                <td class="text-danger fw-bold">Rs. ${d.amount}</td>
                                <td>${d.due_day} تاریخ</td>
                                <td class="text-center">
                                    <button class="btn btn-sm btn-success btn-pay-now" data-std="${d.student_id}" data-type="${d.fee_type_id}" data-amount="${d.amount}">وصول کریں</button>
                                </td>
                            </tr>
                        `;
                    });
                    $body.html(rows || '<tr><td colspan="6" class="text-center py-4 text-success fs-4">تمام طلباء کی فیس جمع ہے! (No defaulters found)</td></tr>');
                }
            });
        }
        loadDefaulters();
    }

    $(document).on('click', '.btn-pay-now', function () {
        const std = $(this).data('std');
        const type = $(this).data('type');
        const amt = $(this).data('amount');
        window.location.href = `fee_collection?std=${std}&type=${type}&amt=${amt}`;
    });
});


// Additional JS for assignments list
$(document).ready(function () {
    // --- Bulk Checkboxes Logic ---
    $('#filter_darja, #filter_year').off('change'); // Unbind default combobox logic

    $('#filter_darja, #filter_year').on('change', function () {
        const darja = $('#filter_darja').val();
        const year = $('#filter_year').val();
        const container = $('#studentCheckboxesContainer');

        if (!darja || !year) {
            container.html('<div class="text-center py-4 text-muted urdu-regular">پہلے درجہ اور سال منتخب کریں</div>');
            $('#studentCountBadge').text('0');
            return;
        }

        container.html('');
        $('#studentLoadSpinner').removeClass('d-none');
        $('#studentCountBadge').text('...');

        $.getJSON(`APIs/fee_api.php?action=get_students&darja=${encodeURIComponent(darja)}&start_year=${encodeURIComponent(year)}`, function (res) {
            $('#studentLoadSpinner').addClass('d-none');
            if (res.success && res.data.length > 0) {
                let html = '<div class="list-group list-group-flush">';
                res.data.forEach(std => {
                    html += `
                            <label class="list-group-item list-group-item-action d-flex align-items-center" style="cursor: pointer;">
                                <input class="form-check-input me-3 student-checkbox ms-2" type="checkbox" value="${std.sno}">
                                <div>
                                    <div class="fw-bold urdu-regular fs-5 text-end">${std.stdName} بن ${std.fatherName}</div>
                                </div>
                            </label>
                        `;
                });
                html += '</div>';
                container.html(html);
                $('#studentCountBadge').text(res.data.length);
                $('#selectAllStudents').prop('checked', false);
            } else {
                container.html('<div class="text-center py-4 text-warning urdu-regular">اس درجہ / سال میں کوئی طالب علم نہیں ملا</div>');
                $('#studentCountBadge').text('0');
            }
        }).fail(function () {
            $('#studentLoadSpinner').addClass('d-none');
            container.html('<div class="text-center py-4 text-danger urdu-regular">ڈیٹا لوڈ نہیں ہو سکا (Load Error)</div>');
            $('#studentCountBadge').text('0');
        });
    });

    $('#selectAllStudents').on('change', function () {
        const isChecked = $(this).is(':checked');
        $('.student-checkbox').prop('checked', isChecked);
    });

    // --- Assignments Table (Read) ---
    function loadAssignments() {
        $.getJSON('APIs/fee_api.php?action=get_assignments', function (res) {
            if (res.success) {
                let rows = '';
                res.data.forEach((a, i) => {
                    const studentLabel = a.stdName ? `${a.stdName} بن ${a.fatherName}` : `ID: ${a.student_id}`;
                    const feeMonth = a.fee_month || '';
                    const feeYear = a.fee_year || '';
                    const monthYearLabel = (feeMonth && feeYear) ? `${feeMonth}-${feeYear}` : '-';
                    rows += `
                        <tr class="urdu-regular">
                            <td class="px-4">${i + 1}</td>
                            <td>${studentLabel}</td>
                            <td>${a.fee_name}</td>
                            <td class="fw-bold fs-5 text-success">Rs. ${a.amount}</td>
                            <td>${a.due_day} تاریخ</td>
                            <td><span class="badge bg-secondary">${monthYearLabel}</span></td>
                            <td class="px-4 text-center">
                                <button class="btn btn-sm btn-outline-info btn-print-assign me-1" title="Print"><i class="bi bi-printer"></i></button>
                                <button class="btn btn-sm btn-outline-primary btn-edit-assign me-1" 
                                        data-id="${a.id}" 
                                        data-std="${studentLabel}" 
                                        data-type="${a.fee_name}" 
                                        data-amt="${a.amount}" 
                                        data-due="${a.due_day}"
                                        data-feemonth="${feeMonth}"
                                        data-feeyear="${feeYear}"
                                        title="Edit"><i class="bi bi-pencil"></i></button>
                                <button class="btn btn-sm btn-outline-danger btn-del-assignment" data-id="${a.id}" title="Delete"><i class="bi bi-trash"></i></button>
                            </td>
                        </tr>
                    `;
                });
                $('#assignmentsTableBody').html(rows || '<tr><td colspan="7" class="text-center p-3 urdu-regular">کوئی اسائنمنٹ نہیں ملی</td></tr>');
            }
        });
    }

    // --- Bulk Form Submit ---
    $('#feeAssignmentForm').off('submit').on('submit', function (e) {
        e.preventDefault();

        let selectedStudents = [];
        $('.student-checkbox:checked').each(function () {
            selectedStudents.push($(this).val());
        });

        if (selectedStudents.length === 0) {
            Swal.fire('توجہ', 'براہ کرم کم از کم ایک طالب علم کا انتخاب کریں۔', 'warning');
            return;
        }

        const month = $('#assign_month').val();
        const year = $('#assign_year').val();

        if (!month || !year) {
            Swal.fire('توجہ', 'براہ کرم مہینہ اور سال بھی منتخب کریں۔', 'warning');
            return;
        }

        const data = {
            action: 'assign_fee_bulk',
            student_ids: selectedStudents,
            fee_type_id: $('#fee_type_id').val(),
            amount: $('#amount').val(),
            due_day: $('#due_day').val(),
            fee_month: month,
            fee_year: year
        };

        const $btn = $('#btnAssign');
        $btn.prop('disabled', true).html('<span class="spinner-border spinner-border-sm"></span>');

        $.ajax({
            url: 'APIs/fee_api.php',
            method: 'POST',
            contentType: 'application/json',
            data: JSON.stringify(data),
            success: function (res) {
                $btn.prop('disabled', false).text('تفویض کریں (Assign Fee)');
                if (res.success) {
                    Swal.fire('کامیابی', res.message, 'success');
                    loadAssignments();
                    $('#amount').val('');
                    $('.student-checkbox').prop('checked', false);
                    $('#selectAllStudents').prop('checked', false);
                } else {
                    Swal.fire('خرابی', res.message, 'error');
                }
            }
        });
    });

    // --- Inline Action Handlers --- 

    // Print
    $(document).on('click', '.btn-print-assign', function () {
        const tr = $(this).closest('tr');
        const stdName = tr.find('td:eq(1)').text();
        const feeType = tr.find('td:eq(2)').text();
        const amount = tr.find('td:eq(3)').text();
        const dueDay = tr.find('td:eq(4)').text();
        const monthYear = tr.find('td:eq(5)').text().trim();

        let printWindow = window.open('', '', 'height=600,width=800');
        printWindow.document.write('<html dir="rtl"><head><title>Print Report</title>');
        printWindow.document.write('<style>body { font-family: Arial, sans-serif; padding: 20px; direction: rtl; text-align: right; } h2 {border-bottom: 2px solid #ccc; padding-bottom: 10px;} table {width:100%; border-collapse:collapse;} td,th{border:1px solid #ccc;padding:8px 12px;}</style>');
        printWindow.document.write('</head><body>');
        printWindow.document.write('<h2>فیس اسائنمنٹ رپورٹ (Fee Assignment Report)</h2>');
        printWindow.document.write('<table><tr><th>طالب علم</th><td>' + stdName + '</td></tr>');
        printWindow.document.write('<tr><th>فیس کی قسم</th><td>' + feeType + '</td></tr>');
        printWindow.document.write('<tr><th>رقم</th><td>' + amount + '</td></tr>');
        printWindow.document.write('<tr><th>واجب الادا دن</th><td>' + dueDay + '</td></tr>');
        printWindow.document.write('<tr><th>مہینہ / سال</th><td>' + monthYear + '</td></tr>');
        printWindow.document.write('</table>');
        printWindow.document.write('</body></html>');
        printWindow.document.close();
        printWindow.focus();
        setTimeout(function () {
            printWindow.print();
            printWindow.close();
        }, 250);
    });

    // Delete
    $(document).on('click', '.btn-del-assignment', function () {
        const id = $(this).data('id');
        Swal.fire({
            title: 'کیا آپ واقعی ڈیلیٹ کرنا چاہتے ہیں؟',
            text: "یہ عمل واپس نہیں ہو سکتا!",
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#d33',
            cancelButtonColor: '#3085d6',
            confirmButtonText: 'ہاں، ڈیلیٹ کریں',
            cancelButtonText: 'کینسل'
        }).then((result) => {
            if (result.isConfirmed) {
                $.ajax({
                    url: 'APIs/fee_api.php',
                    type: 'POST',
                    contentType: 'application/json',
                    data: JSON.stringify({ action: 'delete_assignment', id: id }),
                    success: function (res) {
                        if (res.success) {
                            Swal.fire('Deleted!', 'ریکارڈ ڈیلیٹ ہو گیا۔', 'success');
                            loadAssignments();
                        } else {
                            Swal.fire('Error', res.message, 'error');
                        }
                    }
                });
            }
        });
    });

    // Edit
    $(document).on('click', '.btn-edit-assign', function () {
        $('#edit_assign_id').val($(this).data('id'));
        $('#edit_assign_std').val($(this).data('std'));
        $('#edit_assign_type').val($(this).data('type'));
        $('#edit_assign_amount').val($(this).data('amt'));
        $('#edit_assign_dueday').val(parseInt($(this).data('due')));
        $('#edit_assign_month').val(parseInt($(this).data('feemonth')) || '');
        $('#edit_assign_year').val($(this).data('feeyear') || new Date().getFullYear());

        let editModal = new bootstrap.Modal(document.getElementById('editAssignmentModal'));
        editModal.show();
    });

    $('#formEditAssignment').on('submit', function (e) {
        e.preventDefault();
        const editMonth = $('#edit_assign_month').val();
        const editYear = $('#edit_assign_year').val();
        const data = {
            action: 'update_assignment',
            id: $('#edit_assign_id').val(),
            amount: $('#edit_assign_amount').val(),
            due_day: $('#edit_assign_dueday').val(),
            fee_month: editMonth || null,
            fee_year: editYear || null
        };

        const $btn = $('#btnUpdateAssignment');
        $btn.prop('disabled', true).html('<span class="spinner-border spinner-border-sm"></span>');

        $.ajax({
            url: 'APIs/fee_api.php',
            type: 'POST',
            contentType: 'application/json',
            data: JSON.stringify(data),
            success: function (res) {
                $btn.prop('disabled', false).text('محفوظ کریں (Save Changes)');
                if (res.success) {
                    $('#editAssignmentModal').modal('hide');
                    Swal.fire('Success', 'ریکارڈ اپڈیٹ ہو گیا۔', 'success');
                    loadAssignments();
                } else {
                    Swal.fire('Error', res.message, 'error');
                }
            }
        });
    });

    // Load initially
    loadAssignments();
});