listDataToDatatable();

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

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

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

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

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

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

    $("#pos_ent_id").val(ent_id_value);
    $("#pos_id").val("");
    $("#pos_time_zone").val("America/New_York").trigger('change');
    $("#pos_currency").val("USD").trigger('change');
    $(".divLegalTipping").show();

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

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

// List All Enterprises on change status
// $(document).on("change", ".searchStatus", function () {
//     listDataToDatatable();
// });


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

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

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

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

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

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

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

    // ── Helper: build a toggle switch for a single on/off field ──────────────
    // isOn      — current state is active/on
    // handlerFn — JS function name to call on click
    // posId     — item.pos_id
    // onValue   — value to pass when toggling OFF  (e.g. 'Off' or 'Disabled')
    // offValue  — value to pass when toggling ON   (e.g. 'On'  or 'Enabled')
    function buildToggle(isOn, handlerFn, posId, onValue, offValue) {
        const [nextVal, state, label] = isOn
            ? [onValue, 'checked', translate.enabled]
            : [offValue, 'unchecked', translate.disabled];

        const checked = isOn ? 'checked' : '';

        return `
            <div class="form-check form-switch mb-2">
                <input type="checkbox"
                       class="form-check-input form-check-input-success"
                       onclick="${handlerFn}(${posId},'${nextVal}',this,'${state}')"
                       ${checked}>
                <label class="form-check-label">${label}</label>
            </div>`;
    }

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

    // ── Collect props based on current location ───────────────────────────────
    const props = {
        ent_id: currentLocation === 'branches-adm'
            ? ($("#ent_id_value").val() || '').trim()
            : sess_ent_id,
        pos_status: 'All',
    };

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

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

    try {
        const res = await getDataFromAPI(props);

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

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

            if (res.data.length > 0) {

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

                    // ── Shared toggle switches ────────────────────────────────
                    const btnUsdMenu = buildToggle(item.pos_show_menu_usd_amount !== 'Off', 'jsSwitchUsdInOnlineMenu', item.pos_id, 'Off', 'On');
                    const btnFestive = buildToggle(item.pos_festive_mode !== 'Off', 'jsSwitchFestiveMode', item.pos_id, 'Off', 'On');
                    const btnMenuAccess = buildToggle(item.pos_menu_access !== 'Off', 'jsSwitchOnlineMenuAccess', item.pos_id, 'Off', 'On');
                    const btnCashback = buildToggle(item.pos_cash_back_status !== 'Off', 'jsSwitchCashbackAccess', item.pos_id, 'Off', 'On');
                    const btnStatus = buildToggle(item.pos_status !== 'Disabled', 'jsSwitchStatus', item.pos_id, 'Disabled', 'Enabled');
                    const btnShow = buildToggle(item.pos_show !== 'Off', 'jsSwitchShowStatus', item.pos_id, 'Off', 'On');

                    // ── Shared menu link ──────────────────────────────────────
                    const btnMenuLink = `
                        <a  target="_blank"
                            href="https://menu.evosyspos.com/menu-pos-${item.pos_code}"
                            role="button"
                            class="btn btn-sm btn-warning">
                            <i class="ph-eye me-1"></i> ${translate.show}
                        </a>`;

                    if (currentLocation === 'branches-adm') {

                        const saleResetInfo = {
                            transaction_id: item.pos_id,
                            transaction_type: 'pos_debt_reset',
                        };

                        const btnOptions = `
                            <button type="button" class="btn btn-indigo dropdown-toggle"
                                    data-bs-toggle="dropdown">${translate.action}</button>
                            <div class="dropdown-menu dropdown-menu-theme">
                                <button type="button" class="dropdown-item light-warning-on-hover"
                                        onclick='jsEditData(${JSON.stringify(item)})'>
                                    <i class="ph-pencil-simple-line me-1"></i> ${translate.edit}
                                </button>
                                <button type="button" class="dropdown-item danger-on-hover text-danger"
                                        onclick='jsSaleDebtReset(${JSON.stringify(saleResetInfo)})'>
                                    <i class="ph-warning me-1"></i> ${translate.debt_reset}
                                </button>
                            </div>`;

                        return [
                            item.pos_id,
                            item.pos_name,
                            item.pos_business_category,
                            btnFestive,
                            btnCashback,
                            btnUsdMenu,
                            btnMenuAccess,
                            btnShow,
                            btnStatus,
                            btnMenuLink,
                            btnOptions,
                        ];
                    }

                    if (currentLocation === 'branches') {

                        const posPhones = `<div class="row"><span>${item.pos_phone}</span><span>${item.pos_phone2}</span></div>`;
                        const posAddress = `${item.pos_address}, ${item.pos_city} ${item.pos_state} ${item.pos_zip_code} ${item.pos_country}`;

                        return [
                            item.pos_id,
                            item.pos_name,
                            item.pos_business_category,
                            posPhones,
                            posAddress,
                            btnFestive,
                            btnUsdMenu,
                            btnMenuLink,
                            `<button type="button" class="btn btn-sm btn-indigo"
                                     onclick='jsEditData(${JSON.stringify(item)})'>
                                 <i class="ph-pencil-simple-line me-1"></i> ${translate.edit}
                             </button>`,
                        ];
                    }

                    // Unknown location — log and return null row so DataTables
                    // skips it cleanly rather than receiving undefined
                    console.warn(`listDataToDatatable: unhandled currentLocation "${currentLocation}" for pos_id ${item.pos_id}`);
                    return null;

                }).filter(row => row !== null); // strip any unhandled rows

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

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

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

            tbBranchesList.clear().draw();

        } else {

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

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

    } finally {
        resetSearchButton();
    }
}

