window.onload = function () {
    listDataToDatatable();
};

// Column selectors
const tbInvoicesList = $('.tbInvoicesList').DataTable({
    buttons: {
        buttons: [
            {
                extend: 'excelHtml5',
                className: 'btn btn-light',
                exportOptions: {
                    columns: ':visible'
                }
            },
            {
                extend: 'pdfHtml5',
                className: 'btn btn-light',
                exportOptions: {
                    columns: ':visible'
                }
            },
            {
                extend: 'colvis',
                text: '<i class="ph-list"></i>',
                className: 'btn btn-light btn-icon dropdown-toggle'
            }
        ]
    },
    order: [[0, "desc"]],
});

// Column selectors
const tbViewInvoiceDetails = $('.tbViewInvoiceDetails').DataTable({
    buttons: {
        buttons: [""]
    },
    paging: false,
    searching: false,
    info: false,
    order: false,
});

// Column selectors
const tbAddEditInvoiceDetails = $('.tbAddEditInvoiceDetails').DataTable({
    buttons: {
        buttons: [""]
    },
    paging: false,
    searching: false,
    info: false,
    order: false,
});

// Add New Enterprise
$(document).on("click", ".btnAddInvoice", function () {

    let ent_id = $.trim($("#ent_id_value").val());

    if (ent_id == "" || Number(ent_id) <= 0) {
        fnSweetToast("No enterprise was selected", "warning");
        return false;
    }

    $(".span-modal-title").text(translate.add_purchase);

    $(".btnSave").show();
    $(".btnEdit").hide();

    document.getElementById("frmAddEditInvoiceData").reset();
    $(".tbAddEditInvoiceDetails tbody tr").html("");

    $("#inv_id").val("");

    $("#pur_total").val(0);
    $("#span_pur_total").text(0.00);

    showAmount();

    $('#addEditInvoiceModal').modal('show');
});

// List All Enterprises on click btnRefresh
$(document).on("click", ".btnSearch", function () {
    let btnRefresh = "clicked";
    listDataToDatatable(btnRefresh);
});

// Get data from API
async function getDataFromAPI(props) {
    try {

        const url = `ajax/invoices.ajax.php?op=ajaxInvoicesList&ent_id=${props.ent_id}&fromDate=${props.fromDate}&toDate=${props.toDate}&status=${props.status}`;
        const response = await fetch(url);

        if (!response.ok) {
            throw new Error('Failed to get data from API');
        }

        const data = await response.json();
        return data;

    } catch (error) {
        console.log(error);
        return false;
    }
}

