const user_lang = $("#user_lang").val();
const sess_ent_id = $("#sess_ent_id").val();
const sess_pos_id = $("#sess_pos_id").val();
const sess_user_id = $("#sess_user_id").val();
const stripe_customer_id = $("#stripe_customer_id").val();
const stripe_subscription_id = $("#stripe_subscription_id").val();
const sess_user_profile = $("#sess_user_profile").val();
const sess_user_fullname = $("#sess_user_fullname").val();
const posCurrencyId = $("#sess_pos_currency").val();
const business_category = $("#business_category").val();
const currency_symbol = $("#currency_symbol").val();
const csrf_token = $("#csrf_token").val();

document.addEventListener('DOMContentLoaded', () => {
    document.querySelectorAll('a.dropdown-item.active').forEach(link => {
        link.classList.remove('active');
    });
});

let langURL = "lang/en.json";
if (user_lang == "es") langURL = "lang/es.json";
if (user_lang == "fr") langURL = "lang/fr.json";

/* Loading the language file and storing it in a variable. */
// const translate = (function () {

//     var lang = null;
//     $.ajax({
//         'async': false,
//         'global': false,
//         'url': langURL,
//         'dataType': "json",
//         'success': function (data) {
//             lang = data;
//         }
//     });
//     return lang;
// })();

function loadTranslations() {
    let lang = null;
    $.ajax({
        async: false,
        url: langURL,
        dataType: "json",
        cache: false,           // tell jQuery not to cache
        data: { t: new Date().getTime() }, // extra cache buster
        success: function (data) {
            lang = data;
        }
    });
    return lang;
}

// Usage
const translate = loadTranslations();

// async function loadTranslations() {
//     const response = await fetch(`${langURL}?t=${Date.now()}`);
//     const translate = await response.json();
//     return translate;
// }

// // Usage
// const translate = loadTranslations();

//Función que se ejecuta al inicio
(function init() {
    check_session();
    checkCountOrderNotification();
    js_orders_list();
    fnListAllPendingOrderByUser();
})();

// CHECKING IF SESSION IS ACTIVE
function check_session() {
    // console.log("Checking Session...");
    setTimeout(check_session, 10000);
    $.get("ajax/check-session.ajax.php", function (response) {
        // console.log(response)
        if (response == "session_expired") {
            swalInit.fire(translate.session_expired, translate.your_session_has_expired_please_sign_in_again, "error").then(function (result) {
                window.location = "logout";
            })
        }
    });
}

function getCurrentPathLocation() {
    var url = window.location.pathname;
    return url.substring(url.lastIndexOf('/') + 1);
}

const currentLocation = getCurrentPathLocation();
const currentLocationSplited = getCurrentPathLocation().split("-");

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

    var lang = $(this).attr("lang");

    $.ajax({
        url: "ajax/users.ajax.php?op=ajax_ChangeUserInterfaceLanguage",
        type: "POST",
        data: { lang: lang, csrf_token: csrf_token },
        beforeSend: function () {
            // $(".btnShowStock").html(`<i class="fa fa-spinner fa-spin tx-14"></i> ESPERE...`);
        },
        success: function (response) {
            const res = JSON.parse(response);
            if (res.status == "success") {
                location.reload();
            } else {
                fnSweetToast(translate.error_could_not_change_system_language, "error");
            }
        }
    })

});

const borderColorValidated = localStorage.getItem("borderColorValidated");


function decimalNumberFormat(number) {
    return number.toLocaleString('en-US', {
        minimumFractionDigits: 2,
        maximumFractionDigits: 2
    });
}


function getCurrencyFormat(pos_currency = "", pos_country_code = "") {

    if (pos_currency == "") pos_currency = "USD";
    if (pos_country_code == "") pos_country_code = "es-DO";

    return new Intl.NumberFormat(pos_country_code, {
        style: 'currency',
        currency: pos_currency,
        minimumFractionDigits: 2
    });
}

function jsStorePosInfo(posInfo) {

    let posData = {
        pos_id: posInfo.pos_id, pos_code: posInfo.pos_code, pos_ent_id: posInfo.pos_ent_id, pos_name: posInfo.pos_name, pos_business_category: posInfo.pos_business_category, pos_currency: posInfo.pos_currency, pos_country: posInfo.pos_country, pos_state: posInfo.pos_state, pos_zip_code: posInfo.pos_zip_code, pos_city: posInfo.pos_city, pos_time_zone: posInfo.pos_time_zone, pos_address: posInfo.pos_address, pos_phone: posInfo.pos_phone, pos_phone2: posInfo.pos_phone2, pos_usd_exchange_rate: posInfo.pos_usd_exchange_rate, pos_tax: posInfo.pos_tax, pos_legal_tipping: posInfo.pos_legal_tipping, pos_card_tax: posInfo.pos_card_tax, pos_festive_mode: posInfo.pos_festive_mode, pos_show_menu_usd_amount: posInfo.pos_show_menu_usd_amount, pos_show_stock_menu: posInfo.pos_show_stock_menu, pos_ticket_footer: posInfo.pos_ticket_footer, pos_lang: posInfo.pos_lang, pos_menu_access: posInfo.pos_menu_access, pos_cash_back_status: posInfo.pos_cash_back_status, pos_cash_back_percentage: posInfo.pos_cash_back_percentage, pos_cash_back_availability_days: posInfo.pos_cash_back_availability_days, pos_cash_back_expiration_days: posInfo.pos_cash_back_expiration_days, pos_day_start_time: posInfo.pos_day_start_time, pos_day_end_time: posInfo.pos_day_end_time, pos_status: posInfo.pos_status, pos_created_by: posInfo.pos_created_by, pos_created_at: posInfo.pos_created_at, pos_country_code: `${posInfo.pos_lang}-${posInfo.pos_country}`
    }

    // STORE POS DATA INFO ON localStorage TO NOT CALL API AGAIN
    localStorage.setItem("pos_info", JSON.stringify(posData));
}

