let transactionId = 0;

(function init() {

    if (currentLocationSplited[0] == "sell") {

        var ent_id = $("#sale_ent_id").val();

        localStorage.setItem("PosProductListLimit", 18);

        if (currentLocationSplited[1] == 'det' && Number(currentLocationSplited[2] > 0)) {

            transactionId = currentLocationSplited[2];
            storeSaleData(transactionId);

        } else {
            // console.log(`No id was found in url`);
            $("#inputLoadSaleById").focus();
            selectBranchToSell(ent_id);
            js_selectListTable();
            js_selectListFiscalReceipt(ent_id);
        }
    }
})();


async function storeSaleData(transactionId) {

    let sale_info = await getSaleData(transactionId);

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

        if (Number(sess_ent_id) === Number(sale_info.data.sale_ent_id) || sess_user_profile == "ROOT") {
            let posInfo = await getBranchData(sale_info.data.sale_pos_id);
            jsStorePosInfo(posInfo);
            localStorage.setItem("sale_info", JSON.stringify(sale_info.data));
            jsShowSaleInfo();
        } else {
            localStorage.removeItem("sale_info");
            fnSweetToast(translate.sale_not_found, sale_info.status, 2500);
        }

    } else if (sale_info.status == "warning") {
        localStorage.removeItem("sale_info");
        fnSweetToast(translate.sale_not_found, sale_info.status, 2500);
    } else {
        localStorage.removeItem("sale_info");
        fnSweetToast(translate.data_could_not_be_loaded_please_contact_the_system_vendor_for_technical_assistance, sale_info.status, 3500);
    }
}