// List All data function
async function listDataToDatatable(btnRefresh = '') {

    // ── Helper: restore search button ─────────────────────────────────────────
    function resetSearchButton() {
        $('.btnSearch')
            .prop('disabled', false)
            .css('cursor', 'pointer')
            .html(`<i class="ph-magnifying-glass me-1"></i> ${translate.search}`);
    }

    // ── Helper: currency format (fixed locale for this module) ────────────────
    const fmt = val => showCurrencyFormat('USD', 'es-DO', val);

    // ── Lock button while loading ─────────────────────────────────────────────
    $('.btnSearch')
        .prop('disabled', true)
        .css('cursor', 'not-allowed')
        .html(translate.loading_icon_text);

    // ── Collect filter parameters ─────────────────────────────────────────────
    const [fromDate, toDate] = $.trim($('.dateSelected').val()).split(' / ');

    const props = {
        ent_id: ($("#ent_id_value").val() || '').trim(),
        status: ($(".searchStatus").val() || '').trim(),
        fromDate,
        toDate,
    };

    console.log(props);

    // ── Validate required props ───────────────────────────────────────────────
    const missingProps = Object.entries(props)
        .filter(([, value]) => value === '' || value === undefined)
        .map(([key]) => key);

    if (missingProps.length > 0) {
        resetSearchButton();
        await swalInit.fire(translate.please_fill_in_all_required_fields, missingProps.join(', '), 'warning');
        return;
    }

    let totalAmount = 0;
    let totalDebt = 0;

    try {
        const res = await getDataFromAPI(props);

        if (res.status === 'success') {

            if (btnRefresh === 'clicked') {
                fnSweetToast(translate.data_loaded_successfully, 'success', 2000);
            }

            if (res.data.length > 0) {

                const formattedData = res.data.map(item => {

                    totalAmount += Number(item.inv_total_amount);
                    totalDebt += Number(item.inv_debt);

                    const isCancelled = item.inv_status === 'Disabled';

                    // ── Invoice status badge ──────────────────────────────────
                    const statusMap = {
                        Overdue: `<span class="badge bg-danger  fw-medium text-white fs-md">${translate.overdue_f}</span>`,
                        Paid: `<span class="badge bg-success fw-medium text-white fs-md">${translate.paid_f}</span>`,
                        Disabled: `<span class="badge bg-danger  fw-medium text-white fs-md">${translate.canceled_f}</span>`,
                    };
                    const invoiceStatus = statusMap[item.inv_status]
                        ?? `<span class="badge bg-yellow fw-medium text-black fs-md">${translate.pending}</span>`;

                    // ── Action buttons hidden when cancelled ──────────────────
                    const transactionInfo = { transaction_id: item.inv_id, section: 'invoices' };
                    const transactionInfoJson = JSON.stringify(transactionInfo);
                    const itemJson = JSON.stringify(item);

                    const btnEdit = !isCancelled
                        ? `<button type="button" class="dropdown-item light-warning-on-hover"
                                   onclick='jsEditData(${itemJson})'>
                               <i class="ph-pencil-simple-line me-1"></i> ${translate.edit}
                           </button>`
                        : '';

                    const btnCancel = !isCancelled
                        ? `<div class="dropdown-divider"></div>
                           <button type="button" class="dropdown-item text-danger danger-on-hover"
                                   onclick='jsCancelTransaction(${transactionInfoJson})'>
                               <i class="ph-trash me-1"></i> ${translate.cancel}
                           </button>`
                        : '';

                    const btnOptions = `
                        <button type="button" class="btn btn-indigo dropdown-toggle"
                                data-bs-toggle="dropdown">${translate.action}</button>
                        <div class="dropdown-menu dropdown-menu-theme">
                            <button type="button" class="dropdown-item light-warning-on-hover"
                                    onclick='jsViewData(${itemJson})'>
                                <i class="ph-eye me-1"></i> ${translate.view}
                            </button>
                            ${btnEdit}
                            <button type="button" class="dropdown-item light-warning-on-hover"
                                    onclick='jsPrintData(${item.inv_id})'>
                                <i class="ph-printer me-1"></i> ${translate.print}
                            </button>
                            ${btnCancel}
                        </div>`;

                    return [
                        item.inv_id,
                        item.enterprise_name,
                        item.inv_code,
                        item.inv_date,
                        item.inv_due_date,
                        fmt(item.inv_total_amount),
                        fmt(item.inv_debt),
                        invoiceStatus,
                        btnOptions,
                    ];
                });

                tbInvoicesList.clear().rows.add(formattedData).draw();

            } else {
                tbInvoicesList.clear().draw();
            }

        } else if (res.status === 'warning') {

            tbInvoicesList.clear().draw();

        } else {

            tbInvoicesList.clear().draw();
            console.error('listDataToDatatable unexpected response:', res);
            await swalInit.fire(
                translate.data_could_not_be_loaded_please_contact_the_system_vendor_for_technical_assistance,
                '',
                'error'
            );
        }

    } catch (error) {
        tbInvoicesList.clear().draw();
        console.error('listDataToDatatable error:', error);
        await swalInit.fire(
            translate.data_could_not_be_loaded_please_contact_the_system_vendor_for_technical_assistance,
            '',
            'error'
        );

    } finally {
        resetSearchButton();
        $('#totalAmount').text(fmt(totalAmount));
        $('#totalDebt').text(fmt(totalDebt));
    }
}

/*=============================================
SHOW CUSTOMER INFORMATIONS
=============================================*/
function jsViewData(data) {

    // console.log(data);

    // Modal form
    let inv_total_amount = showCurrencyFormat("USD", "es-DO", data.inv_total_amount);
    let inv_amount = showCurrencyFormat("USD", "es-DO", data.inv_amount);
    let inv_subtotal = showCurrencyFormat("USD", "es-DO", data.inv_subtotal);
    let inv_discount_amount = showCurrencyFormat("USD", "es-DO", data.inv_discount_amount);
    let inv_tax_amount = showCurrencyFormat("USD", "es-DO", data.inv_tax_amount);

    // Create a moment object from the original date string
    let inv_date = moment(data.inv_date, 'YYYY-MM-DD');
    let inv_due_date = moment(data.inv_due_date, 'YYYY-MM-DD');

    inv_date = inv_date.format('MMMM D, YYYY');
    inv_due_date = inv_due_date.format('MMMM D, YYYY');

    $(".customerName").text(data.enterprise_name);
    $(".spanInvoiceNumber").text(`#${data.inv_code}`);
    $(".spanInvoiceDate").text(inv_date);
    $(".spanInvoiceDueDate").text(inv_due_date);
    $(".totalDue").text(inv_total_amount);
    $(".invoiceSubTotal").text(inv_subtotal);
    $(".invoiceDiscountPercent").text(`${data.inv_discount_percent}%`);
    $(".invoiceDiscountAmount").text(inv_discount_amount);
    $(".invoiceTaxPercent").text(`${data.inv_tax_percent}%`);
    $(".invoiceTaxAmount").text(inv_tax_amount);
    $(".invoiceTotalAmount").text(inv_total_amount);

    $("#viewInvoicesModal").modal("show");

    fnViewInvoiceDetails(data);
}

