"use strict";
$(document).ready(function() {
    let companyLogo = document.getElementById('company_logo');
    if(companyLogo){
        companyLogo.onchange = evt => {
            const [file] = companyLogo.files
            let previewImage = document.getElementById('previewLogo')
            if (file) {
                previewImage.src = URL.createObjectURL(file)
            }
        }
    }

    if ($(".first_name").length) {
        document.querySelector(".first_name").addEventListener("input", (event) => {
            const input = event.target;
            input.value = input.value.charAt(0).toUpperCase() + input.value.slice(1).toLowerCase();
        });
    }
    if ($(".last_name").length) {
        document.querySelector(".last_name").addEventListener("input", (event) => {
            const input = event.target;
            input.value = input.value.charAt(0).toUpperCase() + input.value.slice(1).toLowerCase();
        });
    }

    $("body").tooltip({ selector: '[data-toggle=tooltip]' });

    if(typeof selectedCountryId != "undefined" && selectedCountryId != '') {
        get_state_dropdown(selectedStateId,selectedCountryId,'#state_id');
    }

    $(".tab-pane").removeClass('active show');
    $(".nav li:first a").addClass('active show');
    $(".tab-content div:first").addClass('active show');
    var hash = window.location.hash;
    if (hash != '') {
        if(hash == "#change_email"){
            $('.change-email-section').show();
            $('.personal-info-section').hide();
        } else if(hash == "#profile_information"){
            $('.change-email-section').hide();
            $('.personal-info-section').show();
        } else{
            $(".tab-pane").removeClass('active show');
            $(hash).addClass('active show');

            $(".nav-link").removeClass('active show');
            $("a[href='" + hash + "']").addClass('active show');
        }

    }
});
function copySponsorLink(text) {
    if (navigator.clipboard) {
        navigator.clipboard.writeText(text).then(function() {
            swalMsg('Copied!','success');
        }).catch(function(err) {
            fallbackCopyText(text);
        });
    } else {
        fallbackCopyText(text);
    }
}

function fallbackCopyText(text) {
    const tempInput = document.createElement("textarea");
    tempInput.value = text;
    document.body.appendChild(tempInput);
    tempInput.select();
    document.execCommand("copy");
    document.body.removeChild(tempInput);
}

$(document).on("click",".nav-link",function (e) {
    var navLink = $(this).attr("href");
    if(navLink == "#change_email"){
        $('.change-email-section').show();
        $('.personal-info-section').hide();
    } else if(navLink == "#profile_information"){
        $('.personal-info-section').show();
        $('.change-email-section').hide();
    }
    window.location.hash = $(this).attr("href");
    e.preventDefault();
})

$(document).on("click",".back-to-profile",function (e) {
        $('.personal-info-section').show();
        $('.change-email-section').hide();
        $('html, body').animate({ scrollTop: 0 }, 'fast');
})

let oldProfileData = '';
$(document).ready(function () {
    setTimeout(function () {
        oldProfileData =  new FormData($('#formProfile')[0]);
    }, 300);
    $('#add_transfer_address').on('click', function () {
        if (readOnlyMode) {
            swalMsg('Feature disabled whilst in switched user mode.','warning');
            return false;
        }
        $('#addTransferAddress').modal('show');
    });
});