/*================================================
FUNCTION TO SHOW ALL BRANCHES LIST
=================================================*/
async function selectBranchToSell(ent_id = "", pos_id = "") {

    try {

        const url = `ajax/branches.ajax.php?op=ajax_selectBranchesByUserPermission&ent_id=${ent_id}&pos_id=${pos_id}`;
        const response = await fetch(url);

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

        const res = await response.json();

        const userPosAccess = JSON.parse(res.data);

        $("#sale_pos_id").html("");

        if (res.status == "success") {
            if (userPosAccess.length > 1) {

                if (pos_id == "") {
                    $("#sale_pos_id").append(`<option value="">-- ${translate.select} --</option>`);
                }

                userPosAccess.forEach(item => {
                    $("#sale_pos_id").append(`<option value='${item.pos_id}'>${item.pos_name}</option>`);
                });
            } else {
                $("#sale_pos_id").append(`<option value='${userPosAccess[0].pos_id}'>${userPosAccess[0].pos_name}</option>`);
            }

            $("#sale_pos_id").trigger("change");

            return true;

        } else if (res.status == "warning") {
            $("#sale_pos_id").append(`<option value="">-- ${translate.select} --</option>`);
            swalInit.fire(res.title, res.message, res.status).then(function (result) {
                // return false;
                window.location = "sell";
            });

        } else {
            $("#sale_pos_id").append(`<option value="">-- ${translate.select} --</option>`);
            console.log(res);
        }

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

// ON CHANGE BRANCH ID
$(document).on("change", "#sale_pos_id", function () {

    let pos_id = $(this).val();

    if (Number(pos_id) >= 1) {
        jsOnChangeBranchId(pos_id);
    }

});

async function jsOnChangeBranchId(pos_id) {

    var ent_id = $("#sale_ent_id").val();

    let posInfo = await getBranchData(pos_id);
    jsStorePosInfo(posInfo);

    // Get object from localStorage
    let pos_info = JSON.parse(localStorage.getItem("pos_info"));

    if (Number(transactionId) <= 0) {
        fnSelectCustomersList();
        js_SelectSaleType(pos_id);

        if (pos_info.pos_status == "Disabled") {
            swalInit.fire(translate.this_point_of_sale_is_closed, translate.please_contact_the_system_provider, "warning");
            selectBranchToSell(ent_id);
            return false;
        }
    }

    $(".pos_description").text($("#sale_pos_id option:selected").text());
    $(".divBranchSelect").hide();
    $(".divBranchDescription").show();

    js_SelectPaymentType(ent_id, pos_id);

    $("#pos_cash_back_percentage").val(pos_info.pos_cash_back_percentage);
    $("#pos_cash_back_status").val(pos_info.pos_cash_back_status);

    if (pos_info.pos_cash_back_status == "On") {
        $(".trCashBackinfo").show();
    }
};

async function js_SelectPaymentType(ent_id, pos_id) {

    if (Number(pos_id) <= 0) {
        $("#cbo_payment_type").html("");
        $("#cbo_payment_type").append(`<option value="">-- ${translate.select} --</option>`);
        return;
    }

    try {

        const url = `ajax/payment-types.ajax.php?op=ajaxSelectPaymentType&ent_id=${ent_id}&pos_id=${pos_id}&section=sell`;
        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);

        $("#cbo_payment_type").html("");

        if (res.status == "success") {
            res.data.forEach(item => {
                let payTypeName = item.pay_type_name;
                if (payTypeName.toUpperCase() == "CASH") payTypeName = translate.cash;
                if (payTypeName.toUpperCase() == "CREDIT CARD") payTypeName = translate.credit_card;
                if (payTypeName.toUpperCase() == "DEBIT CARD") payTypeName = translate.debit_card;
                if (payTypeName.toUpperCase() == "BANK DEPOSIT") payTypeName = translate.bank_deposit;

                payTypeName = payTypeName.toLowerCase().replace(/\b\w/, char => char.toUpperCase());

                $("#cbo_payment_type").append(`<option value='${item.pay_type_name}'>${payTypeName}</option>`);
            });
        }

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

/*================================================
FUNCTION TO SHOW ALL CLIENTS LIST
=================================================*/
async function fnSelectCustomersList(ent_id = "", cus_id = "") {
    try {

        const url = `ajax/customers.ajax.php?op=ajaxSelectCustomer&ent_id=${ent_id}&cus_id=${cus_id}`;
        const response = await fetch(url);

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

        const res = await response.json();

        $("#sale_cus_id").html("");

        if (cus_id == "") {
            $("#sale_cus_id").append(`<option value="">-- ${translate.select} --</option>`);
        }

        if (res.status == "success") {
            res.data.forEach(item => {
                $("#sale_cus_id").append(`<option value='${item.cus_id}'>${item.cus_full_name}</option>`);
            });

            // if (cus_id > 0) {
            $("#sale_cus_id").trigger("change");
            // }
        }

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


// GET CUSTOMER DEBT ON CHANGE
$(document).on("change", "#sale_cus_id", async function () {

    var ent_id = $("#sale_ent_id").val();
    var cus_id = $(this).val();

    var parameters = {
        ent_id: ent_id,
        cus_id: cus_id,
    }

    if (Number(cus_id) > 0) {

        try {

            // Get object from localStorage
            let pos_info = JSON.parse(localStorage.getItem("pos_info"));

            let cusInfo = await getCustomerDataById(cus_id)
            $("#sale_cus_fiscal_number").val(cusInfo.data.cus_fiscal_number);

            let customerCashBack = await getCustomerCashBack(cus_id);
            $("#customerCashBack").val(customerCashBack.data.available_cashback);
            $("#span_available_cash_back").text(showCurrencyFormat(pos_info.pos_currency, pos_info.pos_country_code, customerCashBack.data.available_cashback));

            const response = await $.ajax({
                type: "GET",
                url: "ajax/customers.ajax.php?op=ajaxShowCustomerDebt",
                data: parameters,
            });

            // Handle the response
            if (Number(response) > 0) {

                var total_client_debt = showCurrencyFormat(pos_info.pos_currency, pos_info.pos_country_code, response);

                swalInit.fire({
                    title: `${translate.this_customer_has_a_debt_of} ${total_client_debt}`,
                    text: translate.make_sure_you_collect_the_debt,
                    icon: "warning",
                    confirmButtonText: `<i class="ph-arrow-right me-1"></i> ${translate.continue}`,
                    buttonsStyling: false,
                    customClass: {
                        confirmButton: 'btn btn-indigo',
                    }
                });
            }

        } catch (error) {
            // Handle any errors that might occur during the request
            console.error(error);
        }
    }
});

/*================================================
FUNCTION TO SHOW ALL SALES TYPE LIST
=================================================*/
async function js_SelectSaleType(pos_id = "", sale_type_name = "") {

    let pos_info = JSON.parse(localStorage.getItem("pos_info"));

    if (Number(pos_id) <= 0) {
        $("#sale_type").html("");
        $("#sale_type").append(`<option value="">-- ${translate.select} --</option>`);
        return;
    }

    try {

        const url = `ajax/sale-types.ajax.php?op=ajaxSelectSaleType&pos_id=${pos_id}&sale_type_name=${sale_type_name}`;
        const response = await fetch(url);

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

        const res = await response.json();

        $("#sale_type").html("");

        if (res.status == "success") {
            res.data.forEach(item => {
                let saleTypeName = item.sale_type_name;
                if (saleTypeName == "Local" && pos_info.pos_business_category == "Restaurant") saleTypeName = translate.local_sale_type;
                if (saleTypeName == "Delivery") saleTypeName = translate.delivery;
                if (saleTypeName == "Take Away") saleTypeName = translate.takeaway;
                if (saleTypeName == "Without Taxes") saleTypeName = translate.without_taxes;
                $("#sale_type").append(`<option value='${item.sale_type_name}'>${saleTypeName}</option>`);
            });

            $("#sale_type").trigger("change");
        }

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

$(document).on("change", "#sale_type", async function () {
    let sale_type = $(this).val();
    jsOnchangeSaleType(sale_type);
});

async function jsOnchangeSaleType(sale_type) {

    let entInfo = await jsGetEnterpriseData();

    // Get object from localStorage
    let pos_info = JSON.parse(localStorage.getItem("pos_info"));

    let saleTaxPercent = pos_info.pos_tax;
    let saleTaxTippingPercent = pos_info.pos_legal_tipping;

    if (Number(transactionId) > 0) {
        // Get object from localStorage
        let sale_info = JSON.parse(localStorage.getItem("sale_info"));

        saleTaxPercent = sale_info.sale_tax_percent;
        saleTaxTippingPercent = sale_info.sale_tax_law_percent;

    } else {
        localStorage.removeItem("sale_info");
    }

    if (pos_info.pos_business_category == "Restaurant" || pos_info.pos_business_category == "Nightclub") {

        if (pos_info.pos_legal_tipping > 0) {
            $("#sale_tax_law_percent").val(saleTaxTippingPercent);
            $("#pos_legal_tipping").val(saleTaxTippingPercent);
            $(".spanLawPercent").text(`(${saleTaxTippingPercent}%)`);
        }

        if (sale_type == "Take Away" || sale_type == "Pedidos Ya" || sale_type == "Uber Eats" || sale_type == "Didi Food") {
            $(".divTax").show();
            $(".spanTaxPercent").text(`(${saleTaxPercent}%)`);
            $("#sale_tax_percent").val(saleTaxPercent);
            $(".divTableSelect").hide();
            $(".divCostDelivery").hide();
            $("#sale_cost_delivery").val(0);
            $(".divTotalDelivery").hide();
            $(".divLegalTipping").hide();
            $("#sale_tax_law_percent").val(0);
            $("#sale_tax_law_value").val(0);

        } else if (sale_type == "Local") {
            $(".divTax").show();
            $(".spanTaxPercent").text(`(${saleTaxPercent}%)`);
            $("#sale_tax_percent").val(saleTaxPercent);
            $("#sale_tax_law_percent").val(saleTaxTippingPercent);
            $(".divTableSelect").show();
            $(".divCostDelivery").hide();
            $("#sale_cost_delivery").val(0);
            $(".divTotalDelivery").hide();
            $(".divLegalTipping").show();
        }

    } else {

        $("#pos_legal_tipping").val(0);
        $("#sale_tax_law_percent").val(0);
        $("#sale_tax_law_value").val(0);
        $(".divTableSelect").hide();
        $(".divLegalTipping").hide();
        $(".spanLawPercent").text(`(0%)`);

        if (sale_type == "Local") {
            $(".divTax").show();
            $(".spanTaxPercent").text(`(${saleTaxPercent}%)`);
            $("#sale_tax_percent").val(saleTaxPercent);
            $(".divCostDelivery").hide();
            $("#sale_cost_delivery").val(0);
            $(".divTotalDelivery").hide();
        }
    }

    if (sale_type == "Delivery") {

        $(".divTax").show();
        $(".spanTaxPercent").text(`(${saleTaxPercent}%)`);
        $("#sale_tax_percent").val(saleTaxPercent);
        $(".divTableSelect").hide();
        $(".divCostDelivery").show();
        $(".divLegalTipping").hide();
        $(".divTotalDelivery").show();
        $("#sale_tax_law_percent").val(0);
        $("#sale_tax_law_value").val(0);

    } else if (sale_type == "Without Taxes") {

        if (sess_user_profile == "ROOT" || sess_user_profile == "Owner") {
            $(".divTableSelect").hide();
            $(".divTax").hide();
            $(".spanTaxPercent").text(`(0%)`);
            $("#sale_tax_percent").val(0);
            $("#sale_tax_value").val(0);
            $(".divCostDelivery").hide();
            $("#sale_cost_delivery").val(0);
            $(".divLegalTipping").hide();
            $("#sale_tax_law_percent").val(0);
            $("#sale_tax_law_value").val(0);
        } else {

            swalInit.fire({
                title: translate.discount_password,
                input: 'password',
                showCancelButton: true,
                inputPlaceholder: "**********",
                inputAttributes: {
                    'autocapitalize': 'off',
                    'autocorrect': 'off',
                    autocomplete: 'off'
                },
                preConfirm: (value) => {
                    if (!value) {
                        swalInit.showValidationMessage(translate.you_must_enter_the_password);
                        return false;
                    } else if (value !== entInfo.ent_discount_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
                    $(".divTableSelect").hide();
                    $(".divTax").hide();
                    $(".spanTaxPercent").text(`(0%)`);
                    $("#sale_tax_percent").val(0);
                    $("#sale_tax_value").val(0);
                    $(".divCostDelivery").hide();
                    $("#sale_cost_delivery").val(0);
                    $(".divLegalTipping").hide();
                    $("#sale_tax_law_percent").val(0);
                    $("#sale_tax_law_value").val(0);

                    // GENERATE A NEW DISCOUNT PASSWORD
                    $.post("ajax/enterprises.ajax.php?op=ajaxGenerateNewDiscountPassword", { entId: entInfo.ent_id, csrf_token: csrf_token }, function (response) { });

                } else if (result.dismiss === swalInit.DismissReason.cancel) {
                    js_SelectSaleType(pos_info.pos_id);
                }
            });
        }
    }

    showAmount();
}

/*================================================
FUNCTION TO SHOW ALL TABLES LIST
=================================================*/
async function js_selectListTable(table_id = "") {
    try {
        const url = `ajax/tables.ajax.php?op=ajax_selectTable&table_id=${table_id}`;
        const response = await fetch(url);

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

        const res = await response.json();

        $("#sale_table_id").html("");

        if (res.status == "success") {
            res.data.forEach(item => {
                $("#sale_table_id").append(`<option value='${item.table_id}'>${translate.table} ${item.table_id}</option>`);
            });
        }

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

// Add New Customer
function jsAddCustomer() {

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

    $(".btnSaveCustomer").show();
    $(".btnEditCustomer").hide();

    document.getElementById("frmAddEditCustomer").reset();

    $("#cus_id").val("");
    $("#cus_ent_id").val($("#sale_ent_id").val());
    $("#cus_pos_id").val($("#sale_pos_id").val());

    $('#customer-modal').modal('show');
}

async function jsEditCustomer() {

    $(".btnSaveCustomer").hide();
    $(".btnEditCustomer").show();

    $(".span-modal-title").text(translate.edit_customer);
    document.getElementById("frmAddEditCustomer").reset();

    let cus_id = $("#sale_cus_id").val();

    if (cus_id != "") {
        let cusInfo = await getCustomerDataById(cus_id);

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

            let data = cusInfo.data;

            $("#cus_id").val(data.cus_id);
            $("#cus_ent_id").val(data.cus_ent_id);
            $("#cus_pos_id").val(data.cus_pos_id);
            $("#cus_full_name").val(data.cus_full_name);
            $("#cus_phone").val(data.cus_phone);
            $("#cus_email").val(data.cus_email);
            $("#cus_address").val(data.cus_address);
            $("#cus_fiscal_number").val(data.cus_fiscal_number);

            $("#customer-modal").modal("show");
        }
    } else {
        fnSweetToast(translate.select_a_customer, "warning", 2000);
    }
}

$(".btnSaveCustomer").click(function () {
    if (validateCustomerForm("save") == false) {
        return false;
    } else {
        fnSaveUpdateCustomer();
    }
});


$(".btnEditCustomer").click(function () {
    if (validateCustomerForm("edit") == false) {
        return false;
    } else {
        fnSaveUpdateCustomer();
    }
});

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

    if (type == "edit") {

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

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

    var cus_full_name = $("#cus_full_name").val();
    var cus_email = $("#cus_email").val();

    if ($.trim(cus_full_name) == "") {
        $("#cus_full_name").css("border", "1px solid red ");
        fnSweetToast(translate.you_must_enter_the_customer_name, "error", 3500);
        return false;
    } else {
        $("#cus_full_name").css("border", `1px solid ${borderColorValidated}`);
    }

    if ($(".intelli-shared-phone").val() != "") {
        if (!intlPhoneFormatShared.isValidNumber()) {
            fnSweetToast(translate.invalid_phone_number_please_try_again, "error", 3500);
            $(".intelli-shared-phone").css("border", "1px solid red");
            return false;
        } else {
            $(".intelli-shared-phone").css("border", `1px solid ${borderColorValidated}`);
        }
    }

    if (cus_email != "") {
        if (validateEmail(cus_email.trim()) == false) {
            $("#cus_email").css("border", "1px solid red ");
            fnSweetToast(translate.invalid_email_address, "error", 3500);
            return false;
        } else {
            $("#cus_email").css("border", `1px solid ${borderColorValidated}`);
        }
    }
}

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

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

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

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

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

            let cus_id = $("#cus_id").val();
            let cus_ent_id = $("#cus_ent_id").val();

            fnSweetAlert(data.message, "", data.status, 1500);
            $("#customer-modal").modal("hide");

            if (Number(cus_id) >= 1) {
                fnSelectCustomersList(cus_ent_id, cus_id);
            } else {
                fnSelectCustomersList();
            }

            document.getElementById("frmAddEditCustomer").reset();

        } else {
            console.log(data);
            swalInit.fire(translate.data_could_not_be_saved, "", data.status).then(function (result) {
                $("#customer-modal").modal("hide");
                document.getElementById("frmAddEditCustomer").reset();
            });
        }

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

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

$("#inputProductSearch").keydown(function (e) {
    if (e.which === 13) {

        var sale_pos_id = $("#sale_pos_id").val();
        var productNameOrBarcode = $("#inputProductSearch").val();
        $("#inputProductSearch").val("");

        if (productNameOrBarcode == "" || $.trim(productNameOrBarcode) == "") {

            // $("#inputProductSearch").focus();
            $("#inputProductSearch").css("border", "1px solid red");
            fnSweetToast(translate.scan_or_type_the_product_name, "warning", 1500);
            return false;

        } else {

            $("#inputProductSearch").css("border", `1px solid ${borderColorValidated}`);

            if (/[^a-zA-Z0-9]/.test(productNameOrBarcode)) {
                // Invalid input: contains non-alphanumeric characters
                fnSweetToast(translate.please_enter_only_alphanumeric_characters, "warning", 2500);
                return false;
            } else {

                var sale_status = $('#sale_status').val();

                if (sale_status == "Disabled") {
                    fnSweetToast(translate.this_sale_has_been_canceled, "error")
                    return false;
                }

                $.post("ajax/products.ajax.php?op=ajax_addProductWithBarCode", {
                    pro_code: productNameOrBarcode, sale_pos_id: sale_pos_id, csrf_token: csrf_token
                }, function (data, status) {

                    data = JSON.parse(data);

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

                        // CHECK IF THE QUERY AJAX RESULT IS DIFERRENTE OF NULL
                        if (data == null || data == undefined || data == false || data == '') {
                            fnSweetToast(translate.code_not_found_or_invalid, "warning");
                            return false;
                        } else {
                            jsAddProductToCart(data);
                        }

                    } else {
                        fnSweetToast(data.message, 'warning');
                    }

                });
            }
        }
    }
});


var productSearchTimeId = null;
$("#inputProductSearch").keyup(function (e) {

    var sale_ent_id = $("#sale_ent_id").val();
    var sale_pos_id = $("#sale_pos_id").val();
    var productNameOrBarcode = $("#inputProductSearch").val();

    if (productNameOrBarcode == "" || $.trim(productNameOrBarcode) == "") {
        // $("#inputProductSearch").focus();
    }

    if (productSearchTimeId) {
        clearTimeout(productSearchTimeId);
    }

    productSearchTimeId = setTimeout(() => {

        if (/[^a-zA-Z0-9]/.test(productNameOrBarcode)) {
            fnSweetToast(translate.please_enter_only_alphanumeric_characters, "warning", 2500);
            return false;
        } else {
            jsShowProductList(sale_ent_id, sale_pos_id, productNameOrBarcode, "");
            $("#inputProductSearch").css("border", `1px solid ${borderColorValidated}`);
        }

    }, 300);

});

// ONCLICK GENERAR NUEVO CODIGO DE PEDIDO
$(document).on("click", ".btnShowNewProductOrder", function () {

    let sale_ent_id = $("#sale_ent_id");
    let sale_pos_id = $("#sale_pos_id");

    if (sale_pos_id.val().trim() === "") {
        sale_pos_id.focus();
        sale_pos_id.next(".select2").css("border", "1px solid red");
        swalInit.fire(translate.please_select_a_branch, "", "warning");
        return false;
    } else {
        sale_pos_id.next(".select2").css("border", "none");
    }

    // $(this).remove();
    // $(this).prop("disabled", true);
    // $(this).html(`${translate.loading_icon_text}`);

    $("#inputProductSearch").prop('disabled', false);
    // $(".btnSearchProduct").prop('disabled', false);
    $("#inputProductSearch").val("");
    // $("#inputProductSearch").focus();

    $.ajax({
        url: "ajax/sales.ajax.php?op=ajax_newOrderCode",
        beforeSend: function () {
            // $(".btnShowNewProductOrder").html(`${translate.loading_icon_text}`);
        },
        success: function (datos) {
            // $(".btnShowNewProductOrder").html(`<i class="ph-circles-four me-2"></i> ${translate.show_products}`);
            $("#txt_ord_det_code").val(datos);
        },
    });

    jsShowProductList(sale_ent_id.val(), sale_pos_id.val(), "", 18);

});

async function getProductsListToSale(props) {
    try {

        const url = `ajax/products.ajax.php?op=ajaxShowProductListToSale&ent_id=${props.ent_id}&pos_id=${props.pos_id}&productNameOrBarcode=${props.productNameOrBarcode}&PosProductListLimit=${props.PosProductListLimit}`;
        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);
        // $(".btnReloadNewOrder").show();
        $(".posProductListContainer").show();
        $(".posProductLoadingStatus").show();
        $(".posProductLoadingStatus").html(`${translate.no_products_found}`);

        $(".btnNewProductOrder").prop("disabled", false);
        $(".btnNewProductOrder").html(`<i class="ph-circles-four me-2"></i> ${translate.show_products}`);
        $(".btnNewProductOrder").addClass("btnShowNewProductOrder");

        // $("#inputProductSearch").focus();
        return false;
    }
}

/*=============================================
SHOW PRODUCTS LIST
=============================================*/
async function jsShowProductList(sale_ent_id, sale_pos_id, productNameOrBarcode = "", PosProductListLimit = "") {

    $(".posProductListContainer").show();
    $(".posProductLoadingStatus").html(`${translate.loading_icon_text}`);

    $(".btnNewProductOrder").prop("disabled", true);
    $(".btnNewProductOrder").html(`${translate.loading_icon_text}`);

    $(".btnLoadMoreProducts").prop("disabled", true);
    $(".btnLoadMoreProducts").css('cursor', 'not-allowed');
    $(".btnLoadMoreProducts").html(`${translate.loading_icon_text}`);

    var props = {
        ent_id: sale_ent_id,
        pos_id: sale_pos_id,
        productNameOrBarcode: productNameOrBarcode,
        PosProductListLimit: PosProductListLimit
    }

    const res = await getProductsListToSale(props);
    // console.log(res);

    // Get object from localStorage
    let pos_info = JSON.parse(localStorage.getItem("pos_info"));

    let productsHtml = "";
    $(".product-grid-container").html("");

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

        $(".btnNewProductOrder").prop("disabled", true);
        $(".btnNewProductOrder").html(`<i class="ph-circles-four me-2"></i> ${translate.show_products}`);
        $(".btnNewProductOrder").removeClass("btnShowNewProductOrder");
        $(".btnNewProductOrder").hide();

        // $(".btnReloadNewOrder").show();

        $(".posProductLoadingStatus").hide();
        $(".btnLoadMoreProducts").show();
        $(".product-grid-container").show();

        $(".btnLoadMoreProducts").prop("disabled", false);
        $(".btnLoadMoreProducts").css('cursor', 'pointer');
        $(".btnLoadMoreProducts").html(`<i class="ph-arrows-clockwise me-1"></i> ${translate.show_more_products}`);

        if (res.data.length > 0) {

            res.data.forEach(item => {

                let pro_price = item.pro_price;
                if (pos_info.pos_festive_mode == "On") pro_price = item.pro_price_party;
                pro_price = showCurrencyFormat(pos_info.pos_currency, pos_info.pos_country_code, pro_price);

                // let proPriceUSD = 0;
                // let proPriceUSDHtml = "";

                // if (pos_info['pos_currency'] != "USD" && pos_info['pos_usd_exchange_rate'] > 0) {
                //     proPriceUSD = Number(item.pro_price) / Number(pos_info['pos_usd_exchange_rate']);
                //     proPriceUSD = showCurrencyFormat("USD", pos_info.pos_country_code, proPriceUSD);
                //     proPriceUSDHtml = `<p class="product-card-price text-success">${proPriceUSD}</p>`;
                // }

                let pro_image = `<img src="${item.pro_image || 'assets/images/no-image.png'}" alt="Product" class="rounded-full object-cover w-[100px] h-[100px]" onerror="this.onerror=null;this.src='assets/images/no-image.png';" />`;

                let stockStatusColor = "bg-success text-success";
                if (Number(item.pro_current_stock) <= 20) stockStatusColor = "bg-warning text-warning";
                if (Number(item.pro_current_stock) <= 10) stockStatusColor = "bg-danger text-danger";

                let productNameFormated = item.pro_description.toLowerCase().replace(/\b\w/g, char => char.toUpperCase());

                productsHtml += `<div class="product-card rounded-lg cursor-pointer transition w-[140px] text-center" onclick='jsAddProductToCart(${JSON.stringify(item)});'>                
                    <div class="stock-info top-left bg-opacity-10 ${stockStatusColor}">${item.pro_current_stock}</div>
                    <div class="aspect-w-1 aspect-h-1 flex justify-center mt-2">
                        ${pro_image}
                    </div>
                    <div class="mt-2">
                        <p class="text-sm">${productNameFormated}</p>
                        <p class="text-blue-400 text-[13px] font-semibold">${pro_price}</p>
                    </div>
                </div>`;

            });

            $(".product-grid-container").html(productsHtml);

        } else {

            $(".product-grid-container").html(`<div class="text-center">${translate.no_results_found}</div>`);
        }

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

        // $(".btnReloadNewOrder").show();
        $(".product-grid-container").show();
        $(".posProductListContainer").show();
        $(".posProductLoadingStatus").show();
        $(".posProductLoadingStatus").html(`${translate.no_products_found}`);
        // $("#inputProductSearch").focus();

        $(".btnNewProductOrder").prop("disabled", false);
        $(".btnNewProductOrder").html(`<i class="ph-circles-four me-2"></i> ${translate.show_products}`);
        $(".btnNewProductOrder").addClass("btnShowNewProductOrder");

        $(".btnLoadMoreProducts").hide();
        $(".btnLoadMoreProducts").prop("disabled", false);
        $(".btnLoadMoreProducts").css('cursor', 'pointer');
        $(".btnLoadMoreProducts").html(`<i class="ph-arrows-clockwise me-1"></i> ${translate.show_more_products}`);

    } else {
        swalInit.fire(translate.data_could_not_be_loaded_please_contact_the_system_vendor_for_technical_assistance, ``, "error");

        // $(".btnReloadNewOrder").show();
        $(".posProductListContainer").show();
        $(".posProductLoadingStatus").show();
        $(".posProductLoadingStatus").html(`${translate.no_products_found}`);
        // $("#inputProductSearch").focus();

        $(".btnNewProductOrder").prop("disabled", false);
        $(".btnNewProductOrder").html(`<i class="ph-circles-four me-2"></i> ${translate.show_products}`);
        $(".btnNewProductOrder").addClass("btnShowNewProductOrder");

        $(".btnLoadMoreProducts").prop("disabled", false);
        $(".btnLoadMoreProducts").css('cursor', 'pointer');
        $(".btnLoadMoreProducts").html(`<i class="ph-arrows-clockwise me-1"></i> ${translate.show_more_products}`);
    }
}

// $(document).on("click", ".btnSearchProduct", function () {

//     var sale_ent_id = $("#sale_ent_id").val();
//     var sale_pos_id = $("#sale_pos_id").val();
//     var productNameOrBarcode = $("#inputProductSearch").val();

//     if (productNameOrBarcode == "" || $.trim(productNameOrBarcode) == "") {
//         $("#inputProductSearch").focus();
//         $("#inputProductSearch").css("border", "1px solid red");
//         fnSweetToast(translate.scan_or_type_the_product_name, "warning", 1500);
//         return false;
//     } else {
//         if (/[^a-zA-Z0-9]/.test(productNameOrBarcode)) {
//             fnSweetToast(translate.please_enter_only_alphanumeric_characters, "warning", 2500);
//             return false;
//         } else {
//             // Valid input: contains only alphanumeric characters
//             jsShowProductList(sale_ent_id, sale_pos_id, productNameOrBarcode, "");
//             $("#inputProductSearch").css("border", `1px solid ${borderColorValidated}`);
//         }
//     }
// });

$(document).on("click", ".btnLoadMoreProducts", function () {
    $("#inputProductSearch").val("");
    var sale_ent_id = $("#sale_ent_id").val();
    var sale_pos_id = $("#sale_pos_id").val();
    var getLimit = localStorage.getItem("PosProductListLimit");
    var newlimitValue = Number(getLimit) + 18;
    localStorage.setItem("PosProductListLimit", newlimitValue);
    jsShowProductList(sale_ent_id, sale_pos_id, "", newlimitValue);

});

const currentProductStock = async function (pro_id) {
    try {

        const url = `ajax/products.ajax.php?op=ajaxGetCurrentProductStockById&pro_id=${pro_id}`;
        const response = await fetch(url);

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

        const res = await response.json();

        if (res.status == "success") {
            pro_current_stock = res.data.pro_current_stock;
            return pro_current_stock;
        } else {
            return false;
        }


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

/*=============================================
ADD NEW PRODUCT ROW
=============================================*/
async function jsAddProductToCart(data = "") {

    $("#productSearch").focus();

    if (Number(transactionId) >= 1) {
        let sale_info = await getSaleData(transactionId);

        if (sale_info.sale_status === "Disabled") {
            swalInit.fire(translate.this_sale_has_been_canceled, "", "error");
            return false;
        }
    }

    // Get object from localStorage
    let pos_info = JSON.parse(localStorage.getItem("pos_info"));

    let currentStock = await currentProductStock(data.pro_id);
    if (!currentStock) return false;

    /*=================================================
    Do not allow to add more than current stock
    ==================================================*/
    if (currentStock != 'FULL' && Number(currentStock) <= 0) {
        fnSweetToast(translate.not_enough_stock_available, "error", 1500);
        return false;
    }

    let ord_det_code = $("#txt_ord_det_code").val();
    let product = document.getElementById(`product_${data.pro_id}${ord_det_code}`);

    if (product) {

        const currentQty = parseFloat(product.value) + 1;
        // const qtyTotal = currentQty + 1;

        if (Number(currentQty) > currentStock) {
            fnSweetToast(`${translate.there_are_only} ${currentStock} ${translate.units_available}`, "warning", 2500);
            // $("#inputProductSearch").focus();
            return false;
        } else {
            product.value = Number(currentQty).toFixed(2);
            fnSweetToast(translate.quantity_increased, "success", 800);
            // $("#inputProductSearch").focus();
        }

    } else {

        let pro_price = data.pro_price;
        if (pos_info.pos_festive_mode == "On") pro_price = data.pro_price_party;

        let saleDetProPrice = `<div>
            <input type="hidden" class="sale_det_pro_price" name="sale_det_pro_price[]" value="${pro_price}"/>
            ${showCurrencyFormat(pos_info.pos_currency, pos_info.pos_country_code, pro_price)}</div>`;

        if (pro_price == 0) saleDetProPrice = `<div class="col-4">
            <input type="text" class="form-control form-control-lg sale_det_pro_price" name="sale_det_pro_price[]" step="0.01" value="${pro_price}" />
            </div>`;

        let pro_image = `<img src="${data.pro_image || 'assets/images/no-image.png'}" class="w-40px h-40px rounded-pill mt-1" alt="product-image" onerror="this.onerror=null;this.src='assets/images/no-image.png';" />`;

        let productNameFormated = data.pro_description.toLowerCase().replace(/\b\w/g, char => char.toUpperCase());

        $(".products-cart-list").prepend(`
                
                <div class="product-item">

                    <input type="hidden" name="sale_det_ord_det_code[]" value="${ord_det_code}">
                    <input type="hidden" class="sale_det_pro_id" name="sale_det_pro_id[]" value="${data.pro_id}">
                    ${pro_image}
                    <div class="product-details">
                        <span class="product-cart-name mt-1">${productNameFormated}</span>
                        <div class="quantity-controls">

                            <div class="input-group productQty">
                            
                                <button type="button" class="btn btn-light btn-icon btnMinus">
                                    <i class="ph-minus ph-sm"></i>
                                </button>

                                <input type="number" min="1" step="1.00" class="form-control form-control-number text-center sale_det_pro_qty" name="sale_det_pro_qty[]" id="product_${data.pro_id}${ord_det_code}" value="1.00">
                                
                                <button type="button" class="btn btn-light btn-icon btnPlus">
                                    <i class="ph-plus ph-sm"></i>
                                </button>

                            </div>
                            
                            ${saleDetProPrice}

                        </div>
                    </div>
                </div>
            `);

        fnSweetToast(translate.product_added, "success", 800);

        // $("#inputProductSearch").focus();
    }

    showAmount();
}


// DECREASE PRODUCT QUANTITY
$(document).on("click", ".btnMinus", function () {

    let thisMinusBtn = $(this);
    let inputSaleQty = thisMinusBtn.closest('.productQty').find('.sale_det_pro_qty');
    let inputSaleQuanty = thisMinusBtn.closest('.productQty').find('.sale_det_pro_quantity');
    let currentSaleQty = Number(inputSaleQty.val());
    currentSaleQty = isNaN(currentSaleQty) ? 1 : currentSaleQty;
    currentSaleQty--;

    if (currentSaleQty <= 0) {
        thisMinusBtn.hide();
        swalInit.fire({
            title: translate.are_you_sure,
            text: translate.Confirm_that_you_want_to_remove_this_product,
            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) {
                thisMinusBtn.parent().parent().parent().parent().remove();
                showAmount();

            } else {
                inputSaleQty.val(Number(currentSaleQty + 1).toFixed(2));
                inputSaleQuanty.val(Number(currentSaleQty + 1).toFixed(2));
                thisMinusBtn.show();
                showAmount();
            }
        });
    }

    inputSaleQty.val(Number(currentSaleQty).toFixed(2));
    inputSaleQuanty.val(Number(currentSaleQty).toFixed(2));
    showAmount();
});


// DECREASE PRODUCT QUANTITY
$(document).on("click", ".btnMinusSaved", async function () {

    let thisMinusBtn = $(this);
    let inputSaleQty = thisMinusBtn.closest('.productQty').find('.sale_det_pro_qty');
    let inputSaleQuanty = thisMinusBtn.closest('.productQty').find('.sale_det_pro_quantity');
    let currentSaleQty = Number(inputSaleQty.val());
    currentSaleQty = isNaN(currentSaleQty) ? 1 : currentSaleQty;

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

        currentSaleQty--;

        if (currentSaleQty <= 0) {
            thisMinusBtn.hide();
            swalInit.fire({
                title: translate.are_you_sure,
                text: translate.Confirm_that_you_want_to_remove_this_product,
                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) {
                    thisMinusBtn.parent().parent().parent().parent().remove();
                    showAmount();

                } else {
                    inputSaleQty.val(Number(currentSaleQty + 1).toFixed(2));
                    inputSaleQuanty.val(Number(currentSaleQty + 1).toFixed(2));
                    thisMinusBtn.show();
                    showAmount();
                }
            });
        }

        inputSaleQty.val(Number(currentSaleQty).toFixed(2));
        inputSaleQuanty.val(Number(currentSaleQty).toFixed(2));
        showAmount();
    } else {

        let entInfo = await jsGetEnterpriseData();

        swalInit.fire({
            title: translate.cancellation_code,
            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

                // GENERATE A NEW CANCEL PASSWORD
                $.post("ajax/enterprises.ajax.php?op=ajaxGenerateNewCancelPassword", { entId: sess_ent_id, csrf_token: csrf_token }, function (response) { });

                currentSaleQty--;

                if (currentSaleQty <= 0) {
                    thisMinusBtn.hide();
                    swalInit.fire({
                        title: translate.are_you_sure,
                        text: translate.Confirm_that_you_want_to_remove_this_product,
                        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) {
                            thisMinusBtn.parent().parent().parent().parent().remove();
                            showAmount();

                        } else {
                            inputSaleQty.val(Number(currentSaleQty + 1).toFixed(2));
                            inputSaleQuanty.val(Number(currentSaleQty + 1).toFixed(2));
                            thisMinusBtn.show();
                            showAmount();
                        }
                    });
                }

                inputSaleQty.val(Number(currentSaleQty).toFixed(2));
                inputSaleQuanty.val(Number(currentSaleQty).toFixed(2));
                showAmount();

            } else if (result.dismiss === swalInit.DismissReason.cancel) {
            }
        });
    }
});


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


// CHANGE PRODUCT QUANTITY
$(document).on("change", ".sale_det_pro_qty", async function () {

    let thisInputQty = $(this);
    let proId = thisInputQty.closest('.product-item').find('.sale_det_pro_id').val();
    let currentStock = await currentProductStock(proId);
    let inputSaleQty = thisInputQty.closest('.productQty').find('.sale_det_pro_qty');
    let inputSaleQuanty = thisInputQty.closest('.productQty').find('.sale_det_pro_quantity');
    let currentSaleQty = Number(thisInputQty.val());

    currentSaleQty = isNaN(currentSaleQty) ? 1 : currentSaleQty;

    if (currentStock != 'FULL' && currentSaleQty > Number(currentStock)) {

        inputSaleQty.val(Number(currentStock).toFixed(2));
        inputSaleQuanty.val(Number(currentStock).toFixed(2));

        fnSweetToast(`${translate.there_are_only} ${currentStock} ${translate.units_available}`, "warning", 2500);
        showAmount();
        return;
    }

    if (currentSaleQty <= 0) {
        swalInit.fire({
            title: translate.are_you_sure,
            text: translate.Confirm_that_you_want_to_remove_this_product,
            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) {
                thisInputQty.parent().parent().parent().parent().remove();
                showAmount();

            } else {
                inputSaleQty.val(Number(currentSaleQty + 1).toFixed(2));
                inputSaleQuanty.val(Number(currentSaleQty + 1).toFixed(2));
                thisInputQty.show();
                showAmount();
            }
        });
    }

    showAmount();
});


// INCREASE PRODUCT QUANTITY
$(document).on("click", ".btnPlus", async function () {

    let thisPlusBtn = $(this);
    let proId = thisPlusBtn.closest('.product-item').find('.sale_det_pro_id').val();
    let currentStock = await currentProductStock(proId);
    let inputSaleQty = thisPlusBtn.closest('.productQty').find('.sale_det_pro_qty');
    let inputSaleQuanty = thisPlusBtn.closest('.productQty').find('.sale_det_pro_quantity');
    let currentSaleQty = Number(inputSaleQty.val());

    currentSaleQty = isNaN(currentSaleQty) ? 1 : currentSaleQty;
    currentSaleQty++;

    if (currentSaleQty >= 1) thisPlusBtn.closest('.productQty').find('.btnMinus').show();

    if (currentStock != 'FULL' && currentSaleQty > Number(currentStock)) {
        /*=================================================================
        SI LA CANTIDAD ES SUPERIOR AL STOCK REGRESAR VALORES INICIALES
        =================================================================*/
        inputSaleQty.val(Number(currentStock).toFixed(2));
        inputSaleQuanty.val(Number(currentStock).toFixed(2));

        fnSweetToast(`${translate.there_are_only} ${currentStock} ${translate.units_available}`, "warning", 2500);
        showAmount();
        return;
    }

    inputSaleQty.val(Number(currentSaleQty).toFixed(2));
    inputSaleQuanty.val(Number(currentSaleQty).toFixed(2));
    showAmount();
});


async function showAmount() {

    // Get object from localStorage
    let pos_info = JSON.parse(localStorage.getItem("pos_info"));

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

    let sale_det_pro_qty = document.getElementsByName("sale_det_pro_qty[]");
    let sale_det_pro_price = document.getElementsByName("sale_det_pro_price[]");

    let totalQuantity = 0;
    let subTotalSale = 0;
    let subTotalSaleFinal = 0;
    let saleTaxValue = 0;
    let saleLegalTippingValue = 0;
    let subTotalSaleTax = 0;
    let saleTotalFinal = 0;

    let arrSumSubTotalSale = [];
    let arrSumTotalQuantity = [];

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

        let pro_quantity = sale_det_pro_qty[i];
        let pro_price = sale_det_pro_price[i];

        arrSumTotalQuantity.push(Number(pro_quantity.value));
        arrSumSubTotalSale.push(Number(pro_quantity.value) * Number(pro_price.value));
    }

    totalQuantity = arrSumTotalQuantity.reduce((previousValue, currentValue) => previousValue + currentValue, 0);
    subTotalSale = arrSumSubTotalSale.reduce((previousValue, currentValue) => previousValue + currentValue, 0);

    $("#orderSumQty").val(totalQuantity);

    //GET TOTAL PAID
    let currentTotalPaid = $(".currentTotalPaid");
    let currentTotalIncome = $(".currentTotalIncome");
    let currentPayDetChange = $(".currentPayDetChange");

    let arraySumaTotalPaid = [];
    let arraySumaTotalIncome = [];
    let arraySumaPayDetChange = [];

    for (var i = 0; i < currentTotalPaid.length; i++) {
        arraySumaTotalPaid.push(Number($(currentTotalPaid[i]).val()));
        arraySumaTotalIncome.push(Number($(currentTotalIncome[i]).val()));
        arraySumaPayDetChange.push(Number($(currentPayDetChange[i]).val()));
    }

    let totalPaid = arraySumaTotalPaid.reduce((previousValue, currentValue) => previousValue + currentValue, 0);
    let totalIncome = arraySumaTotalIncome.reduce((previousValue, currentValue) => previousValue + currentValue, 0);
    let totalPayDetChange = arraySumaPayDetChange.reduce((previousValue, currentValue) => previousValue + currentValue, 0);

    let txtCurrentDebtChange = $("#txtCurrentDebtChange");
    txtCurrentDebtChange.val(Number(txtCurrentDebtChange.val()) > 0 ? txtCurrentDebtChange.val() : totalPayDetChange);

    //CALCULATE DISCOUNT
    let prevDiscountPercent = $("#prevDiscountPercent").val() ?? 0;
    let prevDiscountValue = $("#prevDiscountValue").val() ?? 0;
    let prevCurrentDebt = $("#prevCurrentDebt").val() ?? 0;

    let percentageValue = 0;
    let discountValue = 0;
    let discountFormat = $("#discountFormat").val();
    let discountPercentOrAmount = $("#sale_discount_enter_percent_value").val();

    if (Number(discountPercentOrAmount) > 0) {

        if (discountFormat == "Percentage") {

            percentageValue = discountPercentOrAmount;

            if (Number(percentageValue) > 100) {
                swalInit.fire(translate.the_amount_or_percentage_of_the_discount_cannot_exceed_100.toUpperCase(), "", 'error').then(function (result) {
                    $("#sale_discount_enter_percent_value").focus();
                    return false;
                });
            }

            if (Number(percentageValue) == 100) {
                if (sess_user_profile !== "ROOT" || sess_user_profile !== "Owner") {
                    swalInit.fire(translate.the_amount_or_percentage_of_the_discount_cannot_exceed_100.toUpperCase(), "", 'error').then(function (result) {
                        $("#sale_discount_enter_percent_value").focus();
                        return false;
                    });
                }
            }

            if (Number(percentageValue) == 100 && Number(totalIncome) > 0) {
                swalInit.fire(translate.a_100_discount_cannot_be_applied_to_this_sale_because_payments_have_already_been_made.toUpperCase(), "", 'error').then(function (result) {
                    $("#sale_discount_enter_percent_value").focus();
                    return false;
                });

            } else {

                discountValue = roundedDecimal((subTotalSale * percentageValue) / 100, 2);

                if (Number(prevCurrentDebt) > 0) {

                    if (Number(discountValue) > Number(prevCurrentDebt) && Number(totalIncome) > 0 && Number(prevDiscountValue) <= 0) {
                        swalInit.fire(translate.the_discount_cannot_be_greater_than_the_debt_of_the_sale, `${translate.this_sale_only_has_a_debt_of}: ${showCurrencyFormat(pos_info.pos_currency, pos_info.pos_country_code, prevCurrentDebt)}`, `warning`).then(function (result) {
                            $("#sale_discount_enter_percent_value").focus();
                            percentageValue = prevDiscountPercent;
                            discountValue = prevDiscountValue;
                            return false;
                        });
                    }
                }
            }

        } else {

            discountValue = discountPercentOrAmount;

            if (Number(discountValue) > Number(subTotalSale)) {
                swalInit.fire(translate.the_amount_or_percentage_of_the_discount_cannot_exceed_100.toUpperCase(), "", 'error').then(function (result) {
                    $("#sale_discount_enter_percent_value").focus();
                    percentageValue = prevDiscountPercent;
                    discountValue = prevDiscountValue;
                    return false;
                });
            }

            if (Number(discountValue) == Number(subTotalSale) && Number(totalIncome) > 0) {
                swalInit.fire(translate.a_100_discount_cannot_be_applied_to_this_sale_because_payments_have_already_been_made, "error", 4000).then(function (result) {
                    $("#sale_discount_enter_percent_value").focus();
                    percentageValue = prevDiscountPercent;
                    discountValue = prevDiscountValue;
                    return false;
                });

            } else {

                if (Number(prevCurrentDebt) > 0) {

                    if (Number(discountValue) > Number(prevCurrentDebt) && Number(totalIncome) > 0) {
                        swalInit.fire(translate.the_discount_cannot_be_greater_than_the_debt_of_the_sale, `${translate.this_sale_only_has_a_debt_of}: ${showCurrencyFormat(pos_info.pos_currency, pos_info.pos_country_code, prevCurrentDebt)}`, `warning`).then(function (result) {
                            $("#sale_discount_enter_percent_value").focus();
                            percentageValue = prevDiscountPercent;
                            discountValue = prevDiscountValue;
                            return false;
                        });
                    }
                }

                percentageValue = roundedDecimal((discountValue / subTotalSale) * 100, 2);
            }
        }

    } else if (Number(discountPercentOrAmount) == 0) {

        percentageValue = prevDiscountPercent;
        discountValue = prevDiscountValue;
    } else {

        swalInit.fire(translate.error_the_percentage_of_the_discount_cannot_be_less_than_0.toUpperCase(), "", 'error').then(function (result) {
            $("#sale_discount_enter_percent_value").focus();
            percentageValue = prevDiscountPercent;
            discountValue = prevDiscountValue;
            return false;
        });
    }

    $("#sale_discount_percent").val(percentageValue);
    $("#sale_discount_value").val(discountValue);
    $('.spanDiscountPercent').text(`(-${percentageValue}%)`);
    $('.saleDiscount').text(showCurrencyFormat(pos_info.pos_currency, pos_info.pos_country_code, discountValue));

    discountValue = $("#sale_discount_value").val();

    subTotalSaleFinal = Number(subTotalSale) - Number(discountValue);
    $('.saleSubTotalFinal').text(showCurrencyFormat(pos_info.pos_currency, pos_info.pos_country_code, subTotalSaleFinal));

    let saleCostDelivery = roundedDecimal($('#sale_cost_delivery').val(), 2);

    let sale_tax_percent = $("#sale_tax_percent").val();
    let sale_tax_law_percent = $("#sale_tax_law_percent").val();

    // Get object from localStorage
    if (Number(transactionId) >= 1) {
        let sale_info = JSON.parse(localStorage.getItem("sale_info"));
        sale_tax_percent = sale_info.sale_tax_percent;
        sale_tax_law_percent = sale_info.sale_tax_law_percent;
    }

    if (Number(sale_tax_percent) > 0) saleTaxValue = parseFloat((sale_tax_percent / 100) * subTotalSaleFinal, 2);
    if (Number(sale_tax_law_percent) > 0) saleLegalTippingValue = parseFloat((sale_tax_law_percent / 100) * subTotalSaleFinal, 2);

    subTotalSaleTax = Number(subTotalSaleFinal) + Number(saleTaxValue) + Number(saleLegalTippingValue);

    saleTotalFinal = roundedDecimal(subTotalSaleTax + saleCostDelivery, 2);

    $('.saleSubTotal').text(showCurrencyFormat(pos_info.pos_currency, pos_info.pos_country_code, subTotalSale));
    $('.spanTaxValue').text(showCurrencyFormat(pos_info.pos_currency, pos_info.pos_country_code, saleTaxValue));
    $('.spanLegalTippingValue').text(showCurrencyFormat(pos_info.pos_currency, pos_info.pos_country_code, saleLegalTippingValue));
    $('.saleTotalFinal').text(showCurrencyFormat(pos_info.pos_currency, pos_info.pos_country_code, saleTotalFinal));
    $('.saleCostDelivery').text(showCurrencyFormat(pos_info.pos_currency, pos_info.pos_country_code, saleCostDelivery));

    //SHOW THE TOTAL PAID TO THE USER
    $("#spanModalTotalPaid").text(showCurrencyFormat(pos_info.pos_currency, pos_info.pos_country_code, totalPaid));
    $("#spanModalTotalIncome").text(showCurrencyFormat(pos_info.pos_currency, pos_info.pos_country_code, totalIncome));

    $("#sale_sub_total").val(subTotalSale);
    $("#sale_tax_value").val(saleTaxValue);
    $("#sale_tax_law_value").val(saleLegalTippingValue);
    $("#sale_amount_final").val(saleTotalFinal);
    // $("#sale_debt").val(saleTotalFinal);

    $('#orderAmount').text(showCurrencyFormat(pos_info.pos_currency, pos_info.pos_country_code, saleTotalFinal));

    //MODAL PAYMENT
    $("#span_modal_final_total").text(showCurrencyFormat(pos_info.pos_currency, pos_info.pos_country_code, saleTotalFinal));

    //GET DEBT OR CHANGE
    var valDebtChange = roundedDecimal(saleTotalFinal - totalIncome, 2);

    //SHOW DEBT OR CHANGE FOR THE USER
    if (valDebtChange > 0) {

        $("#sale_debt").val(valDebtChange);
        $(".thDebtChangeRow").removeClass("bg-warning").addClass("bg-danger");
        $("#spanDebtChangeText").text(translate.debt);
        $("#spanDebtChangeValue").text(showCurrencyFormat(pos_info.pos_currency, pos_info.pos_country_code, valDebtChange));
        $("#inp_paid_value").val("");
        $("#inp_paid_value").prop("disabled", false);
        $("#inp_paid_value").css('cursor', 'pointer');
        $("#inp_paid_value").focus();
        $(".divGroupAddPayment").show();

    } else {

        let totalPayDetChange = $("#txtCurrentDebtChange").val();

        $("#sale_debt").val(0.00);
        $(".thDebtChangeRow").removeClass("bg-danger").addClass("bg-warning");
        $("#spanDebtChangeText").text(translate.change);
        $("#spanDebtChangeValue").text(showCurrencyFormat(pos_info.pos_currency, pos_info.pos_country_code, totalPayDetChange));
        $("#inp_paid_value").val(0.00);
        $("#inp_paid_value").prop("disabled", true);
        $("#inp_paid_value").css('cursor', 'not-allowed');
        $(".divGroupAddPayment").hide();
    }

    jsRemoveOptionsIfUserNotBelongToTheSaleEnterprise();
}