/*=============================================
SHOW PURCHASE DETAILS
=============================================*/
async function fnViewInvoiceDetails(data) {
    try {

        const url = `ajax/invoices.ajax.php?op=ajaxShowInvoicesDetails&inv_id=${data.inv_id}`;
        const response = await fetch(url);

        if (!response.ok) {
            throw new Error('Failed to get data from API');
        }

        const res = await response.json();
        // console.log(res);

        if (res.status == "success") {

            const tbodyInvoicesList = document.getElementById('tbodyInvoicesList');
            let html = '';

            if (res.data.length > 0) {
                res.data.forEach(item => {
                    html += ` <tr>
                        <td>${item.inv_item_description}</td>
                        <td>${item.inv_item_quantity}</td>
                        <td>${showCurrencyFormat("USD", "es-DO", item.inv_item_unit_price)}</td>
                        <td>${showCurrencyFormat("USD", "es-DO", item.inv_item_total)}</td>
                        </tr>`;
                });
            } else {
                html += `<tr><td colspan='4'>No data available</td></tr>`;
            }

            tbodyInvoicesList.innerHTML = html;
        }

        // Show total amount
        showAmount();

    } catch (error) {
        console.log(error);
    }
}

/*=============================================
SHOW CUSTOMER INFORMATIONS
=============================================*/
function jsEditData(data) {

    $(".span-modal-title").text(translate.edit_purchase);

    $(".btnSave").hide();
    $(".btnEdit").show();

    document.getElementById("frmAddEditInvoiceData").reset();
    // Modal form
    $(".pos_description").text(data.pos_name);
    $("#inv_id").val(data.inv_id);
    $("#pur_ent_id").val(data.pur_ent_id);
    $("#pur_pos_id").val(data.pur_pos_id);
    $("#pur_cost").val(data.pur_cost);
    $("#pur_date").val(data.pur_date);
    $("#pur_provider_id").val(data.pur_provider_id);
    $("#pur_shipping").val(data.pur_shipping);

    $("#addEditInvoiceModal").modal("show");

    fnEditInvoiceDetails(data.inv_id);
}

/*=============================================
SHOW PURCHASE DETAILS
=============================================*/
async function fnEditInvoiceDetails(inv_id) {

    try {

        const url = `ajax/purchases.ajax.php?op=ajaxShowPurchaseDetails&inv_id=${inv_id}`;
        const response = await fetch(url);

        if (!response.ok) {
            throw new Error('Failed to get data from API');
        }

        const res = await response.json();
        // console.log(res)

        if (res.status == "success") {

            if (res.data.length > 0) {

                const formattedData = res.data.map(item => {
                    return [
                        `<button type="button" class="btn btn-sm btn-icon rounded-pill btn-danger removeInvoiceRowSaved"><i class="mi-close"></i></button>
                        <input type="hidden" name="inv_item_ent_id[]" value="${item.inv_item_ent_id}"><input type="hidden" name="inv_item_inv_code[]" value="${item.inv_item_inv_code}"><input type="hidden" name="pur_det_pro_code[]" value="${item.pur_det_pro_code}">`,

                        `<input type="text" class="form-control form-control-lg input-group-text notAllowed" autocomplete="off" readonly value="${item.pro_description}">`,

                        `<input type="number" min="0" class="form-control form-control-lg invoiceQty" autocomplete="off" required name="inv_item_quantity[]" step="0.01" value="${item.inv_item_quantity}">`,

                        `<input type="number" min="0" class="form-control form-control-lg invoicePrice" autocomplete="off" required name="inv_item_unit_price[]" step="0.01" value="${item.inv_item_unit_price}" placeholder="0.00">`,

                        `<input type="text" class="form-control form-control-lg input-group-text notAllowed" autocomplete="off" required readonly name="inv_item_total[]" value="${item.inv_item_total}" placeholder="0.00">`,
                    ];
                });

                tbAddEditInvoiceDetails.clear().rows.add(formattedData).draw();
            } else {
                tbAddEditInvoiceDetails.clear().draw();
            }
        }

        showAmount();

    } catch (error) {
        console.log(error);
    }
}


