$(document).ready(function () {
    $('.selectize').selectize();
    $('#txtLoan').selectize();
});

// Member Change → Load Loans
$('body').on('change', '#txtMember', function () {
    $("#loader").show();
    var formData = new FormData();

    var CSRF_TOKEN = $('meta[name="csrf-token"]').attr("content");
    formData.append("_token", CSRF_TOKEN);

    var txtMember = $('#txtMember').val();
    formData.append('txtMember', txtMember);

    if (txtMember == '') {
        $.alert({
            title: "Error!",
            content: "Please select the member",
            type: "red",
            theme: 'modern',
            buttons: { okay: { text: "Okay", btnClass: "btn-red", action: function () { $("#loader").hide(); } } },
        });
        return false;
    }

    getUserLocation().then(({ latitude, longitude }) => {
        formData.append('latitude', latitude);
        formData.append('longitude', longitude);
        makeAjaxRequest(formData);
    });
});

function makeAjaxRequest(formData) {
    $.ajax({
        url: "/get-member-loan-data",
        type: "POST",
        data: formData,
        processData: false,
        contentType: false,
        beforeSend: function () { $("#loader").show(); },
        success: function (response) {
            $("#loader").hide();
            if (response.code === 200) {
                $("#txtLoan")[0].selectize.destroy();
                $("#txtLoan").empty().append(response.getAllLoanOption).selectize();
            } else {
                showAlert("Alert", "Something went wrong");
            }
        },
        error: function (xhr, status, error) {
            $("#loader").hide();
            console.error("Error:", error);
            showAlert("Error!", "Something went wrong!");
        },
    });
}

// Add Loan Data
$('body').on('click', '#btnAddLoandata', function () {
    $("#loader").show();
    var formData = new FormData();

    var CSRF_TOKEN = $('meta[name="csrf-token"]').attr("content");
    formData.append("_token", CSRF_TOKEN);

    var txtLoan = $('#txtLoan').val();
    var txtPaymentDate = $('#txtPaymentDate').val();

    formData.append('txtLoan', txtLoan);
    formData.append('txtPaymentDate', txtPaymentDate);

    if (txtLoan == '') {
        $.alert({
            title: "Error!",
            content: "Please select the loan",
            type: "red",
            theme: 'modern',
            buttons: { okay: { text: "Okay", btnClass: "btn-red", action: function () { $("#loader").hide(); } } },
        });
        return false;
    }

    getUserLocation().then(({ latitude, longitude }) => {
        formData.append('latitude', latitude);
        formData.append('longitude', longitude);
        makeAjaxRequestLoanGet(formData);
    });
});