/*=============================================
SHOW SALES INFORMATIONS
=============================================*/
async function jsShowSaleInfo() {

    document.getElementById("frmSubmitOrder").reset();

    // Get object from localStorage
    let sale_info = JSON.parse(localStorage.getItem("sale_info"));

    $("#sale_id").val(sale_info.sale_id);
    $("#sale_ent_id").val(sale_info.sale_ent_id);

    let posResult = await selectBranchToSell(sale_info.sale_ent_id, sale_info.sale_pos_id);

    if (posResult) {

        // $("#sale_type").val(sale_info.sale_type).trigger('change');
        js_SelectSaleType(sale_info.sale_pos_id, sale_info.sale_type);
        fnSelectCustomersList(sale_info.sale_ent_id, sale_info.sale_cus_id);
        js_selectListFiscalReceipt(sale_info.sale_ent_id, sale_info.sale_ncf_type);
        js_selectListTable(sale_info.sale_table_id);

        $("#sale_id").val(sale_info.sale_id);
        $("#sale_ent_id").val(sale_info.sale_ent_id);
        $("#sale_sub_total").val(sale_info.sale_sub_total);
        $("#sale_tax_percent").val(sale_info.sale_tax_percent);
        $("#sale_tax_value").val(sale_info.sale_tax_value);
        $("#sale_tax_law_percent").val(sale_info.sale_tax_law_percent);
        $("#sale_tax_law_value").val(sale_info.sale_tax_law_value);
        $("#sale_discount_percent").val(sale_info.sale_discount_percent);
        $("#sale_discount_value").val(sale_info.sale_discount_value);
        $("#sale_debt").val(sale_info.sale_debt);
        $("#sale_cost_delivery").val(sale_info.sale_cost_delivery);
        $("#sale_amount_final").val(sale_info.sale_amount_final);
        $("#prevDiscountPercent").val(sale_info.sale_discount_percent);
        $("#prevDiscountValue").val(sale_info.sale_discount_value);
        $("#prevCurrentDebt").val(sale_info.sale_debt);
        sale_info.sale_tax_percent
        $("#discountFormat").val("Amount");
        $("#sale_discount_enter_percent_value").val(sale_info.sale_discount_value);

        $(".spanDiscountPercent").text(`(-${sale_info.sale_discount_percent}%)`);
        $('.saleDiscount').text(`${sale_info.sale_discount_value}`);
        $(".spanTaxPercent").text(`(${sale_info.sale_tax_percent}%)`);
        $(".spanLawPercent").text(`(${sale_info.sale_tax_law_percent}%)`);
        $(".saleCostDelivery").text(sale_info.sale_cost_delivery);

        $("#sale_status").val(sale_info.sale_status);

        js_showSaleDetails(sale_info.sale_id);
        js_showDetailsPayments(sale_info.sale_id);
    }

}