$(document).on("submit", "#formProfile", function (event) {
    event.preventDefault();
    let url = $(this).attr("action");
    let formData = $(this)[0];
    let data = new FormData(formData);
    let formId = $(this).attr("id");
    let submitBtn = $("#formProfile #submitBtn");
    var checkBoxChecked = $("input[name='is_business_account']:checked").val() ? "1" : "0";
    let popupMsg = '';
    let needToDropKyc = false;

    // Compare Fields
    const fieldsToCheck = ['first_name', 'last_name', 'day', 'month', 'year', 'address_1', 'country_id', 'state_id', 'city', 'postal_code'];
    for (let field of fieldsToCheck) {
        const oldVal = (oldProfileData.get(field) || '').toLowerCase().trim();
        const newVal = (data.get(field) || '').toLowerCase().trim();
        if (oldVal !== newVal) {
            needToDropKyc = true;
        }
    }

    if(memberKycStatus == 'active' && needToDropKyc){
        popupMsg = 'Are you sure you want to update your profile?<br>Updating your profile will also update your KYC/KYB identity details and drop your KYC/KYB.';
    } else{
        popupMsg = 'Are you sure you want to update your profile?';
    }
    showConfirmationModal( 'Profile Update' , `${popupMsg}` , renderIconTag('confirmyes')+'Yes', function() {
        $.ajax({
            url: url,
            type: "POST",
            data: data,
            headers: {
                "X-CSRF-TOKEN": $('meta[name="csrf-token"]').attr("content"),
            },
            contentType: false,
            processData: false,
            beforeSend: function () {
                submitBtn.prop("disabled", true);
                submitBtn.html(`<i class="fa fa-spinner fa-spin"></i>&nbsp;&nbsp;${translate("loading")}...`);
            },
            success: function (response) {
                submitBtn.prop("disabled", false);
                submitBtn.html(renderIconTag('update')+translate("Update"));
                $(".error").text(""); // remove old errors
                $("#old_password,#password,#password_confirmation").val("");
                if(response.success){
                    oldProfileData = data;
                    swalMsg(response.message,'success');
                    if(checkBoxChecked == 1){
                        $("a[href='#company_information']").closest('.nav-item').show();
                    }else{
                        $("a[href='#company_information']").closest('.nav-item').hide();
                    }
                }
                getHeaderDateTime();
            },
            error: function (jqXHR, textStatus, errorThrown) {
                if (globalErrorHandler(jqXHR.responseJSON)) return false;
                submitBtn.attr("disabled", false);
                submitBtn.html(renderIconTag('update')+translate("Update"));
                if (jqXHR.responseJSON && jqXHR.responseJSON.errors) {
                    $("#" + formId + " .error").text("");
                    for (const key in jqXHR.responseJSON.errors) {
                        if ($("#formProfile ." + key + "_error")) {
                            $("#formProfile ." + key + "_error").text(
                                jqXHR.responseJSON.errors[key]
                            );
                        }
                    }
                }
            },
        });
    }, renderIconTag('cancel')+'No');
});

$(document).on("submit", "#company_information_form", function (event) {
    event.preventDefault();
    let url = $(this).attr("action");
    let formData = $(this)[0];
    let data = new FormData(formData);

    let formId = $(this).attr("id");
    let submitBtn = $("#company_information_form .submitBtn");
    $.ajax({
        url: url,
        type: "POST",
        data: data,
        headers: {
            "X-CSRF-TOKEN": $('meta[name="csrf-token"]').attr("content"),
        },
        contentType: false,
        processData: false,
        beforeSend: function () {
            submitBtn.prop("disabled", true);
            submitBtn.html(`<i class="fa fa-spinner fa-spin"></i>&nbsp;&nbsp;${translate("loading")}...`);
        },
        success: function (response) {
            submitBtn.prop("disabled", false);
            submitBtn.html(renderIconTag('update')+translate("Update"));
            $('#company_logo').val('');
            $(".error").text(""); // remove old errors
            swalMsg(response.message,'success');
            if(response.status){
                bsAlert('dark');
                $('#company_url').attr('readonly', true);
                $('#company_logo').attr('disabled', true);
            }
        },
        error: function (jqXHR, textStatus, errorThrown) {
            if (globalErrorHandler(jqXHR.responseJSON)) return false;
            submitBtn.attr("disabled", false);
            submitBtn.html(renderIconTag('update')+translate("Update"));
            if (jqXHR.responseJSON && jqXHR.responseJSON.errors) {
                $("#" + formId + " .error").text("");
                for (const key in jqXHR.responseJSON.errors) {
                    if ($("#company_information_form ." + key + "_error")) {
                        $("#company_information_form ." + key + "_error").text(
                            jqXHR.responseJSON.errors[key]
                        );
                    }
                }
            }
        },
    });
});

$(document).on("click", ".company-btn-close", function () {
    $(this).closest(".alert").alert('close');
});

function bsAlert(type) {
    $('#liveAlertPlaceholder').html('');
    let wrapper = document.createElement('div')
    let alertPlaceholder = document.getElementById('liveAlertPlaceholder');
    wrapper.innerHTML = `<div class="alert alert-${type} alert-dismissible" role="alert">
    <b>The review of your logo and URL is in progress.</b>
    <p>Please allow up to 7 days for approval and check back periodically.</p>
   <button type="button" class="btn-close company-btn-close" data-bs-dismiss="alert" aria-label="Close"  data-placement="top" ></button>`
    alertPlaceholder.append(wrapper)
}