// Enable or disable status
async function jsSwitchUsdInOnlineMenu(pos_id, status, thisSwitcher, switcher) {

    let props = {
        pos_id: pos_id,
        status: status,
        csrf_token: csrf_token
    }

    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(async function (result) {
        if (result.value) {

            try {

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

                const res = JSON.parse(response);

                if (res.status == "success") {
                    fnSweetToast(res.message, res.status, 2500);
                    listDataToDatatable();
                }

            } catch (error) {
                console.error('Error:', error);
            }

        } else if (result.dismiss === swal.DismissReason.cancel) {
            if (switcher == 'checked') {
                thisSwitcher.checked = true;
            } else {
                thisSwitcher.checked = false;
            }
        }
    });
}

// Enable or disable status
async function jsSwitchFestiveMode(pos_id, status, thisSwitcher, switcher) {

    let props = {
        pos_id: pos_id,
        status: status,
        csrf_token: csrf_token
    }

    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(async function (result) {
        if (result.value) {

            try {

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

                const res = JSON.parse(response);

                if (res.status == "success") {
                    fnSweetToast(res.message, res.status, 2500);
                    listDataToDatatable();
                }

            } catch (error) {
                console.error('Error:', error);
            }

        } else if (result.dismiss === swal.DismissReason.cancel) {
            if (switcher == 'checked') {
                thisSwitcher.checked = true;
            } else {
                thisSwitcher.checked = false;
            }
        }
    });
}


// Enable or disable status
async function jsSwitchOnlineMenuAccess(pos_id, status, thisSwitcher, switcher) {

    let props = {
        pos_id: pos_id,
        status: status,
        csrf_token: csrf_token
    }

    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(async function (result) {
        if (result.value) {

            try {

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

                const res = JSON.parse(response);

                if (res.status == "success") {
                    fnSweetToast(res.message, res.status, 2500);
                    listDataToDatatable();
                }

            } catch (error) {
                console.error('Error:', error);
            }

        } else if (result.dismiss === swal.DismissReason.cancel) {
            if (switcher == 'checked') {
                thisSwitcher.checked = true;
            } else {
                thisSwitcher.checked = false;
            }
        }
    });
}


// Enable or disable status
async function jsSwitchCashbackAccess(pos_id, status, thisSwitcher, switcher) {

    let props = {
        pos_id: pos_id,
        status: status,
        csrf_token: csrf_token
    }

    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(async function (result) {
        if (result.value) {

            try {

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

                const res = JSON.parse(response);

                if (res.status == "success") {
                    fnSweetToast(res.message, res.status, 2500);
                    listDataToDatatable();
                }

            } catch (error) {
                console.error('Error:', error);
            }

        } else if (result.dismiss === swal.DismissReason.cancel) {
            if (switcher == 'checked') {
                thisSwitcher.checked = true;
            } else {
                thisSwitcher.checked = false;
            }
        }
    });
}