/*================================================
FUNCTION TO SHOW ALL BRANCHES LIST
=================================================*/
async function selectBranchByUserPermission(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);

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

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

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

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

            return true;

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

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

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


const showCurrencyFormat = function (pos_currency, pos_country_code = "", amount) {
    let amountFormat = getCurrencyFormat(pos_currency, pos_country_code).format(Number(amount)).replace(/([^\d,.]+)/, '$1 ');
    return amountFormat;
}

const currencyFormat = async function (pos_id, amount) {

    let posInfo = await getBranchData(pos_id);
    let posCountryCode = `${posInfo.pos_lang}-${posInfo.pos_country}`;

    let amountFormat = showCurrencyFormat(posInfo.pos_currency, posCountryCode, Number(amount));
    return amountFormat;
}

function roundedDecimal(value, decimals) {
    return Number(Math.round(value + 'e' + decimals) + 'e-' + decimals);
}

const fnSweetToast = function (text, icon, timer = "") {
    if (!timer) timer = 3000;
    swalInit.fire({
        text: text,
        icon: icon,
        toast: true,
        showConfirmButton: false,
        position: 'top',
        timer: timer,
    });
}

// Override Noty defaults
Noty.overrideDefaults({
    theme: 'limitless',
    layout: 'topCenter',
    type: 'alert',
    timeout: 3000,
    // modal: true,
    // closeWith: ['button']
});

const fnNotyToast = function (text, icon, timer = "") {
    if (!timer) timer = 3000;
    new Noty({
        text: text,
        type: icon,
        timeout: timer,
    }).show();
}

const fnSweetAlert = function (title, text, icon, timer = "") {
    if (!timer) timer = 3000;
    swalInit.fire({
        title: title,
        text: text,
        icon: icon,
        timer: timer,
    });
}


// swalInit.fire({
//     title: 'Enter your password',
//     input: 'password',
//     inputPlaceholder: 'Enter your password',
//     allowOutsideClick: false,
//     backdrop: false,
//     inputAttributes: {
//         'maxlength': 10,
//         'autocapitalize': 'off',
//         'autocorrect': 'off'
//     }
// }).then(function (result) {
//     if (result.value) {
//         swalInit.fire({
//             icon: 'success',
//             html: 'Entered password: ' + result.value
//         });
//     }
// });


if (!$().DataTable) {
    console.warn('Warning - datatables.min.js is not loaded.');
}

// Setting datatable defaults
$.extend($.fn.dataTable.defaults, {
    autoWidth: false,
    responsive: true,
    dom: '<"datatable-header justify-content-start"f<"ms-sm-auto"l><"ms-sm-3"B>><"datatable-scroll-wrap"t><"datatable-footer"ip>',
    language: {
        search: `<span class="me-3">${translate.filter}:</span> <div class="form-control-feedback form-control-feedback-end flex-fill">_INPUT_<div class="form-control-feedback-icon"><i class="ph-magnifying-glass opacity-50"></i></div></div>`,
        searchPlaceholder: `${translate.type_to_filter}...`,
        lengthMenu: `<span class="me-3">${translate.show}:</span> _MENU_`,
        paginate: { 'first': `${translate.first}`, 'last': `${translate.last}`, 'next': document.dir == "rtl" ? '&larr;' : '&rarr;', 'previous': document.dir == "rtl" ? '&rarr;' : '&larr;' }
    }
});

$(document).on('show.bs.modal', '.modal', function () {
    const zIndex = 1050 + 10 * $('.modal:visible').length;
    $(this).css('z-index', zIndex);
    setTimeout(() => $('.modal-backdrop').not('.modal-stack').css('z-index', zIndex - 1).addClass('modal-stack'));
});

$(document).on("click", ".btnOpenOrdersNotificationModal", function () {
    $('#orders-notification-modal').modal('show');
});

const timeAgo = (dateString) => {
    // function timeAgo(dateString) {
    const date = new Date(dateString);
    const now = new Date();
    const diff = now - date;
    const seconds = Math.floor(diff / 1000);
    const minutes = Math.floor(seconds / 60);
    const hours = Math.floor(minutes / 60);
    const days = Math.floor(hours / 24);
    const years = Math.floor(days / 365);

    if (years > 0) {
        return `${years} year${years !== 1 ? 's' : ''} ago`;
    } else if (days >= 30) {
        const months = Math.floor(days / 30);
        return `${months} month${months !== 1 ? 's' : ''} ago`;
    } else if (days > 0) {
        return `${days} day${days !== 1 ? 's' : ''} ago`;
    } else if (hours > 0) {
        return `${hours} hour${hours !== 1 ? 's' : ''} ago`;
    } else if (minutes > 0) {
        return `${minutes} minute${minutes !== 1 ? 's' : ''} ago`;
    } else {
        return 'just now';
    }
}