$(document).ready(function () {
    //for change email checkbox
    $('#has_old_email_access').on('change', function () {
        if ($(this).is(':checked')) {
            $('#formChangeEmail #firstSubmitBtn').hide();
            $('#formChangeEmail #nextEmailChangeBtn').show();
        } else {
            $('#formChangeEmail #firstSubmitBtn').show();
            $('#formChangeEmail #nextEmailChangeBtn').hide();
        }
    });
    //for change email link
    $('.change_email_link').on('click', function () {
        $('.change-email-section').show();
        $('.personal-info-section').hide();
    });
});

$(document).on("click", "#formChangeEmail #nextEmailChangeBtn", function () {
    let newEmail = $("#new_email").val();
    let oldEmail = $("#old_email").val();
    let currentPassword = $("#current_password").val();
    let submitBtn = $('#formChangeEmail #nextEmailChangeBtn');
    let submitBtnHtml = submitBtn.html();

    var formData = new FormData();
    formData.append('new_email', newEmail);
    formData.append('current_password', currentPassword);
    $.ajax({
        url: baseURL + 'check-email-password',
        type: 'POST',
        data: formData,
        contentType: false,
        processData: false,
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        },
        beforeSend: function () {
            submitBtn.prop('disabled', true);
            submitBtn.html(`<i class="fa fa-spinner fa-spin"></i>&nbsp;&nbsp;${translate("loading")}...`);
        },
        success: function (response) {
            if (response.status == true) {
                submitBtn.prop('disabled', false);
                submitBtn.html(submitBtnHtml);
                $('.new_email').text(newEmail);
                $('#formChangeEmail .change_email_section').hide();
                $('#formChangeEmail .upload_image_section').show();
            }
        },
        error: function (jqXHR, textStatus, errorThrown) {
            if (globalErrorHandler(jqXHR.responseJSON)) return false;
            submitBtn.attr("disabled", false);
            submitBtn.html(renderIconTag('next')+translate("Next"));
            if (jqXHR.responseJSON && jqXHR.responseJSON.errors) {
                $("#formChangeEmail .error").text("");
                for (const key in jqXHR.responseJSON.errors) {
                    if ($("#formChangeEmail ." + key + "_error")) {
                        $("#formChangeEmail ." + key + "_error").text(
                            jqXHR.responseJSON.errors[key]
                        );
                    }
                }
            }
        },
    });
});

$(document).on("click", "#formChangeEmail #prevEmailChangeBtn", function () {
    $('#formChangeEmail .change_email_section').show();
    $('#formChangeEmail .upload_image_section').hide();
});

$(document).on("submit", "#formChangeEmail", function (event) {
    event.preventDefault();
    $(".error").text(""); // remove old errors
    let url = $(this).attr("action");
    let formData = $(this)[0];
    let data = new FormData(formData);
    let formId = $(this).attr("id");
    let submitBtn = $("#formChangeEmail button[type='submit']");
    let saveBtnText = submitBtn.html();

    $.ajax({
        url: url,
        type: "POST",
        data: data,
        headers: {
            "X-CSRF-TOKEN": $('meta[name="csrf-token"]').attr("content"),
        },
        contentType: false,
        processData: false,
        beforeSend: function () {
            submitBtn.prop("disabled", true);
            submitBtn.html(`<i class="fa fa-spinner fa-spin"></i>&nbsp;&nbsp;${translate("loading")}...`);
            $('#formChangeEmail #prevEmailChangeBtn').prop('disabled',true);
        },
        success: function (response) {
            submitBtn.prop("disabled", false);
            submitBtn.html(saveBtnText);
            $('#formChangeEmail #prevEmailChangeBtn').prop('disabled',false);
            if (response.status) {
                if(response.resend_link == false){
                    $('#resendLinkBtn').hide();
                    $('#verification_send_email_section').hide();
                    $('#verification_ticket_email_section').show();
                    $('#verification_send_email_admin_section').hide();
                } else{
                    $('#resendLinkBtn').show();
                    $('#verification_send_email_section').show();
                    $('#verification_ticket_email_section').hide();
                    $('#verification_send_email_admin_section').hide();
                }
                $('.change_email_form').hide();
                $('.change_email_table').show();
                $('.new_email').text(response.new_email);
                swalMsg(response.message,'success');
            } else {
                swalMsg(response.message,'error');
            }
        },
        error: function (jqXHR, textStatus, errorThrown) {
            if (globalErrorHandler(jqXHR.responseJSON)) return false;
            submitBtn.attr("disabled", false);
            submitBtn.html(saveBtnText);
            $('#formChangeEmail #prevEmailChangeBtn').prop('disabled',false);
            if (jqXHR.responseJSON && jqXHR.responseJSON.errors) {
                $("#formChangeEmail .error").text("");
                for (const key in jqXHR.responseJSON.errors) {

                    if ($("#formChangeEmail ." + key + "_error")) {
                        $("#formChangeEmail ." + key + "_error").text(
                            jqXHR.responseJSON.errors[key]
                        );
                    }
                }
            }
        },
    });
});