/*=============================================
SHOW SALES PRODUCTS DETAILS
=============================================*/
async function js_showSaleDetails(sale_id) {

    try {

        const url = `ajax/sales.ajax.php?op=ajax_showSaleDetails&sale_id=${sale_id}`;
        const response = await fetch(url);

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

        const res = await response.json();
        const parsedData = JSON.parse(res.data);

        let productsHtml = "";
        $(".products-cart-list").html("");

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

            let pos_info = JSON.parse(localStorage.getItem("pos_info"));

            if (Number(res.hasPayment) >= 1) {

                parsedData.forEach(item => {

                    let pro_image = `<img src="${item.pro_image || 'assets/images/no-image.png'}" class="w-40px h-40px rounded-pill" alt="product-image" onerror="this.onerror=null;this.src='assets/images/no-image.png';" />`;

                    let productNameFormated = item.pro_description.toLowerCase().replace(/\b\w/g, char => char.toUpperCase());

                    productsHtml += `
                    <div class="product-item">
                        <input type="hidden" name="sale_det_ord_det_code[]" value="${item.sale_det_ord_det_code}">
                        <input type="hidden" class="sale_det_pro_id" name="sale_det_pro_id[]" value="${item.pro_id}">
                        <input type="hidden" name="sale_det_pro_price[]" class="sale_det_pro_price" value="${item.sale_det_pro_price}" />
                        ${pro_image}
                        <div class="product-details">
                            <span class="product-cart-name">${productNameFormated}</span>
                            <div class="quantity-controls">
                                <div class="input-group productQty">
                                    <span class="">${item.sale_det_pro_qty} x ${showCurrencyFormat(pos_info.pos_currency, pos_info.pos_country_code, item.sale_det_pro_price)}</span>
                                    <input type="hidden" class="sale_det_pro_qty" stock="${item.stock_actual}" name="sale_det_pro_qty[]" id="product_${item.pro_id}${item.sale_det_ord_det_code}" value="${item.sale_det_pro_qty}">
                                </div>
                            </div>
                        </div>
                    </div>`
                });

                $(".products-cart-list").prepend(productsHtml);
            } else {
                parsedData.forEach(item => {

                    let pro_image = `<img src="${item.pro_image || 'assets/images/no-image.png'}" class="w-40px h-40px rounded-pill mt-1" alt="product-image" onerror="this.onerror=null;this.src='assets/images/no-image.png';" />`;

                    let productNameFormated = item.pro_description.toLowerCase().replace(/\b\w/g, char => char.toUpperCase());

                    productsHtml += `
                    <div class="product-item">
                        <input type="hidden" name="sale_det_ord_det_code[]" value="${item.sale_det_ord_det_code}">
                        <input type="hidden" class="sale_det_pro_id" name="sale_det_pro_id[]" value="${item.pro_id}">
                        <input type="hidden" name="sale_det_pro_price[]" class="sale_det_pro_price" value="${item.sale_det_pro_price}" />
                        ${pro_image}
                        <div class="product-details">
                            <span class="product-cart-name mt-1">${productNameFormated}</span>
                            <div class="quantity-controls">
                                <div class="input-group productQty">                                
                                    <button type="button" class="btn btn-light btn-icon btnMinusSaved warning-on-hover">
                                        <i class="ph-minus ph-sm"></i>
                                    </button>
                                    <input type="hidden" readonly min="1" step="1.00" class="form-control form-control-number text-center sale_det_pro_qty" name="sale_det_pro_qty[]" id="product_${item.pro_id}${item.sale_det_ord_det_code}" value="${item.sale_det_pro_qty}">
                                    <input type="number" readonly class="form-control form-control-number text-center sale_det_pro_quantity" value="${item.sale_det_pro_qty}">
                                    <button type="button" class="btn btn-light btn-icon btnPlus">
                                        <i class="ph-plus ph-sm"></i>
                                    </button>
                                </div>
                                <div>${showCurrencyFormat(pos_info.pos_currency, pos_info.pos_country_code, item.sale_det_pro_price)}</div>
                            </div>
                        </div>
                    </div>`
                });

                $(".products-cart-list").prepend(productsHtml);
            }

            showAmount();
        }

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

async function js_showDetailsPayments(sale_id) {
    try {

        const url = `ajax/payments.ajax.php?op=ajax_showPaymentsDetails&sale_id=${sale_id}`;
        const response = await fetch(url);

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

        const res = await response.json();

        let paymentsHtml = "";

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

            let pos_info = JSON.parse(localStorage.getItem("pos_info"));

            res.data.forEach(item => {

                let cashBackRowStatus = "Yes";
                if (item.pay_det_payment_type == 'CASHBACK') cashBackRowStatus = "No";

                let cashierName = item.cashier_full_name ? formatName(item.cashier_full_name) : "--";

                paymentsHtml += `<tr class="text-center">
                    <td class="dataRow">
                    <span>${cashierName}</span>
                    <input type="hidden" name="pay_det_date[]" readonly value="${item.pay_det_date}">
                    <input type="hidden" name="pay_det_payment_type[]" readonly value="${item.pay_det_payment_type}">
                    <input type="hidden" class="currentTotalPaid " name="pay_det_value[]" value="${item.pay_det_value}">
                    <input type="hidden" class="currentTotalIncome" name="pay_det_income[]" readonly value="${item.pay_det_income}">
                    <input type="hidden" name="pay_det_created_by[]" value="${item.pay_det_created_by}">
                    <input type="hidden" name="pay_det_note[]" value="${item.pay_det_note}">
                    <input type="hidden" name="pay_det_previous_debt[]" value="${item.pay_det_previous_debt}">
                    <input type="hidden" class="currentPayDetChange" name="pay_det_change[]" value="${item.pay_det_change}"></input>
                    <input type="hidden" class="currentPayDetCashBack" cashbackatt="${cashBackRowStatus}" name="pay_det_cashback[]" value="${item.pay_det_cashback}">
                    <input type="hidden" name="pay_det_cashback_status[]" value="${item.pay_det_cashback_status}">
                    </td>
                    <td><span>${item.pay_det_date_formatted}</span></td>
                    <td><span>${item.pay_det_payment_type}</span></td>
                    <td><span>${showCurrencyFormat(pos_info.pos_currency, pos_info.pos_country_code, item.pay_det_value)}</span></td>
                    <td><span>${showCurrencyFormat(pos_info.pos_currency, pos_info.pos_country_code, item.pay_det_income)}</span></td>
                    <td><span>${showCurrencyFormat(pos_info.pos_currency, pos_info.pos_country_code, item.pay_det_change)}</span ></td >
                    <td><span>${item.pay_det_note}</span></td>
                    </tr>`
            });

            $(".payment_entry_details").prepend(paymentsHtml);

            showAmount();
        }

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


function jsRemoveOptionsIfUserNotBelongToTheSaleEnterprise() {

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

    if (Number(sess_ent_id) !== Number(sale_ent_id)) {

        // $(".btnReloadNewOrder").show();
        $(".btnShowNewProductOrder").remove();
        $(".btnSaveOrder").remove();
        $(".btnDiscount").remove();
        $(".divGroupAddPayment").hide();
        $(".divAddPayment").remove();
        $(".btnConfirmPayment").remove();
    }

}

async function validateToSaveOrder(option = "") {

    if (Number(transactionId) >= 1) {
        let sale_info = await getSaleData(transactionId);

        if (sale_info.sale_status === "Disabled") {
            swalInit.fire(translate.this_sale_has_been_canceled, "", "error");
            return false;
        }
    }

    let sale_pos_id = $("#sale_pos_id");
    let sale_cus_id = $("#sale_cus_id");
    let sale_type = $("#sale_type");
    let sale_table_id = $("#sale_table_id");
    let saleCostDelivery = $("#sale_cost_delivery");
    let orderSumQty = $("#orderSumQty");

    if (sale_pos_id.val().trim() === "") {
        sale_pos_id.next(".select2").css("border", "1px solid red");
        swalInit.fire(translate.please_select_a_branch, "", "warning");
        return false;
    } else {
        sale_pos_id.next(".select2").css("border", "none");
    }

    if (sale_cus_id.val().trim() === "") {
        sale_cus_id.next(".select2").css("border", "1px solid red");
        swalInit.fire(translate.select_a_customer, "", "warning");
        return false;
    } else {
        sale_cus_id.next(".select2").css("border", "none");
    }

    if (sale_type.val().trim() == "Local") {

        if ($.trim(sale_table_id.val().trim()) === '' || sale_table_id.val().trim() === null || sale_table_id.val().trim() <= 0) {
            swalInit.fire(translate.select_a_table, "warning", 1000);
            return false;
        }
    }

    if (saleCostDelivery.val().trim() == "" || saleCostDelivery.val().trim() < 0) {
        $("#sale_cost_delivery").val(0);
    }

    if (Number(orderSumQty.val().trim()) <= 0) {
        swalInit.fire(translate.no_products_have_been_added, translate.please_add_a_product_to_continue, "error");
        return false;
    }
}

$(document).on("click", ".btnSaveOrder", async function () {

    // Await the result of validateToSaveOrder before continuing
    if (await validateToSaveOrder("save") === false) return false;

    fnSaveUpdate();

});


$(document).on("click", ".btnDiscount", async function () {

    // Await the result of validateToSaveOrder before continuing
    if (await validateToSaveOrder("discount") === false) return false;

    $(".btnDiscPercent").removeClass("btn-warning").addClass("btn-light");
    $(".btnDiscAmount").removeClass("btn-light").addClass("btn-warning");
    $("#sale_discount_enter_percent_value").focus();
    $("#discountFormat").val("Amount");

    var currentDebt = $("#sale_debt").val();

    let entInfo = await jsGetEnterpriseData();

    //GET TOTAL PAID
    let currentTotalPaid = $(".currentTotalPaid");
    let arraySumaTotalPaid = [];
    for (var i = 0; i < currentTotalPaid.length; i++) {
        arraySumaTotalPaid.push(Number($(currentTotalPaid[i]).val()));
    }
    // Providing an initial value of 0 if totalPaid is empty
    var totalPaid = arraySumaTotalPaid.reduce((previousValue, currentValue) => previousValue + currentValue, 0);

    if (Number(currentDebt) <= 0 && Number(totalPaid) > 0) {
        swalInit.fire(translate.no_discount_can_be_applied, translate.payment_for_this_sale_has_been_completed, `warning`);
        return false;
    }

    if (sess_user_profile == "ROOT" || sess_user_profile == "Owner") {
        $("#myModalDiscount").modal("show");
        $("#sale_discount_enter_percent_value").val("");
        $("#sale_discount_enter_percent_value").focus();
    } else {

        swalInit.fire({
            title: translate.discount_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_discount_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
                $("#myModalDiscount").modal("show");
                $("#sale_discount_enter_percent_value").val("");
                $("#sale_discount_enter_percent_value").focus();

                // GENERATE A NEW DISCOUNT PASSWORD
                $.post("ajax/enterprises.ajax.php?op=ajaxGenerateNewDiscountPassword", { entId: entInfo.ent_id, csrf_token: csrf_token }, function (response) { });

            } else if (result.dismiss === swalInit.DismissReason.cancel) {
                // $("#expense-modal").modal("show");
            }
        });
    }
});


$(document).on("click", ".btnDiscAmount", function () {
    $(".btnDiscPercent").removeClass("btn-warning").addClass("btn-light");
    $(this).removeClass("btn-light").addClass("btn-warning");
    $("#sale_discount_enter_percent_value").focus();
    $("#discountFormat").val("Amount");
});


$(document).on("click", ".btnDiscPercent", function () {
    $(".btnDiscAmount").removeClass("btn-warning").addClass("btn-light");
    $(this).removeClass("btn-light").addClass("btn-warning");
    $("#sale_discount_enter_percent_value").focus();
    $("#discountFormat").val("Percentage");
});

// ON KEYDOWN TO CONFIRM INPUT PERCENT DISCOUNT
$("#sale_discount_enter_percent_value").keydown(function (e) {
    if (e.which === 13) {
        showAmount();
        $("#myModalDiscount").modal("hide");
    }
});

$(document).on("click", ".btnConfirmDiscount", function () {
    showAmount();
    $("#myModalDiscount").modal("hide");
});

$(document).on("click", ".btnShowPayment", async function () {

    if (await validateToSaveOrder("show_payment") === false) return false;

    $("#myModalPayment").modal("show");
    $("#inp_paid_value").focus();
    showAmount();

});

function paiment_validation() {

    // var cbo_payment_type = $(".cbo_payment_type").val();
    // var pay_det_confirmation_number = $("#pay_det_confirmation_number").val();
    // var nameOnCard = $("#nameOnCard").val();

    // if (cbo_payment_type == "CREDIT CARD" || cbo_payment_type == "BANK DEPOSIT" || cbo_payment_type == "MONCASH" || cbo_payment_type == "ZELLE" || cbo_payment_type == "CASH APP" && $.trim(pay_det_confirmation_number) === '') {
    //     fnSweetToast(translate.please_enter_the_payment_confirmation_number, "error")
    //     $("#pay_det_confirmation_number").css("border", "1px solid red");
    //     $("#pay_det_confirmation_number").focus();
    //     return false;
    // } else {
    //     $("#pay_det_confirmation_number").css("border", `1px solid ${borderColorValidated}`);
    // }

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

    if (inp_paid_value === '' || inp_paid_value <= 0) {
        fnSweetToast(translate.enter_the_amount_to_pay, "error")
        $("#inp_paid_value").css("border", "1px solid red");
        $("#inp_paid_value").focus();
        return false;
    } else {
        $("#inp_paid_value").css("border", `1px solid ${borderColorValidated}`);
    }

}


$("#inp_paid_value").keydown(async function (e) {
    if (e.which === 13) {
        e.preventDefault(); // Prevent the form from submitting
        if (await validateToSaveOrder("add_payment") === false || paiment_validation() == false) return false;

        js_addPaymentData();
    }
});


$("#pay_det_note").keydown(async function (e) {
    if (e.which === 13) {
        e.preventDefault(); // Prevent the form from submitting
        if (await validateToSaveOrder("add_payment") === false || paiment_validation() == false) return false;

        js_addPaymentData();
    }
});

/*=============================================
PAYMENT BUTTON FUNCTION TO ADD NEW PAYMENT ROW
=============================================*/
$(document).on("click", ".btnAddPayment", async function () {

    if (await validateToSaveOrder("add_payment") === false || paiment_validation() == false) return false;

    js_addPaymentData();
})

async function js_addPaymentData() {

    if (Number(transactionId) >= 1) {
        let sale_info = await getSaleData(transactionId);

        if (sale_info.sale_status === "Disabled") {
            swalInit.fire(translate.this_sale_has_been_canceled, translate.cannot_add_more_payments, "error");
            return false;
        }
    }

    // Get object from localStorage
    let pos_info = JSON.parse(localStorage.getItem("pos_info"));

    $.get("ajax/sales.ajax.php?op=ajaxCurrentDateTime", function (response, status) {
        $("#txtCurrentDateTime").val(response);
    });

    let CurrentDateTime = $("#txtCurrentDateTime").val();

    let payment_type = $("#cbo_payment_type").val();
    let currentPaid = roundedDecimal($("#inp_paid_value").val(), 2);
    let pay_det_note = $("#pay_det_note").val();

    let pay_det_income = 0;
    let newTotalToPaid = 0;
    let pay_det_change = 0;
    let pay_det_previous_debt = $("#sale_debt").val();

    //GET TAXE PERCENT TO CALCULATE VAL TO PAID
    let totalToPaid = roundedDecimal($("#sale_amount_final").val(), 2);

    //GET TOTAL PAID
    let currentTotalIncome = $(".currentTotalIncome");
    let arraySumaQuantity = [];
    for (var i = 0; i < currentTotalIncome.length; i++) {
        arraySumaQuantity.push(Number($(currentTotalIncome[i]).val()));
    }

    // Providing an initial value of 0 if totalPaid is empty
    let previousPaid = roundedDecimal(arraySumaQuantity.reduce((previousValue, currentValue) => previousValue + currentValue, 0), 2);

    // console.log("totalToPaid: " + totalToPaid);
    // console.log("previousPaid: " + previousPaid);
    // console.log("currentPaid: " + currentPaid);

    newTotalToPaid = roundedDecimal(totalToPaid - previousPaid, 2);
    pay_det_income = roundedDecimal(currentPaid - newTotalToPaid, 2);

    if (pay_det_income >= 0) {
        pay_det_income = newTotalToPaid;
    } else {
        pay_det_income = currentPaid;
    }

    pay_det_change = roundedDecimal(currentPaid - pay_det_income, 2);

    // START CALCULATE NEW CASHBACK
    let totalCashBack = $("#totalCashBack").val();
    let currentCashBack = 0;
    let pos_cash_back_percentage = $("#pos_cash_back_percentage").val();
    let totalCustomerCashBack = $("#customerCashBack").val();
    let cashBackRowStatus = "Yes";
    let pay_det_cashback_status = "Pending";

    if (payment_type == "CASHBACK") {

        if (Number(totalCustomerCashBack) <= 0) {
            fnSweetToast(`${translate.you_do_not_have_available_cashback}`, "error", 2500);
            return;
        } else if (Number(totalCustomerCashBack) < Number(currentPaid)) {
            fnSweetToast(`${translate.you_do_not_have_enough_cashback_you_just_have}: ${totalCustomerCashBack} ${translate.available_cash_back}`, "info", 4500);
            return;
        }

        pay_det_change = 0;
        cashBackRowStatus = "No";
        pay_det_cashback_status = "Used";
        currentCashBack = pay_det_income;
        currentPaid = pay_det_income;

        let leftCashBack = roundedDecimal(Number(totalCustomerCashBack) - Number(pay_det_income), 2);
        $("#customerCashBack").val(leftCashBack);
        $("#span_available_cash_back").text(showCurrencyFormat(pos_info.pos_currency, pos_info.pos_country_code, leftCashBack));

    } else {

        currentCashBack = roundedDecimal((pay_det_income * pos_cash_back_percentage) / 100, 2);
        totalCashBack = roundedDecimal(Number(totalCashBack) + Number(currentCashBack), 2);
        $("#totalCashBack").val(roundedDecimal(totalCashBack, 2));
        $("#span_modal_new_cash_back").text(showCurrencyFormat(pos_info.pos_currency, pos_info.pos_country_code, totalCashBack));
    }

    $("#txtCurrentDebtChange").val(pay_det_change);
    // console.log(`totalCashBack = ${totalCashBack}`)
    // console.log(`leftCashBack = ${leftCashBack}`)
    // console.log(`pay_det_change = ${pay_det_change}`)
    // console.log(`currentCashBack = ${currentCashBack}`)

    $(".payment_entry_details tbody").prepend(`
        <tr class="text-center">
        <td class="dataRow">
        <button type="button" class="btn btn-sm btn-icon rounded-pill btn-danger removeRow_payment"><i class="mi-close" style="text-align: center;"></i></button>
        <input type="hidden" name="pay_det_date[]" readonly value="${CurrentDateTime}">
        <input type="hidden" name="pay_det_payment_type[]" readonly value="${payment_type}">
        <input type="hidden" class="currentTotalPaid " name="pay_det_value[]" value="${currentPaid}">
        <input type="hidden" class="currentTotalIncome" name="pay_det_income[]" readonly value="${pay_det_income}">
        <input type="hidden" name="pay_det_created_by[]" value="${sess_user_id}">
        <input type="hidden" name="pay_det_note[]" readonly value="${pay_det_note}">
        <input type="hidden" name="pay_det_previous_debt[]" value="${pay_det_previous_debt}">
        <input type="hidden" class="currentPayDetChange" name="pay_det_change[]" value="${pay_det_change}"></input>
        <input type="hidden" class="currentPayDetCashBack" cashbackatt="${cashBackRowStatus}" name="pay_det_cashback[]" value="${currentCashBack}">
        <input type="hidden" name="pay_det_cashback_status[]" value="${pay_det_cashback_status}">
        </td>
        <td><span>${CurrentDateTime}</span></td>
        <td><span>${payment_type}</span></td>
        <td><span>${showCurrencyFormat(pos_info.pos_currency, pos_info.pos_country_code, currentPaid)}</span></td>
        <td><span>${showCurrencyFormat(pos_info.pos_currency, pos_info.pos_country_code, pay_det_income)}</span></td>
        <td><span>${showCurrencyFormat(pos_info.pos_currency, pos_info.pos_country_code, pay_det_change)}</span ></td >
        <td><span>${pay_det_note}</span></td>

        </tr >
    `);

    $("#inp_paid_value").val(0);
    showAmount();
}


/*=============================================
FUNCTION TO REMOVE ROW FROM PAYMENT
=============================================*/
$(document).on("click", ".removeRow_payment", function () {

    let pos_info = JSON.parse(localStorage.getItem("pos_info"));

    let currentButton = $(this);

    $(this).parent().parent().remove();

    // RECALCULATE NEW CASHBACK ON REMOVE PAYMENT ROW
    let totalCashBack = $("#totalCashBack").val();
    let totalCustomerCashBack = $("#customerCashBack").val();
    let cashBackAtt = currentButton.closest('.dataRow').find('.currentPayDetCashBack').attr("cashbackatt");
    let currentCashBack = currentButton.closest('.dataRow').find('.currentPayDetCashBack');

    currentCashBack = Number(currentCashBack.val());

    // IF THE PAYMENT TYPE WAS DIFFERENT TO CASHBACK (MEANS THERE WAS NEW CASHBACK ASSIGNED TO THE CUSTOMER AND MUST BE REMOVED)
    if (cashBackAtt == "Yes") {

        let newCashBackAmount = totalCashBack - currentCashBack
        $("#totalCashBack").val(newCashBackAmount);
        $("#span_modal_new_cash_back").text(showCurrencyFormat(pos_info.pos_currency, pos_info.pos_country_code, newCashBackAmount));

    } else {

        let leftCashBack = roundedDecimal(Number(totalCustomerCashBack) + Number(currentCashBack), 2);
        $("#customerCashBack").val(leftCashBack);
        $("#span_available_cash_back").text(showCurrencyFormat(pos_info.pos_currency, pos_info.pos_country_code, leftCashBack));
    }

    showAmount();
    fnSweetToast(translate.row_removed, "success", 1500);

});

/*=============================================
CONFIMR PAYMENT CLICK ACTION
=============================================*/
$(document).on("change", "#sale_ncf_type", function () {

    let sale_ncf_type = $(this).val();
    let sale_cus_fiscal_number = $("#sale_cus_fiscal_number").val();

    if (!sale_cus_fiscal_number.trim() && sale_ncf_type == 'B01') {
        fnSweetToast(translate.please_confirm_the_customer_fiscal_number, "warning", 4000);
        jsEditCustomer();
        $("#myModalPayment").modal("hide");
        return false;
    }
});

/*=============================================
CONFIMR PAYMENT CLICK ACTION
=============================================*/
$(document).on("click", ".btnConfirmPayment", async function () {

    let tableListPaiement = $('.payment_entry_details tbody tr').length;

    if (tableListPaiement <= 0) {
        swalInit.fire(translate.no_payment_has_been_added, translate.please_add_a_payment_to_continue, "error");
        return;
    }

    let sale_ncf_type = $("#sale_ncf_type").val();
    let sale_cus_fiscal_number = $("#sale_cus_fiscal_number").val();

    if (Number(transactionId) >= 1) {
        let sale_info = await getSaleData(transactionId);

        if (sale_info.sale_status === "Disabled") {
            swalInit.fire(translate.this_sale_has_been_canceled, translate.cannot_add_more_payments, "error");
            return false;
        }
    }

    if (await validateToSaveOrder("save_payment") === false) return false;

    // if (sale_ncf_type == 'B01' && sale_cus_fiscal_number === "") {
    if (!sale_cus_fiscal_number.trim() && sale_ncf_type == 'B01') {
        fnSweetToast(translate.please_confirm_the_customer_fiscal_number, "warning", 3000);
        jsEditCustomer();
        return false;
    } else {
        fnSaveUpdate();

    }
});

// SAVE UPDATE SALE
async function fnSaveUpdate() {

    if (await validateToSaveOrder("save") === false) return false;

    $(".btnSaveOrder").prop("disabled", true);
    $(".btnSaveOrder").css('cursor', 'not-allowed');
    $(".btnSaveOrder").html(`${translate.loading_icon_text}`);

    $(".btnConfirmPayment").prop("disabled", true);
    $(".btnConfirmPayment").css('cursor', 'not-allowed');
    $(".btnConfirmPayment").html(`${translate.loading_icon_text}`);

    const formPostData = $("#frmSubmitOrder, #frmSubmitOrderDetail, #frmSubmitPaymentDetail").serialize();
    const apiUrl = 'ajax/sales.ajax.php?op=ajaxSaveUpdate';

    try {
        const response = await fetch(apiUrl, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded', // Include correct content type
            },
            body: formPostData,
        });


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

        // let result = {
        //     message: "Vente #31892 <br> Mises à jour avec succès",
        //     printMessage: "Voulez-vous imprimer une facture?",
        //     sale_code: "116581",
        //     sale_id: "31892",
        //     status: "success"
        // }

        if (res.status == "success") {
            showAmount();
            $(".btnConfirmPayment").prop("disabled", false);
            $(".btnConfirmPayment").css('cursor', 'pointer');
            $(".btnConfirmPayment").html(`<i class="ph-check-circle me-1"></i> ${translate.confirm_payment}`);

            swalInit.fire(res.message, "", res.status).then(function (result) {

                let ticketInfo = {
                    sale_id: res.sale_id,
                    sale_cus_id: res.sale_cus_id,
                    sale_ent_id: res.sale_ent_id,
                    sale_pos_id: res.sale_pos_id,
                }

                $(".divBtnOrderControl").remove();

                jsShowTicket(ticketInfo);
            });

        } else {
            console.log(res);
            swalInit.fire(translate.data_could_not_be_saved, "", res.status).then(function (result) {
                window.location = "sell";
            });
        }

    } catch (error) {
        console.error('Error:', error);
        swalInit.fire(translate.data_could_not_be_saved, "", "error").then(function (result) {
            window.location = "sell";
        });
    }
}