async function jsGetEnterpriseData(ent_id = "") {
    try {

        let valEntId = sess_ent_id;

        if (ent_id != "") {
            valEntId = ent_id;
        }

        const url = `ajax/enterprises.ajax.php?op=ajaxGetEnterpriseData&ent_id=${valEntId}`;
        const response = await fetch(url);

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

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

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


async function getBranchData(pos_id) {
    try {

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

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

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

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

async function getUserData(user_id) {
    try {

        const url = `ajax/users.ajax.php?op=ajaxGetUserData&user_id=${user_id}`;
        const response = await fetch(url);

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

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

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

async function getSaleData(sale_id) {
    try {

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

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

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

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

function formatName(fullName) {
    const names = fullName.trim().split(' ');
    return `${names[0]} ${names[names.length - 1].charAt(0)}.`;
}

async function isValidURL(urlToValidate) {
    try {
        // 1️⃣ Check valid URL format
        const url = new URL(urlToValidate);

        // 2️⃣ Check if resource exists using HEAD request
        const response = await fetch(url, {
            method: "HEAD",
            cache: "no-store"
        });

        return response.ok; // true if status 200–299

    } catch (error) {
        return false;
    }
}

/* Sending a request to the server to get the data to print. */
async function jsShowTicket(ticketInfo) {

    let entInfo = await jsGetEnterpriseData(ticketInfo.sale_ent_id);
    let posInfo = await getBranchData(ticketInfo.sale_pos_id);
    let cusInfo = await getCustomerDataById(ticketInfo.sale_cus_id);

    let ticketInfos = {
        sale_id: ticketInfo.sale_id,
        ent_name: entInfo.ent_name,
        ent_email: entInfo.ent_email,
        pos_phone: posInfo.pos_phone,
        pos_lang: posInfo.pos_lang,
        cus_phone: cusInfo.data.cus_phone,
        cus_email: cusInfo.data.cus_email,
    };

    // Remove object from localStorage
    localStorage.removeItem("ticketInfos");
    // Store object in localStorage
    localStorage.setItem("ticketInfos", JSON.stringify(ticketInfos));

    if (ticketInfos.sale_id === '' || ticketInfos.sale_id == undefined) {
        return false;
    } else {

        var parameters = {
            sale_id: ticketInfos.sale_id,
            csrf_token: csrf_token
        };

        $.ajax({
            data: parameters,
            url: 'reports/ticket/sale-ticket-modal.php',
            type: 'post',
            success: function (datos) {
                // $(".loader").hide();
                $("#printDiv").html("");
                $("#printDiv").html(datos);
                $("#printSaleTicketModal").modal("show");
            }
        });
    }
};

// Print Ticket
$(document).on("click", ".btnPrintTicket", function () {

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

    jsPrintPDFTicket(ticketInfos.sale_id);
});

/*=============================================
PRINT PURCHASE
=============================================*/
function jsPrintPDFTicket(sale_id) {
    var url = `reports/ticket/index.php?sale_id=${sale_id}`;
    window.open(url);
}

/* Opening a new window and printing the content of the div with id printDiv. */
function printTicket(reload = "", location = "") {
    var myPrintContent = document.getElementById('printDiv');
    // console.log(myPrintContent)
    var myPrintWindow = window.open("about:blank", 'Imprimir Ticket', 'toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=1,width=350,height=600,left = 390,top = 50');
    myPrintWindow.document.write(myPrintContent.innerHTML);
    myPrintWindow.document.close();
    myPrintWindow.focus();
    myPrintWindow.print();
    myPrintWindow.close();
    if (reload == 'yes') {
        window.location = location;
        return false;
    } else {
        return false;
    }
}

async function getCustomerDataById(cus_id) {
    try {

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

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

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

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

// getCustomerCashBack
async function getCustomerCashBack(cus_id) {
    try {

        const url = `ajax/customers.ajax.php?op=ajaxGetCustomerCashBack&cus_id=${cus_id}`;
        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);
    }
}


/* Reset Debt. */
async function jsSaleDebtReset(data) {

    // Remove object from localStorage when done
    localStorage.removeItem("tempObjDebtReset");
    // Store object in localStorage
    localStorage.setItem("tempObjDebtReset", JSON.stringify(data));

    $("#txtResetReason").val("");
    $("#txtResetReason").focus();
    $("#modalTransactionResetReason").modal('show');
};

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

    var reason = $("#txtResetReason").val();

    if (reason === "") {
        swalInit.fire(translate.please_write_the_reason_why_you_want_to_cancel_the_debt, "", "warning");
        $("#txtResetReason").css("border", "1px solid #d33 ");
        return false;
    } else {
        $("#txtResetReason").css("border", `1px solid ${borderColorValidated}`);
    }

    $("#modalTransactionResetReason").modal('hide');

    let objCancelReason = { transaction_reason: reason };
    let csrf_token_param = { csrf_token: csrf_token };

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

    // Merging objects using spread operator
    let finalDataDebtReset = { ...getIdAndType, ...objCancelReason, ...csrf_token_param };

    jsConfirmSaleDebtReset(finalDataDebtReset);
});

/**
 * It's a function that resets a debt of a customer.
 */
async function jsConfirmSaleDebtReset(props) {

    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
            $.post("ajax/sales.ajax.php?op=ajaxResetDebt", props, function (response) {
                // console.log(response)
                response = JSON.parse(response);
                swalInit.fire(response.title, response.message, response.type).then(function (result) {
                    // Remove object from localStorage when done
                    localStorage.removeItem("tempObjDebtReset");
                    listDataToDatatable();
                    $("#modalCustomerDebtOrdes").modal('hide');
                });
            });

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

/* Reset Debt. */
function jsCancelTransaction(ticketInfo) {

    // Remove object from localStorage when done
    localStorage.removeItem("tempObjCancellation");
    // Store object in localStorage
    localStorage.setItem("tempObjCancellation", JSON.stringify(ticketInfo));

    $("#txtCancellationReason").val("");
    $("#txtCancellationReason").focus();
    $("#modalTransactionCancelReason").modal('show');
};

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

    var reason = $("#txtCancellationReason").val();

    if (reason === "") {
        swalInit.fire(translate.please_write_the_reason_for_the_cancellation, "", "warning");
        $("#txtCancellationReason").css("border", "1px solid #d33 ");
        return false;
    } else {
        $("#txtCancellationReason").css("border", `1px solid ${borderColorValidated}`);
    }

    $("#modalTransactionCancelReason").modal('hide');

    let objCancelReason = { transaction_reason: reason };
    let csrf_token_param = { csrf_token: csrf_token };

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

    // Merging objects using spread operator
    let finalDataCancellation = { ...getTicketInfo, ...objCancelReason, ...csrf_token_param };

    jsConfirmCancelData(finalDataCancellation);
});

/*=============================================
CANCEL INFORMATION
=============================================*/
async function jsConfirmCancelData(props) {

    let url = "";
    if (props.section == "sales") url = "ajax/sales.ajax.php?op=ajaxCancelData";
    if (props.section == "purchases") url = "ajax/purchases.ajax.php?op=ajaxCancelData";

    if (url == "") return false;

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

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

                // Do something with the result
                $.post(url, props, function (response) {
                    // console.log(response)
                    response = JSON.parse(response);

                    swalInit.fire(response.title, response.message, response.status).then(function (result) {
                        // Remove object from localStorage when done
                        localStorage.removeItem("tempObjCancellation");

                        if (props.section == "sales") {
                            listPendingSaleToTable();
                            listCompletedSaleToTable();
                            listCancelledSaleToTable();

                            if (response.status == "success") {
                                jsShowTicket(props);
                            }
                        }

                        if (props.section == "purchases") {
                            listDataToDatatable();
                        }
                    });
                });
            }
        });

    } 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
                $.post(url, props, function (response) {
                    // console.log(response)
                    response = JSON.parse(response);
                    swalInit.fire(response.title, response.message, response.status).then(function (result) {
                        // Remove object from localStorage when done
                        localStorage.removeItem("tempObjCancellation");

                        if (props.section == "sales") {
                            listPendingSaleToTable();
                            listCompletedSaleToTable();
                            listCancelledSaleToTable();

                            if (response.status == "success") {
                                jsShowTicket(props);
                            }
                        }

                        if (props.section == "purchases") {
                            listDataToDatatable();
                        }
                    });
                });
            } else if (result.dismiss === swalInit.DismissReason.cancel) {
            }
        });
    }
}