// List All Enterprises on click btnRefresh
$(document).on("click", ".btnPrintPurchase", function () {
    let inv_id = $("#pur_print_id").val();
    jsPrintData(inv_id)
});

/*=============================================
PRINT PURCHASE
=============================================*/
function jsPrintData(inv_id) {
    var url = `reports/purchase/index.php?inv_id=${inv_id}`;
    window.open(url);
}


/*=============================================
ON COST ROW CHANGE SUM SUB_TOTAL
=============================================*/
$(document).on("change", ".invoiceQty", function () {

    if (Number($(this).val()) <= 0) {
        $(this).val(1);
        swalInit.fire(translate.the_quantity_cannot_be_less_than_one, translate.please_add_a_correct_quantity, "warning");
    }
    showAmount();
});

/*=============================================
ON COST ROW CHANGE SUM SUB_TOTAL
=============================================*/
$(document).on("change", ".invoicePrice", function () {

    if (Number($(this).val()) < 0 || Number($(this).val()) == -0) {
        $(this).val(1);
        swalInit.fire(translate.the_sale_price_cannot_be_empty_or_less_than_zero, translate.please_add_a_correct_amount, "warning");
    }
    showAmount();
});

// 
$(document).on("change", "#inv_discount_percent", function () {
    showAmount();
});

$(document).on("change", "#inv_tax_percent", function () {
    showAmount();
});


/*=============================================
VALIDATE INPUT FORM
=============================================*/
function validationToAddItem() {

    let inv_item_description = document.getElementsByName("inv_item_description[]");
    let inv_item_quantity = document.getElementsByName("inv_item_quantity[]");
    let inv_item_unit_price = document.getElementsByName("inv_item_unit_price[]");

    for (var i = 0; i < inv_item_description.length; i++) {

        let item_description = inv_item_description[i];
        let item_quantity = inv_item_quantity[i];
        let item_unit_price = inv_item_unit_price[i];

        if (item_description.value.trim() == "") {
            fnSweetToast("Please enter the invoice description", "error");
            item_description.setAttribute("style", "border:red 1px solid;");
            return false;
        } else {
            item_description.setAttribute("style", "border:light-gray 1px solid;");
        }

        if (item_quantity.value.trim() == "" || Number(item_quantity.value) <= 0) {
            fnSweetToast("Please enter the quantity", "error");
            item_quantity.setAttribute("style", "border:red 1px solid;");
            return false;
        } else {
            item_quantity.setAttribute("style", "border:light-gray 1px solid;");
        }

        if (item_unit_price.value.trim() == "" || Number(item_unit_price.value) <= 0) {
            fnSweetToast("Please enter the unit price", "error");
            item_unit_price.setAttribute("style", "border:red 1px solid;");
            return false;
        } else {
            item_unit_price.setAttribute("style", "border:light-gray 1px solid;");
        }
    }
}

// Add New Row
$(document).on("click", ".btnAddNewPurchase", function () {

    var purchaseTableSize = $('.tbAddEditInvoiceDetails tbody tr').length;

    if (purchaseTableSize > 0) {
        if (validationToAddItem() == false) {
            return false;
        } else {
            jsAddNewInvoiceRow();
        }
    } else {
        jsAddNewInvoiceRow();
    }
});

/*=============================================
ADD NEW PURCHASE ROW 
=============================================*/
function jsAddNewInvoiceRow() {

    $(".tbAddEditInvoiceDetails tbody").append(`<tr>
            <td><button type="button" class="btn btn-sm btn-icon rounded-pill btn-danger removeInvoiceRow"><i class="mi-close"></i></button></td>

            <td><input type="text" class="form-control form-control-lg" name="inv_item_description[]" autocomplete="off" value=""></td>

            <td><input type="number" min="1" class="form-control form-control-lg invoiceQty" autocomplete="off" required name="inv_item_quantity[]" value="1"></td>

            <td><input type="number" min="0" class="form-control form-control-lg invoicePrice" autocomplete="off" required name="inv_item_unit_price[]" step="0.01" value="0" placeholder="0.00"></td>

            <td><input type="text" class="form-control form-control-lg input-group-text notAllowed" autocomplete="off" required readonly name="inv_item_total[]" value="0" placeholder="0.00"></td>
            
        </tr>`);

    showAmount();
}