$(document).on("click", ".btnClosePrintTicket", function () {
    if (currentLocationSplited[0] == "sell") {
        window.location = "sell";
    }
});

function js_selectListFiscalReceipt(ent_id, sale_ncf_type = "") {

    let parameters = {
        ent_id: ent_id,
        sale_ncf_type: sale_ncf_type,
        csrf_token: csrf_token
    }
    $.post("ajax/tax-receipt.ajax.php?op=ajax_selectFiscalList", parameters,
        function (response) {
            // console.log(response);
            $("#sale_ncf_type").html(response);
            $("#sale_ncf_type").trigger("change");
        }
    );
}

$("#inputLoadSaleById").keydown(function (e) {
    if (e.which === 13) {

        let sale_id = $("#inputLoadSaleById").val();

        if (Number(sale_id) >= 1) {

            if (sale_id == "" || $.trim(sale_id) == "") {
                $("#inputLoadSaleById").focus();
                fnSweetToast(translate.enter_order_code, "warning", 1500);
                return false;
            } else {
                window.location = `sell-det-${sale_id}`;
            }

        } else {
            fnSweetToast(translate.invalide_code, "error", 1500);
        }
    }
});

$(document).on("click", ".btnSearchOrder", function () {

    let sale_id = $("#inputLoadSaleById").val();

    if (Number(sale_id) >= 1) {

        if (sale_id == "" || $.trim(sale_id) == "") {
            $("#inputLoadSaleById").focus();
            fnSweetToast(translate.enter_order_code, "warning", 1500);
            return false;
        } else {
            window.location = `sell-det-${sale_id}`;
        }

    } else {
        fnSweetToast(translate.invalide_code, "error", 1500);
    }

});