async function fnShowEnterprisePasswords() {

    try {

        const url = `ajax/enterprises.ajax.php?op=ajaxShowEnterprisePasswords`;
        const response = await fetch(url);

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

        const res = await response.json();

        $("#txtCancelPassword").val(res.ent_cancel_password);
        $("#txtDiscountPassword").val(res.ent_discount_password);
        $("#txtStatisticPassword").val(res.ent_statistic_password);

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

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

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

        const url = `ajax/enterprises.ajax.php?op=ajaxResetAllPasswords`;
        const response = await fetch(url);

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

        fnShowEnterprisePasswords();
        fnSweetToast(translate.access_codes_have_been_regenerated, "success", 3000);

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

$(document).on("click", ".btnRefreshPasswords", async function () {
    fnShowEnterprisePasswords();
    fnSweetToast(translate.refreshed, "success", 2000);
});

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

});

async function fnListAllPendingOrderByUser() {

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

    const response = await fetch("ajax/header.ajax.php?op=ajaxListPendingOrderByUser");
    const res = await response.json();
    // console.log(res);

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

        if (res.data.length > 0) {

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

                let customerNameFormated = item.client_full_name.toLowerCase().replace(/\b\w/g, char => char.toUpperCase());
                let saleDebt = showCurrencyFormat(pos_info.pos_currency, pos_info.pos_country_code, item.sale_debts);

                return [
                    `<a href='sell-det-${item.sale_id}' id='${item.sale_id}'>${item.sale_id}</a>`,
                    `<a href='sell-det-${item.sale_id}'>${customerNameFormated}</a>`,
                    `<span class="badge bg-danger fw-medium text-white fs-sm">${saleDebt}</span>`,
                ];
            });

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

$(document).on("click", ".odd", function () {
    let sale_id = $(this).closest("tr").find("td:first-child a").attr("id");
    if (sale_id !== undefined) location.href = `sell-det-${sale_id}`;
});

async function checkCountOrderNotification() {
    setTimeout(checkCountOrderNotification, 10000);

    const orderNotification = await fetch("ajax/header.ajax.php?op=ajax_countOrderNotification");
    const res = await orderNotification.json();
    // console.log(res);

    $("#count_pending_orders").text(res.PendingOrderByUser.pendingSaleByUser);
    $("#count_undelivered_orders").text(res.OrderNotification.total_pending);
    $("#count_delivered_orders").text(`${res.OrderNotification.total_complete}`);

    let totalNotification = Number(res.PendingOrderByUser.pendingSaleByUser) + Number(res.OrderNotification.total_pending);

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

    if (pos_info == null) {
        totalNotification = 0;
    } else {

        if (pos_info.pos_business_category == "Others") {
            totalNotification = Number(res.PendingOrderByUser.pendingSaleByUser);
        }
    }

    $(".count_orders_notifications").hide();
    if (totalNotification > 0) $(".count_orders_notifications").show();
    $(".count_orders_notifications").text(totalNotification);

    $(".divBtnCompleteAllOrders").addClass("hide");
    if (Number(res.OrderNotification.total_pending) > 0) $(".divBtnCompleteAllOrders").removeClass("hide");
}

