/**
 * defaulters_list.js
 * Handles fetching and rendering the fee defaulters list page.
 */
$(document).ready(function () {
    const apiUrl = 'APIs/defaulters_list.php';
    let searchTimer = null;

    // Set default month/year to current
    const now = new Date();
    $('#filterMonth').val(now.getMonth() + 1);
    $('#filterYear').val(now.getFullYear());

    // Initial load
    loadDefaulters();

    // Filter change → reload
    $('#filterMonth, #filterYear, #filterDarja').on('change', function () {
        loadDefaulters();
    });

    // Search input with debounce
    $('#searchInput').on('input', function () {
        clearTimeout(searchTimer);
        searchTimer = setTimeout(function () {
            loadDefaulters();
        }, 400);
    });

    // Clear search
    $('#btnClearSearch').on('click', function () {
        $('#searchInput').val('');
        loadDefaulters();
    });

    // Pay Dues button click -> Open Modal
    $(document).on('click', '.btn-pay-dues', function () {
        const d = $(this).data('std-full');
        const fMonth = $('#filterMonth').val();
        const fYear = $('#filterYear').val();

        // Use the assignment's own month/year if set, otherwise use the filter values
        const m = d.assign_month || fMonth;
        const y = d.assign_year || fYear;
        const monthYear = `${String(m).padStart(2, '0')}-${y}`;

        // Pre-fill modal
        $('#pay_std_id').val(d.student_id);
        $('#pay_fee_type_id').val(d.fee_type_id);
        $('#pay_month_year').val(monthYear);
        $('#pay_std_name').val(`${d.stdName} بن ${d.fatherName}`);
        $('#pay_fee_name').val(d.fee_name);
        $('#pay_period_label').val(`${m}/${y}`);
        $('#pay_amount').val(d.amount);
        $('#pay_ref').val('');

        // Reset button
        $('#btnSubmitPayment').prop('disabled', false).html('<i class="bi bi-check-circle me-2"></i> وصولی مکمل کریں (Submit Payment)');

        const modal = new bootstrap.Modal(document.getElementById('payDuesModal'));
        modal.show();
    });

    // Handle Payment Submission
    $('#payDuesForm').on('submit', function (e) {
        e.preventDefault();

        const data = {
            action: 'collect_fee',
            student_id: $('#pay_std_id').val(),
            fee_type_id: $('#pay_fee_type_id').val(),
            amount: $('#pay_amount').val(),
            payment_date: $('#pay_date').val(),
            payment_method: $('#pay_method').val(),
            reference_no: $('#pay_ref').val(),
            month_year: $('#pay_month_year').val()
        };

        const $btn = $('#btnSubmitPayment');
        $btn.prop('disabled', true).html('<span class="spinner-border spinner-border-sm me-2"></span> عمل جاری ہے...');

        $.ajax({
            url: 'APIs/fee_api.php',
            method: 'POST',
            contentType: 'application/json',
            data: JSON.stringify(data),
            success: function (res) {
                if (res.success) {
                    Swal.fire({
                        title: 'وصولی کامیاب',
                        text: `رسیڈ نمبر: ${res.receipt_no}`,
                        icon: 'success',
                        showCancelButton: true,
                        confirmButtonText: 'پرنٹ رسید',
                        cancelButtonText: 'بند کریں'
                    }).then((result) => {
                        $('#payDuesModal').modal('hide');
                        loadDefaulters(); // Refresh list
                        if (result.isConfirmed) {
                            window.open(`fee_receipt_view?receipt_no=${res.receipt_no}`, '_blank');
                        }
                    });
                } else {
                    $btn.prop('disabled', false).html('<i class="bi bi-check-circle me-2"></i> وصولی مکمل کریں (Submit Payment)');
                    Swal.fire('خرابی', res.message, 'error');
                }
            },
            error: function () {
                $btn.prop('disabled', false).html('<i class="bi bi-check-circle me-2"></i> وصولی مکمل کریں (Submit Payment)');
                Swal.fire('خرابی', 'سرور سے رابطہ نہیں ہو سکا', 'error');
            }
        });
    });

    /**
     * Fetch defaulters from API and render table
     */
    function loadDefaulters() {
        const month = $('#filterMonth').val();
        const year = $('#filterYear').val();
        const darja = $('#filterDarja').val();
        const search = $('#searchInput').val().trim();
        const $body = $('#defaultersTableBody');
        const $count = $('#defaultersCount');

        // Loading state
        $body.html(`
            <tr>
                <td colspan="7" class="text-center py-5">
                    <div class="spinner-border text-danger" role="status"></div>
                    <div class="mt-2 text-muted urdu-regular">لوڈ ہو رہا ہے...</div>
                </td>
            </tr>
        `);

        let params = `?month=${month}&year=${year}&darja=${darja || ''}`;
        if (search) {
            params += `&search=${encodeURIComponent(search)}`;
        }

        $.getJSON(apiUrl + params, function (res) {
            if (res.success && res.data && res.data.length > 0) {
                let rows = '';
                res.data.forEach(function (d, i) {
                    const regNo = d.registrationNo || '—';
                    const monthNames = ["", "جنوری (Jan)", "فروری (Feb)", "مارچ (Mar)", "اپریل (Apr)", "مئی (May)", "جون (Jun)", "جولائی (Jul)", "اگست (Aug)", "ستمبر (Sep)", "اکتوبر (Oct)", "نومبر (Nov)", "دسمبر (Dec)"];

                    // If assign_month is null, it's a recurring fee for the filtered month
                    const m = d.assign_month || month;
                    const y = d.assign_year || year;
                    const monthLabel = `${monthNames[m]} ${y}`;

                    rows += `
                        <tr class="urdu-regular">
                            <td class="px-3 text-center">${i + 1}</td>
                            <td>
                                <div class="fw-bold">${d.stdName} بن ${d.fatherName}</div>
                                <small class="text-muted">${regNo}</small>
                            </td>
                            <td><span class="badge bg-secondary">${d.darjaName || '—'}</span></td>
                            <td>${d.fee_name}</td>
                            <td class="fw-bold text-primary">${monthLabel}</td>
                            <td class="text-danger fw-bold">Rs. ${Number(d.amount).toLocaleString()}</td>
                            <td>${d.due_day} تاریخ</td>
                            <td class="text-center">
                                <button class="btn btn-sm btn-success btn-pay-dues px-3"
                                        data-std-full='${JSON.stringify(d)}'>
                                    <i class="bi bi-cash-coin me-1 p-1"></i> بقایا ادا کریں
                                </button>
                            </td>
                        </tr>
                    `;
                });
                $body.html(rows);
                $count.text(res.data.length);
            } else {
                $body.html(`
                    <tr>
                        <td colspan="7" class="text-center py-5">
                            <i class="bi bi-check-circle-fill text-success fs-1"></i> 
                            <div class="mt-2 text-success urdu-regular fs-4">تمام طلباء کی فیس جمع ہے!</div>
                            <div class="text-muted">(No defaulters found)</div>
                        </td>
                    </tr>
                `);
                $count.text('0');
            }
        }).fail(function () {
            $body.html(`
                <tr>
                    <td colspan="7" class="text-center py-5 text-danger urdu-regular">
                        <i class="bi bi-exclamation-triangle fs-1"></i>
                        <div class="mt-2">ڈیٹا لوڈ نہیں ہو سکا (Network Error)</div>
                    </td>
                </tr>
            `);
            $count.text('0');
        });
    }
});