// Enable or disable status
async function jsSwitchStatus(pos_id, status, thisSwitcher, switcher) {

    let props = {
        pos_id: pos_id,
        status: status,
        csrf_token: csrf_token
    }

    let text = translate.confirm_that_you_want_to_disable_this_account;
    if (status == 'Enabled') text = translate.confirm_that_you_want_to_enable_this_account;

    swalInit.fire({
        title: translate.are_you_sure,
        text: 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/branches.ajax.php?op=ajaxSwitchStatus",
                    data: props,
                });

                const res = JSON.parse(response);

                if (res.status == "success") {
                    fnSweetToast(res.message, res.status, 2500);
                    listDataToDatatable();
                }

            } catch (error) {
                console.error('Error:', error);
            }

        } else if (result.dismiss === swal.DismissReason.cancel) {
            if (switcher == 'checked') {
                thisSwitcher.checked = true;
            } else {
                thisSwitcher.checked = false;
            }
        }
    });
}

// Enable or disable status
async function jsSwitchShowStatus(pos_id, status, thisSwitcher, switcher) {

    let props = {
        pos_id: pos_id,
        status: status,
        csrf_token: csrf_token
    }

    let text = translate.confirm_that_you_want_to_disable_this_account;
    if (status == 'Enabled') text = translate.confirm_that_you_want_to_enable_this_account;

    swalInit.fire({
        title: translate.are_you_sure,
        text: 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/branches.ajax.php?op=ajaxSwitchShowStatus",
                    data: props,
                });

                const res = JSON.parse(response);

                if (res.status == "success") {
                    fnSweetToast(res.message, res.status, 2500);
                    listDataToDatatable();
                }

            } catch (error) {
                console.error('Error:', error);
            }

        } else if (result.dismiss === swal.DismissReason.cancel) {
            if (switcher == 'checked') {
                thisSwitcher.checked = true;
            } else {
                thisSwitcher.checked = false;
            }
        }
    });
}


// Edit enterprise function
function jsEditData(data) {

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

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

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

    if (data.pos_business_category == 'Restaurant' || data.pos_business_category == 'Nightclub') {
        $(".divLegalTipping").show();
    } else {
        $(".divLegalTipping").hide();
    }

    $("#pos_ent_id").val(data.pos_ent_id);
    $("#pos_id").val(data.pos_id);
    $("#pos_name").val(data.pos_name);
    $("#pos_business_category").val(data.pos_business_category).trigger('change');
    $("#pos_address").val(data.pos_address);
    $("#pos_city").val(data.pos_city);
    $("#pos_state").val(data.pos_state);
    $("#pos_zip_code").val(data.pos_zip_code);
    $("#pos_country").val(data.pos_country).trigger('change');
    $("#pos_currency").val(data.pos_currency).trigger('change');
    $("#pos_time_zone").val(data.pos_time_zone).trigger('change');
    // $("#pos_phone").val(data.pos_phone);
    // $("#pos_phone2").val(data.pos_phone2);

    let fullPhone = data.pos_phone.replace(/[\s\-\_\(\)\.]/g, "");
    let fullPhone2 = data.pos_phone2.replace(/[\s\-\_\(\)\.]/g, "");

    intlPhoneFormat.setNumber(fullPhone);
    intlPhoneFormat2.setNumber(fullPhone2);

    $("#pos_usd_exchange_rate").val(data.pos_usd_exchange_rate);
    $("#pos_tax").val(data.pos_tax);
    $("#pos_legal_tipping").val(data.pos_legal_tipping);
    $("#pos_lang").val(data.pos_lang).trigger('change');
    $("#pos_ticket_footer").val(data.pos_ticket_footer);

    $(".cashbackConfiguration").hide();
    if (data.pos_cash_back_status == 'On') {
        $(".cashbackConfiguration").show();
    }

    $("#pos_cash_back_percentage").val(data.pos_cash_back_percentage);
    $("#pos_cash_back_availability_days").val(data.pos_cash_back_availability_days);
    $("#pos_cash_back_expiration_days").val(data.pos_cash_back_expiration_days);

    $("#branch-modal").modal("show");
}