async function js_orders_list() {

    const responseUndelivered = await fetch("ajax/header.ajax.php?op=ajax_pending_orders_list");
    const resUndelivered = await responseUndelivered.json();

    let htmlUndelivered = "";
    if (resUndelivered.data.length > 0) {
        resUndelivered.data.forEach(item => {
            htmlUndelivered += `<div class="d-flex justify-content-center px-3 mt-2">
            <span class="input-group-text fs-3 me-3">#${item.ord_det_sale_id}-${item.ord_det_number}</span>
            <button class="btn btn-warning me-2" onclick="js_show_order('${item.ord_det_code}','${item.ord_det_sale_id}')"><i class="ph-eye"></i></button>
            <button class="btn btn-secondary me-2" onclick="printPendingOrder('${item.ord_det_code}')"><i class="ph-printer"></i></button>
            <button class="btn btn-success" onclick="js_complete_order('${item.ord_det_code}')"><i class="ph-check"></i></button>
            </div>`;
        });
    } else {
        htmlUndelivered = `<div class="d-flex justify-content-center px-3 mt-3">
        <span class="input-group-text fs-base me-3">${translate.no_order_to_deliver}</span>
        </div>`;
    }

    $(".show_undelivered_orders").html(htmlUndelivered);

    const responseDelivered = await fetch("ajax/header.ajax.php?op=ajax_complete_orders_list");
    const resDelivered = await responseDelivered.json();
    let htmlDelivered = "";
    if (resDelivered.data.length > 0) {
        resDelivered.data.forEach(item => {
            htmlDelivered += `<div class="d-flex justify-content-center px-3 mt-2">
            <span class="input-group-text fs-3 me-3">#${item.ord_det_sale_id}-${item.ord_det_number}</span>
            <button class="btn btn-warning me-2" onclick="js_show_order('${item.ord_det_code}','${item.ord_det_sale_id}','delivered')"><i class="ph-eye"></i></button>
            <button class="btn btn-secondary me-2" onclick="printPendingOrder('${item.ord_det_code}')"><i class="ph-printer"></i></button>
            </div>`;
        });
    } else {
        htmlDelivered = `<div class="d-flex justify-content-center px-3 mt-3">
        <span class="input-group-text fs-base me-3">${translate.no_order_has_been_delivered_yet}</span>
        </div>`;
    }

    $(".show_delivered_orders").html(htmlDelivered);
}


/* Sending a request to the server to get the data to print. */
function js_show_order(ord_det_code, sale_id, status) {

    if (ord_det_code === '' || ord_det_code == undefined) {
        return false;
    } else {

        var parameters = {
            ord_det_code: ord_det_code,
            csrf_token: csrf_token
        };

        $.ajax({
            data: parameters,
            url: 'reports/exTicketOrder.php',
            type: 'post',
            success: function (datos) {
                // $(".loader").hide();
                $("#printDivOrderHidden").html("");
                $("#printDivOrderHidden").html(datos);
                $("#printDivOrder").html("");
                $("#printDivOrder").html(datos);
                $("#showOrderModal").modal("show");
                $("#order_id").val(sale_id);
                $("#order_code").val(ord_det_code);

                if (status == "delivered") {
                    $(".btnCompleteOrder").hide();
                } else {
                    $(".btnCompleteOrder").show();
                }
            }
        });
    }
};

/* Sending a request to the server to get the data to print. */
function jsEditOrder() {
    let sale_id = $("#order_id").val();
    location.href = `sell-det-${sale_id}`;
};

/* Sending a request to the server to get the data to print. */
function jsCompleteOrder() {
    let ord_det_code = $("#order_code").val();
    js_complete_order(ord_det_code);
};

/* Sending a request to the server to get the data to print. */
function printPendingOrder(ord_det_code) {

    if (ord_det_code === '' || ord_det_code == undefined) {
        return false;
    } else {

        var parameters = {
            ord_det_code: ord_det_code,
            csrf_token: csrf_token
        };

        $.ajax({
            data: parameters,
            url: 'reports/exTicketOrder.php',
            type: 'post',
            success: function (datos) {
                // $(".loader").hide();
                $("#printDivOrderHidden").html("");
                $("#printDivOrderHidden").html(datos);
                printTicketOrder();
            }
        });
    }
};

/*=============================================
FUNCTION TO PRINT SALE
=============================================*/
function printTicketOrder() {
    var myPrintContent = document.getElementById('printDivOrderHidden');
    // console.log(myPrintContent)
    var myPrintWindow = window.open("about:blank", 'Imprimir Ticket', 'toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=1,width=350,height=600,left = 390,top = 50');
    myPrintWindow.document.write(myPrintContent.innerHTML);
    myPrintWindow.document.close();
    myPrintWindow.focus();
    myPrintWindow.print();
    myPrintWindow.close();
    return false;
}