/*=============================================
SUMAR TODOS LOS PRECIOS
=============================================*/

async function showAmount() {

    /*========== SUMAR TODAS LAS CANTITADES AGREGADAS PARA LA CATIDAD DE PIEZAS ==========*/

    let inv_tax_percent = $('#inv_tax_percent').val();
    let inv_discount_percent = $('#inv_discount_percent').val();
    let inv_item_quantity = document.getElementsByName("inv_item_quantity[]");
    let inv_item_unit_price = document.getElementsByName("inv_item_unit_price[]");
    let inv_item_total = document.getElementsByName("inv_item_total[]");

    let finalItemSubTotal = 0;
    let finalTotalToPay = 0;

    let arrfinalItemSubTotal = [];

    for (var i = 0; i < inv_item_quantity.length; i++) {

        let itemQty = inv_item_quantity[i];
        let itemPrice = inv_item_unit_price[i];
        let itemTotal = inv_item_total[i];

        let currentItemTotal = Number(itemQty.value) * Number(itemPrice.value);
        itemTotal.value = currentItemTotal.toFixed(2);

        arrfinalItemSubTotal.push(Number(itemQty.value) * Number(itemPrice.value));
    }

    finalItemSubTotal = arrfinalItemSubTotal.reduce((previousValue, currentValue) => previousValue + currentValue, 0);
    finalTotalToPay = Number(finalItemSubTotal) - Number(inv_discount_percent) + Number(inv_tax_percent);

    /*========== MOSTRAR TODOS LOS PRECIOS ==========*/
    $('#inv_span_subtotal').text(showCurrencyFormat("USD", "es-DO", finalItemSubTotal));
    $('#inv_span_discount').text(showCurrencyFormat("USD", "es-DO", inv_discount_percent));
    $('#inv_span_tax').text(showCurrencyFormat("USD", "es-DO", inv_tax_percent));
    $('#inv_span_total').text(showCurrencyFormat("USD", "es-DO", finalTotalToPay));

}


/*=============================================
FUNCTION TO REMOVE ROW
=============================================*/
$(document).on("click", ".removeInvoiceRow", function () {
    $(this).parent().parent().remove();
    fnSweetToast(translate.row_removed, "success", 2000);
    showAmount();
});


/*=============================================
FUNCTION TO REMOVE ROW
=============================================*/
$(document).on("click", ".removeInvoiceRowSaved", async function () {

    let thisButton = $(this);

    if (sess_user_profile == 'ROOT' || sess_user_profile == 'Owner') {

        swalInit.fire({
            title: translate.are_you_sure,
            text: translate.confirm_that_you_want_to_perform_this_action,
            icon: 'question',
            showCancelButton: true,
            confirmButtonText: translate.yes,
            cancelButtonText: translate.no,
            buttonsStyling: false,
            customClass: {
                confirmButton: 'btn btn-success',
                cancelButton: 'btn btn-danger'
            }
        }).then(function (result) {
            if (result.value) {
                thisButton.parent().parent().remove();
                fnSweetToast(translate.row_removed, "success", 2000);
                showAmount();
            }
        });

    } else {

        let entInfo = await jsGetEnterpriseData();

        $("#addEditInvoiceModal").modal("hide");

        swalInit.fire({
            title: translate.cancellation_password,
            input: 'password',
            showCancelButton: true,
            inputPlaceholder: "**********",
            inputAttributes: {
                'autocapitalize': 'off',
                'autocorrect': 'off'
            },
            preConfirm: (value) => {
                if (!value) {
                    swalInit.showValidationMessage(translate.you_must_enter_the_password);
                    return false;
                } else if (value !== entInfo.ent_cancel_password) {
                    swalInit.showValidationMessage(translate.incorrect_password_please_try_again);
                    return false;
                }
                return value;
            },
            allowOutsideClick: false,
            allowEscapeKey: false,
            stopKeydownPropagation: false
        }).then((result) => {
            if (result.isConfirmed) {
                // Do something with the result
                $("#addEditInvoiceModal").modal("show");
                setTimeout(() => {
                    thisButton.parent().parent().remove();
                    fnSweetToast(translate.row_removed, "success", 2000);
                    showAmount();
                }, 500);
            } else if (result.dismiss === swalInit.DismissReason.cancel) {
                $("#addEditInvoiceModal").modal("show");
            }
        });

    }

});