// Validation input form
function validateInputFormData(type) {

    if (type == "edit") {

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

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

    var pos_ent_id = $("#pos_ent_id").val();
    var pos_name = $("#pos_name").val();
    var pos_address = $("#pos_address").val();
    var pos_phone = $("#pos_phone").val();

    if ($.trim(pos_ent_id) === '' || pos_ent_id === null || pos_ent_id <= 0) {
        fnSweetToast(translate.select_an_enterprise, "warning", 1000);
        return false;
    }

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

    if ($.trim(pos_address) == '') {
        $("#pos_address").css("border", "1px solid red ");
        fnSweetToast(translate.you_must_enter_the_address, "error");
        return false;
    } else {
        $("#pos_address").css("border", "1px solid #d1d5db ");
    }

    if ($.trim(pos_phone) == '') {
        $("#pos_phone").css("border", "1px solid red ");
        fnSweetToast(translate.you_must_enter_the_phone_number, "error");
        return false;
    } else {
        $("#pos_phone").css("border", "1px solid #495057 ");
    }

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

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


// Save enterprise function
$(document).on("click", ".btnSave", function () {
    if (validateInputFormData("save") == false) {
        return false;
    } else {
        fnSaveUpdate();
    }
});

// Save enterprise function
$(document).on("click", ".btnEdit", function () {
    if (validateInputFormData("edit") == false) {
        return false;
    } else {
        fnSaveUpdate();
    }
});

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

// Save and Edit enterprise function
async function fnSaveUpdate() {

    setButtonStatus('loading');

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

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

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

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

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

            setButtonStatus('ready')

            document.getElementById("frmBranch").reset();
            fnSweetAlert(data.message, "", data.status, 1500);
            $("#branch-modal").modal("hide");
            listDataToDatatable();

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

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

$(document).on("change", "#pos_cash_back_percentage", function () {
    if ($(this).val() <= 0) $(this).val(0);
});

$(document).on("change", "#pos_cash_back_availability_days", function () {
    if ($(this).val() < 0) $(this).val(0);
});

$(document).on("change", "#pos_cash_back_expiration_days", function () {
    if ($(this).val() <= 7) $(this).val(8);
});


// International Phone Number Validation
const intellinput = document.querySelector(".intelli-phone");

const intlPhoneFormat = window.intlTelInput(intellinput, {
    initialCountry: "auto",
    geoIpLookup: callback => {
        fetch("https://ipapi.co/json")
            .then(res => res.json())
            .then(data => callback(data.country_code))
            .catch(() => callback("us"));
    },
    strictMode: true,
    autoPlaceholder: true,
    formatAsYouType: true,
    formatOnDisplay: true,
    nationalMode: false,
    hiddenInput: () => ({ phone: "full_phone", country: "country_code" }),
    loadUtilsOnInit: "../intlTelInput/utils.js", // just for formatting/placeholders etc
    // loadUtilsOnInit: "https://cdn.jsdelivr.net/npm/intl-tel-input@24.6.0/build/js/utils.js",
});


var productSearchTimeId = null;
$(".intelli-phone").keyup(function (e) {

    if (productSearchTimeId) {
        clearTimeout(productSearchTimeId);
    }

    if (!intlPhoneFormat.isValidNumber()) {
        // console.log("Invalid number. Please try again.");
        return false;
    }
    // Get the formatted phone number
    const fullPhone = intlPhoneFormat.getNumber();

    // Get the hidden input value
    productSearchTimeId = setTimeout(() => {
        if (fullPhone) {
            // console.log(`fullPhone: ${fullPhone}`);
            intlPhoneFormat.setNumber(fullPhone);
        }
    }, 100);

});

// International Phone Number Validation
const intellinput2 = document.querySelector(".intelli-phone-2");

const intlPhoneFormat2 = window.intlTelInput(intellinput2, {
    initialCountry: "auto",
    geoIpLookup: callback => {
        fetch("https://ipapi.co/json")
            .then(res => res.json())
            .then(data => callback(data.country_code))
            .catch(() => callback("us"));
    },
    strictMode: true,
    autoPlaceholder: true,
    formatAsYouType: true,
    formatOnDisplay: true,
    nationalMode: false,
    hiddenInput: () => ({ phone: "full_phone", country: "country_code" }),
    loadUtilsOnInit: "../intlTelInput/utils.js", // just for formatting/placeholders etc
    // loadUtilsOnInit: "https://cdn.jsdelivr.net/npm/intl-tel-input@24.6.0/build/js/utils.js",
});


var productSearchTimeId = null;
$(".intelli-phone-2").keyup(function (e) {

    if (productSearchTimeId) {
        clearTimeout(productSearchTimeId);
    }

    if (!intlPhoneFormat2.isValidNumber()) {
        // console.log("Invalid number. Please try again.");
        return false;
    }
    // Get the formatted phone number
    const fullPhone = intlPhoneFormat2.getNumber();

    // Get the hidden input value
    productSearchTimeId = setTimeout(() => {
        if (fullPhone) {
            // console.log(`fullPhone: ${fullPhone}`);
            intlPhoneFormat.setNumber(fullPhone);
        }
    }, 100);

});