function js_complete_order(ord_det_code) {

    let props = {
        ord_det_code: ord_det_code,
        csrf_token: csrf_token
    }

    swalInit.fire({
        title: `${translate.confirm_that_this_order_has_been_delivered}.`,
        text: "",
        icon: 'warning',
        showCancelButton: true,
        confirmButtonText: translate.yes,
        cancelButtonText: translate.no,
        buttonsStyling: false,
        customClass: {
            confirmButton: 'btn btn-success',
            cancelButton: 'btn btn-danger'
        }
    }).then(async function (result) {
        if (result.value) {

            try {

                const response = await $.ajax({
                    type: "POST",
                    url: "ajax/header.ajax.php?op=ajax_complete_order",
                    data: props
                });

                const res = JSON.parse(response);
                fnSweetToast(res.message, res.status, 1000);
                js_orders_list();
                $("#showOrderModal").modal("hide");

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

        }

    })
}

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

    let qtyPending = $("#count_undelivered_orders").text();

    if (Number(qtyPending) <= 0) {
        fnSweetToast(translate.there_are_no_pending_orders, "error", 2000);
        return false;
    }

    swalInit.fire({
        title: translate.are_you_sure,
        text: translate.confirm_that_you_want_to_deliver_all_pending_orders,
        icon: 'warning',
        showCancelButton: true,
        confirmButtonText: translate.yes,
        cancelButtonText: translate.no,
        buttonsStyling: false,
        customClass: {
            confirmButton: 'btn btn-success',
            cancelButton: 'btn btn-danger'
        }
    }).then(async function (result) {
        if (result.value) {

            try {

                const response = await $.ajax({
                    type: "GET",
                    url: "ajax/header.ajax.php?op=ajax_complete_all_orders",
                });

                const res = JSON.parse(response);
                fnSweetToast(res.message, res.status, 1000);
                js_orders_list();

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

    })
});


async function fnShowProfile() {

    try {

        const url = `ajax/users.ajax.php?op=ajaxGetUserSessionData`;
        const response = await fetch(url);

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

        const res = await response.json();

        $("#user_id_profile").val(res.user_id);
        $("#current_password_profile").val(res.user_password);

        let imagePath = res.user_image || "assets/images/anonymous.png";
        $(".profilePicturePreview").off("error").on("error", function () {
            $(this).off("error").attr("src", "assets/images/anonymous.png");
        }).attr("src", imagePath);

        $(".spanUserFullName").text(`${res.user_firstname} ${res.user_lastname}`);
        $(".spanUserProfile").text(res.user_profile);
        $(".spanUserName").text(res.user_name);
        $(".spanUserPhone").text(res.user_phone);
        $(".spanUserEmail").text(res.user_email);
        $(".spanUserAddress").text(res.user_address);

        const formattedDate = moment(`${res.user_birthday}`).format('DD-MMMM-YYYY');
        $(".spanUserBirthday").text(formattedDate);

        $("#user_name_profile").val(res.user_name);

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

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

$(document).on("change", ".new_profile_picture", async function () {

    var imageUploaded = this.files[0];

    //image validation
    if (imageUploaded["type"] != "image/jpeg" && imageUploaded["type"] != "image/jpg" && imageUploaded["type"] != "image/png") {

        $(".new_profile_picture").val("");

        fnSweetToast(translate.the_image_must_be_in_jpg_jpeg_or_png_forma, "error", 3500);

    } else if (imageUploaded["size"] > 2000000) {

        $(".new_profile_picture").val("");

        fnSweetToast(translate.the_image_must_not_exceed_2m, "error", 3500);

    } else {

        var imageData = new FileReader;
        imageData.readAsDataURL(imageUploaded);

        $(imageData).on("load", function (event) {
            var imagePath = event.target.result;
            $(".profilePicturePreview").attr("src", imagePath);
        })
    }
});

// Validation input form
function validateProfileInputFormData(type) {

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

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

    var user_name_profile = $("#user_name_profile").val();
    var user_password_profile = $("#user_password_profile").val();
    var user_password_confirm_profile = $("#user_password_confirm_profile").val();

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

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

// Save user function
$(document).on("click", ".btnSaveProfile", function () {
    if (validateProfileInputFormData("save") == false) {
        return false;
    } else {
        fnSaveUpdateUserProfile();
    }
});

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

// Save and Edit User function
async function fnSaveUpdateUserProfile() {

    if (validateProfileInputFormData("save") === false) return false;

    setButtonStatus('loading');

    const formPostData = new FormData($("#frmUserProfile")[0]);
    const apiUrl = 'ajax/users.ajax.php?op=ajaxSaveUpdateUserProfile';

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

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

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

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

            setButtonStatus('ready');

            swalInit.fire(data.message, "", data.status).then(function (result) {
                $("#modalUserProfile").modal("hide");
                if (data.reload) location.reload();
            });

        } else {
            console.log(data);
            swalInit.fire(data.message, "", data.status).then(function (result) {
                setButtonStatus('ready');
            });
        }

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

function modalTextMessageWhatsApp() {
    $("#modalTextMessageWhatsApp").modal("show");
}


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

    let ws_phone_number = $("#ws_phone_number").val(); // ws_phone_number
    let ws_text_message = $("#ws_text_message").val(); // ws_text_message

    if (ws_phone_number == "" || ws_text_message == "") {
        fnSweetToast(`${translate.please_complete_the_form_the_fields_with} * ${translate.are_required}`, "error", 3500);
        return false;
    }

    let toPhoneFormatted = ws_phone_number.replace(/[\s\-\_\(\)\.\+]/g, "");

    let entInfo = await jsGetEnterpriseData(sess_ent_id);
    let posInfo = await getBranchData(sess_pos_id);

    const props = {
        toPhone: toPhoneFormatted,
        entName: entInfo.ent_name,
        replyTo: posInfo.pos_phone,
        pos_lang: posInfo.pos_lang,
        message: ws_text_message,
        csrf_token: csrf_token
    };

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

    // Send the image data to PHP
    $.post("controllers/send-whatsapp-message.php?op=sendWhatsAppTextMessage", props, function (response) {

        // console.log(response);
        resJson = JSON.parse(response);

        if (resJson.status == "success") {
            console.log(`From: ${resJson.response.response.from}, To: ${resJson.response.response.to}, Body: ${resJson.response.response.body}`);
            swalInit.fire(translate.success, translate.the_ticket_has_been_sent_successfully, resJson.status).then(function (result) {
                $("#sendWhatsAppTicketModal").modal("hide");

                $(".btnSendWhatsAppTextMessage").prop("disabled", false);
                $('.btnSendWhatsAppTextMessage').css('cursor', 'pointer');
                $(".btnSendWhatsAppTextMessage").html(`<i class="ph-whatsapp-logo me-1"></i> Send Message`);
            });
        } else {
            console.log(response);
            swalInit.fire(translate.whatsapp_messaging_service_is_unavailable, translate.please_try_again_later, "warning").then(function (result) {
                $("#sendWhatsAppTicketModal").modal("hide");

                $(".btnSendWhatsAppTextMessage").prop("disabled", false);
                $('.btnSendWhatsAppTextMessage').css('cursor', 'pointer');
                $(".btnSendWhatsAppTextMessage").html(`<i class="ph-whatsapp-logo me-1"></i> Send Message`);
            });
        }
    });
});


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

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

    intlPhoneFormatWsPhoneMediaMsg.setNumber(ticketInfos.cus_phone);
    $("#sendWhatsAppTicketModal").modal("show");
});

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

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

    let cus_send_whatsapp = $("#cus_send_whatsapp").val();

    if (cus_send_whatsapp == "") {
        $("#cus_send_whatsapp").css("border", "1px solid red ");
        fnSweetToast(translate.please_enter_the_customer_phone, "error", 3500);
        return false;
    } else {

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

        if (!intlPhoneFormatWsPhoneMediaMsg.isValidNumber()) {
            fnSweetToast(translate.invalid_phone_number_please_try_again, "error", 3500);
            $("#cus_send_whatsapp").css("border", "1px solid red");
            return false;
        } else {
            $("#cus_send_whatsapp").css("border", `1px solid ${borderColorValidated}`);
        }
    }

    // Save customer phone number


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

    let props = {
        sale_id: ticketInfos.sale_id,
        from: 'whatsapp',
        csrf_token: csrf_token
    };

    $.ajax({
        data: props,
        url: 'reports/ticket/sale-ticket-whatsapp-email.php',
        type: 'post',
        success: function (response) {

            // Create a temporary div and set the HTML content
            const tempDiv = document.createElement('div');
            tempDiv.innerHTML = response;
            tempDiv.style.position = 'absolute';
            tempDiv.style.left = '-9999px'; // Hide the div
            document.body.appendChild(tempDiv);

            html2canvas(tempDiv).then(function (canvas) {

                // Remove the temporary div after capturing
                document.body.removeChild(tempDiv);

                // Convert canvas to Base64 and prepare data for AJAX
                const imageData = canvas.toDataURL("image/jpeg", 0.8); // quality 80%

                let cus_send_whatsapp = $("#cus_send_whatsapp").val();
                // Format phone number
                let toPhoneFormatted = cus_send_whatsapp.replace(/[\s\-\_\(\)\.\+]/g, "");

                const props = {
                    image: imageData,
                    sale_id: ticketInfos.sale_id,
                    toPhone: toPhoneFormatted,
                    entName: ticketInfos.ent_name,
                    replyTo: ticketInfos.pos_phone,
                    pos_lang: ticketInfos.pos_lang,
                    csrf_token: csrf_token
                };

                // Send the image data to PHP
                $.post("controllers/send-whatsapp-message.php?op=sendTicketWhatsApp", props, function (response) {

                    // console.log(response);
                    resJson = JSON.parse(response);

                    if (resJson.status == "success") {
                        console.log(`From: ${resJson.response.response.from}, To: ${resJson.response.response.to}, Body: ${resJson.response.response.body}`);
                        swalInit.fire(translate.success, translate.the_ticket_has_been_sent_successfully, resJson.status).then(function (result) {
                            $("#sendWhatsAppTicketModal").modal("hide");

                            $(".btnSendTicketToWhatsApp").prop("disabled", false);
                            $('.btnSendTicketToWhatsApp').css('cursor', 'pointer');
                            $(".btnSendTicketToWhatsApp").html(`<i class="ph-envelope me-1"></i> Send ticket`);
                        });
                    } else {
                        console.log(response);
                        swalInit.fire(translate.whatsapp_messaging_service_is_unavailable, translate.please_try_again_later, "warning").then(function (result) {
                            $("#sendWhatsAppTicketModal").modal("hide");

                            $(".btnSendTicketToWhatsApp").prop("disabled", false);
                            $('.btnSendTicketToWhatsApp').css('cursor', 'pointer');
                            $(".btnSendTicketToWhatsApp").html(`<i class="ph-envelope me-1"></i> Send ticket`);
                        });
                    }
                });
            });
        }
    });

});


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

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

    $("#cus_send_email").val(ticketInfos.cus_email);
    $("#sendEmailTicketModal").modal("show");
});