$(document).on("click", "#resendLinkBtn", function (e) {
    let submitBtn = $("#resendLinkBtn");
    let saveBtnText = submitBtn.html();
    e.preventDefault();
    $.ajax({
        url: baseURL+'profile/change-email/resend-link',
        type: "GET",
        headers: {
            "X-CSRF-TOKEN": $('meta[name="csrf-token"]').attr("content"),
        },
        beforeSend: function() {
            submitBtn.attr("disabled", true).html(`<i class="fa fa-spinner fa-spin"></i>&nbsp;&nbsp;${translate("loading")}...`);
        },
        success: function(response) {
            submitBtn.attr("disabled", false).html(saveBtnText);
            if (response.status) {
                $('.change_email_form').hide();
                $('.change_email_table').show();
                $('.new_email').text(response.new_email);
                swalMsg(response.message,'success');
            }
        },
        complete: function() {
            submitBtn.attr("disabled", false).html(saveBtnText);
        }
    });
});

$(document).on("click", "#cancelLinkBtn", function (e) {
    let submitBtn = $("#cancelLinkBtn");
    let saveBtnText = submitBtn.html();
    e.preventDefault();
    $.ajax({
        url: baseURL+'profile/change-email/request-cancel',
        type: "GET",
        headers: {
            "X-CSRF-TOKEN": $('meta[name="csrf-token"]').attr("content"),
        },
        beforeSend: function() {
            submitBtn.attr("disabled", true).html(`<i class="fa fa-spinner fa-spin"></i>&nbsp;&nbsp;${translate("loading")}...`);
        },
        success: function(response) {
            submitBtn.attr("disabled", false).html(saveBtnText);
            if (response.status) {
                $('.change_email_form').show();
                $('.change_email_section').show();
                $('.upload_image_section').hide();
                $('.change_email_table').hide();
                $('.new_email').text('');
                $('input[name="new_email"]').val('');
                $('input[name="current_password"]').val('');
                swalMsg(response.message,'success');
            } else{
                swalMsg(response.message,'fail');
            }
        },
        complete: function() {
            submitBtn.attr("disabled", false).html(saveBtnText);
        }
    });
});

$(document).on("submit", "#formChangePassword", function (event) {
    event.preventDefault();
    let url = $(this).attr("action");
    let formData = $(this)[0];
    let data = new FormData(formData);
    let formId = $(this).attr("id");
    let submitBtn = $("#formChangePassword #submitBtn");
    $.ajax({
        url: url,
        type: "POST",
        data: data,
        headers: {
            "X-CSRF-TOKEN": $('meta[name="csrf-token"]').attr("content"),
        },
        contentType: false,
        processData: false,
        beforeSend: function () {
            submitBtn.prop("disabled", true);
            submitBtn.html(`<i class="fa fa-spinner fa-spin"></i>&nbsp;&nbsp;${translate("loading")}...`);
        },
        success: function (response) {
            submitBtn.prop("disabled", false);
            submitBtn.html(renderIconTag('save')+translate("Change"));
            $(".error").text(""); // remove old errors
            if (response.status) {
                $("#formChangePassword")[0].reset();
                $('.success_message_password').html('<i class="fa fa-check verified-icon float-right mt-1 me-2 fs-6"></i><span>'+response.message+'</span>');
            } else {
                swalMsg(response.message,'error');
            }
        },
        error: function (jqXHR, textStatus, errorThrown) {
            if (globalErrorHandler(jqXHR.responseJSON)) return false;
            submitBtn.attr("disabled", false);
            submitBtn.html(renderIconTag('update')+translate("Update"));
            if (jqXHR.responseJSON && jqXHR.responseJSON.errors) {
                $("#" + formId + " .error").text("");
                for (const key in jqXHR.responseJSON.errors) {
                    if ($("#formChangePassword ." + key + "_error")) {
                        $("#formChangePassword ." + key + "_error").text(
                            jqXHR.responseJSON.errors[key]
                        );
                    }
                }
            }
        },
    });
});