function makeAjaxRequestLoanGet(formData) {
    $.ajax({
        url: "/get-loan-repayment-data",
        type: "POST",
        data: formData,
        processData: false,
        contentType: false,
        beforeSend: function () { $("#loader").show(); },
        success: function (response) {
            $("#loader").hide();

            if (response.code === 200) {
                let formatNum = num => new Intl.NumberFormat('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 }).format(num);

                if (parseFloat(response.balancePay) < 0) return;

                let loanCounter = $('#tblLoanRepayment tbody tr').length + 1;

                // ✅ Calculate total including arrears
                let totalPayment = parseFloat(response.interest) 
                                 + parseFloat(response.arrearsInterest) 
                                 + parseFloat(response.principalPayment);

                const row = `
                    <tr>
                        <td>${loanCounter}</td>
                        <td class='loan-id'>${response.loanId}</td>
                        <td class='loan-amount text-end'>${formatNum(response.loanAmount)}</td>
                        <td class='days text-end'>${response.days}</td>
                        <td class='interest text-end'>${formatNum(response.interest)}</td>
                        <td class='arrears-interest text-end'>${formatNum(response.arrearsInterest)}</td>
                        <td class='principal text-end'>${formatNum(response.principalPayment)}</td>
                        <td class='total text-end'>${formatNum(totalPayment)}</td>
                        <td class='balance text-end'>${formatNum(response.balancePay)}</td>
                    </tr>
                `;

                $('#tblLoanRepayment tbody').append(row);

            } else if (response.code === 202) {
                showAlert("Alert", response.message);
            } else {
                showAlert("Alert", "Something went wrong");
            }
        },
        error: function (xhr, status, error) {
            $("#loader").hide();
            console.error("Error:", error);
            showAlert("Error!", "Something went wrong!");
        },
    });
}

// Submit Repayment Data
$('body').on('click', '#txtRepaymentAmount', function () {
    $("#loader").show();
    var formData = new FormData();

    var CSRF_TOKEN = $('meta[name="csrf-token"]').attr("content");
    formData.append("_token", CSRF_TOKEN);

    var txtMember = $('#txtMember').val();
    formData.append('txtMember', txtMember);

    var txtLoan = $('#txtLoan').val();
    formData.append('txtLoan', txtLoan);

    var txtPaymentDate = $('#txtPaymentDate').val();
    formData.append('txtPaymentDate', txtPaymentDate);

    var txtSavingAmount = $('#txtSavingAmount').val();
    formData.append('txtSavingAmount', txtSavingAmount);

    // Get the old receipt number
    var txtOldReceiptNumber = $('#txtOldReceiptNumber').val();
    formData.append('txtOldReceiptNumber', txtOldReceiptNumber);

    // Get the pay amount from the separate field
    var txtPayAmount = $('#txtPayAmount').val();
    formData.append('payAmount', txtPayAmount); // Changed from txtPayAmount to payAmount to match server expectation

    let loanData = [];

    $('#tblLoanRepayment tbody tr').each(function () {
        const loanId = $(this).find('.loan-id').text().trim();
        const loanAmount = parseFloat($(this).find('.loan-amount').text().replace(/,/g, ''));
        const days = parseInt($(this).find('.days').text().trim(), 10);
        const interest = parseFloat($(this).find('.interest').text().replace(/,/g, ''));
        const arrearsInterest = parseFloat($(this).find('.arrears-interest').text().replace(/,/g, ''));
        const principal = parseFloat($(this).find('.principal').text().replace(/,/g, ''));
        const total = parseFloat($(this).find('.total').text().replace(/,/g, ''));
        const balance = parseFloat($(this).find('.balance').text().replace(/,/g, ''));

        loanData.push({
            loanId,
            loanAmount,
            days,
            interest,
            arrearsInterest,
            principal,
            total,
            balance,
            payAmount: txtPayAmount // Add payAmount to each loan object
        });
    });

    console.log(loanData);
    formData.append('loanData', JSON.stringify(loanData));

    if (loanData.length === 0 && (!txtSavingAmount || parseFloat(txtSavingAmount) <= 0) && (!txtPayAmount || parseFloat(txtPayAmount) <= 0)) {
        $.alert({
            title: "Error!",
            content: "Please enter a saving amount, pay amount, or add at least one loan to repay.",
            type: "red",
            theme: 'modern',
            buttons: { okay: { text: "Okay", btnClass: "btn-red", action: function () { $("#loader").hide(); } } },
        });
        return false;
    }
    if (txtMember == '') {
        $.alert({
            title: "Error!",
            content: "Please select the member",
            type: "red",
            theme: 'modern',
            buttons: { okay: { text: "Okay", btnClass: "btn-red", action: function () { $("#loader").hide(); } } },
        });
        return false;
    }

    getUserLocation().then(({ latitude, longitude }) => {
        formData.append('latitude', latitude);
        formData.append('longitude', longitude);
        makeAjaxRequestRepayment(formData);
    });
});

function makeAjaxRequestRepayment(formData) {
    $.ajax({
        url: "/pay-repayment-data",
        type: "POST",
        data: formData,
        processData: false,
        contentType: false,
        beforeSend: function () { $("#loader").show(); },
        success: function (response) {
            $("#loader").hide();
            handleResponse(response);
        },
        error: function (xhr, status, error) {
            $("#loader").hide();
            console.error("Error:", error);
            showAlert("Error!", "Something went wrong!");
        },
    });
}

// File Import for Repayment
$('body').on('click', '#btnImportRepayment', function () {
    $("#loader").show();
    var formData = new FormData();

    var CSRF_TOKEN = $('meta[name="csrf-token"]').attr("content");
    formData.append("_token", CSRF_TOKEN);

    let fileInput = document.getElementById('txtImportFile');
    let file = fileInput.files[0];

    if (!file) {
        $.alert({
            title: "Error!",
            content: "Please Select the file",
            type: "red",
            theme: 'modern',
            buttons: { okay: { text: "Okay", btnClass: "btn-red", action: function () { $("#loader").hide(); } } },
        });
        return false;
    }
    formData.append("file", file);

    getUserLocation().then(({ latitude, longitude }) => {
        formData.append('latitude', latitude);
        formData.append('longitude', longitude);
        makeAjaxRequestImport(formData);
    });
});

function makeAjaxRequestImport(formData) {
    $.ajax({
        url: "/import-repayment-data",
        type: "POST",
        data: formData,
        processData: false,
        contentType: false,
        beforeSend: function () { $("#loader").show(); },
        success: function (response) {
            $("#loader").hide();
            handleResponse(response);
        },
        error: function (xhr, status, error) {
            $("#loader").hide();
            console.error("Error:", error);
            showAlert("Error!", "Something went wrong!");
        },
    });
}

// Helper Alert
function showAlert(title, content) {
    $.alert({
        title: title,
        content: content,
        icon: "fa fa-exclamation-triangle",
        type: "red",
        theme: "modern",
        buttons: { okay: { text: "Okay", btnClass: "btn-red", action: function () { $("#loader").hide(); } } },
    });
}