function validateEmail(email) {
    const emailPattern = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
    return emailPattern.test(email);
}


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

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

    let cus_send_email = $("#cus_send_email").val();

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

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

    if (validateEmail(cus_send_email.trim()) == false) {

        $("#cus_send_email").css("border", "1px solid red ");
        fnSweetToast(translate.invalid_email_address, "error", 3500);
        return false;

    } else {

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

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

        let props = {
            sale_id: ticketInfos.sale_id,
            from: 'email',
            csrf_token: csrf_token
        };

        $.ajax({
            data: props,
            url: 'reports/ticket/sale-ticket-whatsapp-email.php',
            type: 'post',
            success: function (response) {

                const htmlContent = response;
                const bodyParam = `htmlContent=${encodeURIComponent(htmlContent)}&toEmail=${encodeURIComponent(cus_send_email)}&saleId=${encodeURIComponent(ticketInfos.sale_id)}&entName=${encodeURIComponent(ticketInfos.ent_name)}&replyTo=${encodeURIComponent(ticketInfos.ent_email)}&replyToPhone=${encodeURIComponent(ticketInfos.pos_phone)}&pos_lang=${encodeURIComponent(ticketInfos.pos_lang)}`;

                // console.log(bodyParam);
                // return

                // Send HTML content via POST
                fetch("controllers/resend-email.php?op=sendTicketEmail", {
                    method: "POST",
                    headers: {
                        "Content-Type": "application/x-www-form-urlencoded",
                    },
                    body: bodyParam // Include both htmlContent and username in the body
                })
                    .then(response => response.text())
                    .then(data => {

                        resJson = JSON.parse(data);

                        if (resJson.status == "success") {
                            swalInit.fire(translate.success, translate.email_has_been_sent_successfully, resJson.status).then(function (result) {
                                $("#sendEmailTicketModal").modal("hide");

                                $(".btnSendTicketToEmail").prop("disabled", false);
                                $('.btnSendTicketToEmail').css('cursor', 'pointer');
                                $(".btnSendTicketToEmail").html(`<i class="ph-envelope me-1"></i> Send ticket`);
                            });
                        } else {
                            console.log(resJson);
                            swalInit.fire(translate.email_service_is_not_available, translate.please_try_again_later, "warning").then(function (result) {
                                $("#sendEmailTicketModal").modal("hide");

                                $(".btnSendTicketToEmail").prop("disabled", false);
                                $('.btnSendTicketToEmail').css('cursor', 'pointer');
                                $(".btnSendTicketToEmail").html(`<i class="ph-envelope me-1"></i> Send ticket`);
                            });
                        }
                    })
                    .catch(error => {
                        console.error("Error:", error);
                        $("#sendEmailTicketModal").modal("hide");
                        $(".btnSendTicketToEmail").prop("disabled", false);
                        $('.btnSendTicketToEmail').css('cursor', 'pointer');
                        $(".btnSendTicketToEmail").html(`<i class="ph-envelope me-1"></i> Send ticket`);
                    });
            }
        });
    }

});