/*=============================================
VALIDATE INPUT FORM
=============================================*/
function validationToSaved(type) {

    if (type === "edit") {

        var inv_id = $("#inv_id").val();

        if ($.trim(inv_id) == "" && Number(inv_id <= 0)) {
            fnSweetToast(translate.no_data_was_selected_for_updating, "error", 3500);
            return false;
        }
    }

    var purchaseTableSize = $('.tbAddEditInvoiceDetails tbody tr').length;

    if (purchaseTableSize <= 0) {
        fnSweetToast(translate.no_purchase_have_been_added, "error", 3500);
        return false;
    }

    let inv_item_ent_id = document.getElementsByName("inv_item_ent_id[]");
    let inv_item_quantity = document.getElementsByName("inv_item_quantity[]");
    let inv_item_unit_price = document.getElementsByName("inv_item_unit_price[]");

    for (var i = 0; i < inv_item_ent_id.length; i++) {
        let invoiceQtyVal = inv_item_quantity[i];
        let invoicePriceVal = inv_item_unit_price[i];

        if (invoiceQtyVal.value == "") {
            fnSweetToast(translate.quantity_must_be_at_least_one, "error");
            invoiceQtyVal.setAttribute("style", "border:red 1px solid;");
            return false;
        } else {
            invoiceQtyVal.setAttribute("style", "border:light-gray 1px solid;");
        }

        if (invoicePriceVal.value.trim() == "" || Number(invoicePriceVal.value) <= 0) {
            fnSweetToast(translate.enter_the_selling_price_of_the_product, "error");
            invoicePriceVal.setAttribute("style", "border:red 1px solid;");
            return false;
        } else {
            invoicePriceVal.setAttribute("style", "border:light-gray 1px solid;");
        }
    }
}


$(".btnSave").click(function () {
    if (validationToSaved("save") == false) {
        return false;
    } else {
        fnSaveUpdate();
    }
});


$(".btnEdit").click(function () {
    if (validationToSaved("edit") == false) {
        return false;
    } else {
        fnSaveUpdate();
    }
});

// ── Helper: set all action buttons to a given state ───────────────────────
function setButtonStatus(state) {
    if (state === 'loading') {
        $('.btnSave, .btnEdit')
            .prop('disabled', true)
            .css('cursor', 'not-allowed')
            .html(translate.waiting_icon_text);
        return;
    }
    if (state === 'ready') {
        $('.btnSave, .btnEdit')
            .prop('disabled', false)
            .css('cursor', 'pointer')
            .html(`<i class="ph-floppy-disk me-1"></i> ${translate.save}`);
    }
}


/*=============================================
FUNCTION TO SAVE OR UPDATE DATA
=============================================*/
async function fnSaveUpdate() {

    setButtonStatus('loading');

    return;

    const formPostData = new FormData($("#frmAddEditInvoiceData")[0]);
    const apiUrl = 'ajax/purchases.ajax.php?op=ajaxSaveUpdate';

    // for (var pair of formPostData.entries()) {
    //     console.log(pair[0] + " - " + pair[1]);
    // }
    // return;

    try {
        const response = await fetch(apiUrl, {
            method: 'POST',
            body: formPostData,
        });


        const res = await response.json();
        // console.log(res);

        if (res.status == "success") {

            setButtonStatus('ready');

            document.getElementById("frmAddEditInvoiceData").reset();
            fnSweetAlert(res.message, "", res.status, 1500);
            $("#addEditInvoiceModal").modal("hide");
            listDataToDatatable();

        } else {
            // console.log(data);
            swalInit.fire(translate.data_could_not_be_saved, "", res.status).then(function (result) {
                $("#addEditInvoiceModal").modal("hide");
                document.getElementById("frmAddEditInvoiceData").reset();
                setButtonStatus('ready');
            });
        }

    } catch (error) {
        console.error('Error:', error);
        swalInit.fire(translate.data_could_not_be_saved, "", "error").then(function (result) {
            $("#addEditInvoiceModal").modal("hide");
            document.getElementById("frmAddEditInvoiceData").reset();
            setButtonStatus('ready');
        });
    }
}