$(document).on("submit", "#formChangeTransactionPassword", function (event) {
    event.preventDefault();
    let url = $(this).attr("action");
    let formData = $(this)[0];
    let data = new FormData(formData);
    let formId = $(this).attr("id");
    let submitBtn = $("#formChangeTransactionPassword #submitBtn");
    $.ajax({
        url: url,
        type: "POST",
        data: data,
        headers: {
            "X-CSRF-TOKEN": $('meta[name="csrf-token"]').attr("content"),
        },
        contentType: false,
        processData: false,
        beforeSend: function () {
            submitBtn.prop("disabled", true);
            submitBtn.html(`<i class="fa fa-spinner fa-spin"></i>&nbsp;&nbsp;${translate("loading")}...`);
        },
        success: function (response) {
            submitBtn.prop("disabled", false);
            submitBtn.html(renderIconTag('update')+translate("Update"));
            $(".error").text(""); // remove old errors
            if (response.status) {
                if (typeof response.reload_screen != 'undefined'){
                    window.location.reload();
                } else {
                    $("#formChangeTransactionPassword")[0].reset();
                    swalMsg(response.message, 'success');
                }
            } else {
                swalMsg(response.message,'error');
            }
        },
        error: function (jqXHR, textStatus, errorThrown) {
            if (globalErrorHandler(jqXHR.responseJSON)) return false;
            submitBtn.attr("disabled", false);
            submitBtn.html(renderIconTag('update')+translate("Update"));
            if (jqXHR.responseJSON && jqXHR.responseJSON.errors) {
                $("#" + formId + " .error").text("");
                for (const key in jqXHR.responseJSON.errors) {
                    if ($("#formChangeTransactionPassword ." + key + "_error")) {
                        $("#formChangeTransactionPassword ." + key + "_error").text(
                            jqXHR.responseJSON.errors[key]
                        );
                    }
                }
            }
        },
    });
});

var showOtpVerifyBtn = true;
function showOtpSaveBtn(){
    if (showOtpVerifyBtn) {
        $("#formOneTimePasscode #submitBtn").show();
    }
}

function OneTimePasscodeView(){
    $.ajax({
        url: baseURL+'profile/one-time-passcode/index',
        type: "GET",
        headers: {
            "X-CSRF-TOKEN": $('meta[name="csrf-token"]').attr("content"),
        },
        success: function(response) {
            if (response.status) {
                $('.one-time-passcode').html(response.htmlContent);
                showOtpVerifyBtn = true;
                reSetupOtpInputsFocus('formOneTimePasscode');
            }
        }
    });
}

$(document).on("click", "#cancelOneTimePasscodeBtn", function (event) {
    event.preventDefault();
    let submitBtn = $("#formOneTimePasscode #submitBtn");
    let saveBtnText = submitBtn.html();
    $(this).html(`<i class="fa fa-spinner fa-spin"></i>&nbsp;&nbsp;${translate("loading")}...`).attr("disabled", true);
    OneTimePasscodeView();

});

$(document).on("click", "#disabledOneTimePasscodeBtn", function (event) {
    $("#formOneTimePasscode #submitBtn").hide();
    $("#formOneTimePasscode #inputDiv").remove();
    $(this).remove();
    $('#cancelOneTimePasscodeBtn').show();
    $("#formOneTimePasscode #otpDiv").show();
    $("#formOneTimePasscode").submit();
    stopResendOtpTimer();
});

$(document).on('keyup', '#formOneTimePasscode .threeFaOtpInput', function(e) {
    var closestForm = $(this).closest('#formOneTimePasscode');
    var inputName = $(this).attr('name');

    // Find the input element with the same name inside the closest form
    var inputElements = closestForm.find('input[name="' + inputName + '"]');


    // Check if all 6 input fields have values
    var allFilled = inputElements.toArray().every(function(input) {
        return $(input).val() !== ''; // Check if each input has a non-empty value
    });

    // If all inputs have values, submit the form
    if (allFilled) {
        $('#formOneTimePasscode #submitBtn').trigger('click');
    }
});

function loadingMy3faInputs(flag='show',formId,error=false){
    $(".threeFaOtpInput").removeClass('invalid-input');
    if (flag=='show'){
        $("#" + formId + " .authLoader").show();
        $("#"+formId+" .threeFaOtpInput").attr('readonly',true);
    } else {
        $("#"+formId+" .authLoader").hide();
        $("#"+formId+" .threeFaOtpInput").attr('readonly',false).val('');
        $("#"+formId+" .threeFaOtpInput").first().focus();
    }

    if (error){
        $("#"+formId+" .threeFaOtpInput").addClass('invalid-input');
    }
}