$("#spanNetworkError").text(translate.network_error);
$("#spanNetworkErrorMessage").text(translate.please_connect_to_the_internet_and_try_again);
$("#spanNetworkErrorRefresh").text(translate.refresh);

// $("#spanScreenLock").text(translate.locked_screen);
$("#spanUserFullName").text(sess_user_fullname);
$("#spanScreenLockMessage").text(translate.please_enter_your_password_to_unlock_the_screen);
$("#spanLogout").text(translate.log_out);
$("#spanUnlock").text(translate.unlock);

function fnLockScreen() {

    fetch(`ajax/users.ajax.php?op=ajaxLockScreen`);

    $(".screen-lock").removeClass("hide");
}

async function fnUnlockScreen() {

    let password = $(".inputScreenLockPassword").val();

    if (password == "") {
        $(".inputScreenLockPassword").focus();
        $(".inputScreenLockPassword").css("border", "1px solid red ");
        fnSweetToast(translate.please_enter_your_password_to_unlock_the_screen, "warning", 3500);
        return false;
    } else {
        $(".inputScreenLockPassword").css("border", `1px solid ${borderColorValidated}`);
    }

    try {
        const url = `ajax/users.ajax.php?op=ajaxUnlockScreen&unlockPassword=${password}`;
        const response = await fetch(url);

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

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

        if (res.status == "success") {
            $(".screen-lock").addClass("hide");
            fnSweetToast(translate.screen_unlocked, "success", 2000);
        } else {
            fnSweetToast(translate.incorrect_password_try_again, "error", 3500);
        }

        $(".inputScreenLockPassword").val("");
        $(".inputScreenLockPassword").focus();

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

$(document).on("click", ".btnUnlockScreen", async function () {
    fnUnlockScreen();
});

$(".inputScreenLockPassword").keydown(function (e) {
    if (e.which === 13) {
        fnUnlockScreen();
    }
});

const pswrdField = document.querySelector(".passwordLockScreen"),
    toggleIcon = document.querySelector(".pointerLockScreen");

toggleIcon.onclick = () => {
    if (pswrdField.type === "password") {
        pswrdField.type = "text";
        pswrdField.focus();
    } else {
        pswrdField.type = "password";
    }
}

async function createCheckoutStripeSession(arrayEntInfo) {

    const entInfo = JSON.parse(arrayEntInfo.dataset.info);
    // console.log(entInfo); // Ejemplo de uso

    const enterpriseId = entInfo.ent_id;
    const entEmail = entInfo.ent_email;
    const entName = entInfo.ent_name;
    const productPriceId = entInfo.plan_product_price_id;
    const posQuantity = entInfo.pos_quantity;

    if (productPriceId) {
        // Redirect to Stripe Checkout
        try {
            // You can dynamically build the URL using parameters
            const params = new URLSearchParams({
                case: 'createCheckoutStripeSession',
                product_price_id: productPriceId,
                client_reference_id: enterpriseId,
                client_reference_email: entEmail,
                client_reference_name: entName,
                pos_quantity: posQuantity
            });

            const url = `stripe/stripe.controller.php?${params.toString()}`;
            const response = await fetch(url);

            const data = await response.json();

            if (!response.ok) {
                // console.error(`HTTP ${await response.json()} - Failed to get data from API`);
                throw new Error(`HTTP ${response.status} - ${data.error}`);
            }

            if (!data.success) {
                console.error('❌ Stripe API Error:', data.error);
                return false;
            }

            console.log('✅ Checkout Session Created:', data);

            window.location.href = data.data.checkout_url;

        } catch (error) {
            console.error('⚠️ Fetch error:', error.message);
            return false;
        }
    }
}

// function fnOpenStripeCustomerPortal(arrayEntInfo) {
//     // alert("Stripe Customer Portal: " + entInfo);
//     const entInfo = JSON.parse(arrayEntInfo.dataset.info);
//     // console.log(entInfo); // Ejemplo de uso

//     let entEmailLinkExt = `?prefilled_email=${entInfo.ent_email}`;
//     if (entInfo.ent_email == "" || entInfo.ent_email == null) entEmailLinkExt = "";

//     window.open(`https://billing.stripe.com/p/login/eVqcN6ec94uM1Kr5iRaVa00${entEmailLinkExt}`);
// }