$(document).on("submit", "#formOneTimePasscode", function (event) {
    showOtpVerifyBtn = false;
    event.preventDefault();
    let url = $(this).attr("action");
    let formData = $(this)[0];
    let data = new FormData(formData);
    let formId = $(this).attr("id");
    let submitBtn = $("#formOneTimePasscode #submitBtn");
    let submitTextBtn = $("#formOneTimePasscode #submitBtn").text();
    $.ajax({
        url: url,
        type: "POST",
        data: data,
        headers: {
            "X-CSRF-TOKEN": $('meta[name="csrf-token"]').attr("content"),
        },
        contentType: false,
        processData: false,
        beforeSend: function () {
            submitBtn.html(`<i class="fa fa-spinner fa-spin"></i>&nbsp;&nbsp;${translate("loading")}...`).prop("disabled", true);
            loadingMy3faInputs('show','formOneTimePasscode');
        },
        success: function (response) {
            submitBtn.text(submitTextBtn).prop("disabled", false);
            $(".error").text(""); // remove old errors
            if (response.status) {
                stopResendOtpTimer();
                if (typeof response.reload_screen != 'undefined'){
                    swalMsg(response.message, 'success');
                    OneTimePasscodeView();
                } else if (typeof response.newRoute != "undefined") {
                    setTimeout(function () {
                        startResendOtpTimer();
                    },500);
                    $("#formOneTimePasscode").attr('action', response.newRoute);
                    $("#disabledOneTimePasscodeBtn").hide();
                    $("#cancelOneTimePasscodeBtn").show();
                    $("#formOneTimePasscode #otpDiv").show();
                    $("#formOneTimePasscode #submitBtn").hide();
                    swalMsg(response.message, 'success');
                    loadingMy3faInputs('hide','formOneTimePasscode');
                } else {
                    swalMsg(response.message, 'success');
                    loadingMy3faInputs('hide','formOneTimePasscode');
                }
            } else {
                swalMsg(response.message,'error');
                loadingMy3faInputs('hide','formOneTimePasscode',true);
            }
        },
        error: function (jqXHR, textStatus, errorThrown) {
            loadingMy3faInputs('hide','formOneTimePasscode',true);
            if (globalErrorHandler(jqXHR.responseJSON)) return false;
            submitBtn.html("Save").attr("disabled", false);
            if (jqXHR.responseJSON && jqXHR.responseJSON.errors) {
                $("#" + formId + " .error").text("");
                for (const key in jqXHR.responseJSON.errors) {
                    if ($("#formOneTimePasscode ." + key + "_error")) {
                        $("#formOneTimePasscode ." + key + "_error").text(
                            jqXHR.responseJSON.errors[key]
                        );
                    }
                }
            }
        },
    });
});

$(document).ready(function () {
    $(".select2").select2({
        tags: false,
    });

    $('#country_id').change(function() {
        var countryId = $(this).val();
        var phoneCode = $('#country_id option:selected').data('phone-code');

        if (phoneCode) {
            phoneCode = String(phoneCode); // Ensure phoneCode is a string
            $('.phone_code').text(phoneCode.startsWith('+') ? phoneCode : '+' + phoneCode);
            phoneCodeCssDynamic();
        } else {
            $('.phone_code').text('+1');
            phoneCodeCssDynamic();
        }

        if (countryId) {
            get_state_dropdown('', countryId, "#state_id")
        } else {
            $('#state_id').html('<option value="">Select Region / State / Province</option>');
        }
    });
});

function get_state_dropdown(selected_id,country_id,target_dropdown_id) {
    $.ajax({
        url: baseURL+'get-state',
        type: 'POST',
        data: {
            'country_id' : country_id,
            'selected_id' : selected_id,
        },
        headers: { 'X-CSRF-Token' : $('meta[name="csrf-token"]').attr('content') },
        success: function (response) {
            if(response.count > 0){
                $('.state-input').show();
            }else{
                $('.state-input').hide();
            }
            $(target_dropdown_id).html(response.html);
        },
        error: function () {
        }
    });
}

$(document).ready(function () {
    phoneCodeCssDynamic();
});

function phoneCodeCssDynamic(){
    const $span = $('.phone_code');
    const spanWidth = $span.outerWidth();
    const extraSpacing = 2;
    $('label[for="phone"]').css('margin-left', spanWidth + extraSpacing + 'px');
}
