function open_frm_tab(evt, cityName) {
    var entity_id_select = jQuery('.entity_id_select').val();
    var assigned_company_id = jQuery('.assigned_company_id').val();
    if (entity_id_select == '' || assigned_company_id == '') {
        jQuery('.tablinks1').removeClass('active');
        jQuery('#Mapping').hide();
        jQuery('.tablinks2').addClass('active');
        jQuery('#Settings').show();
        if (entity_id_select == '') {
            jQuery('.entity_id_select').attr('style', 'border-color:red');
        }
        if (assigned_company_id == '') {
            jQuery('.assigned_company_id').attr('style', 'border-color:red');
        }
        setTimeout(function () {
            jQuery('.assigned_company_id').attr('style', '');
            jQuery('.entity_id_select').attr('style', '');
        }, 2000);
        return '';
    }
    var i, tabcontent, tablinks;
    tabcontent = document.getElementsByClassName("tabcontent");
    for (i = 0; i < tabcontent.length; i++) {
        tabcontent[i].style.display = "none";
    }
    tablinks = document.getElementsByClassName("tablinks");
    for (i = 0; i < tablinks.length; i++) {
        tablinks[i].className = tablinks[i].className.replace(" active", "");
    }
    document.getElementById(cityName).style.display = "block";
    evt.currentTarget.className += " active";
    var url = new URL(window.location);
    if (cityName == 'Settings') {
        url.searchParams.set('tab', '1');
        window.history.pushState({}, '', url);

    } else {
        url.searchParams.delete('tab');
        window.history.pushState({}, '', url);
    }
}
function kopiereText(id) {
    var textarea = document.getElementById(id);
    textarea.select();
    textarea.setSelectionRange(0, 99999); // Für mobile Geräte
    navigator.clipboard.writeText(textarea.value)
            .then(() => alert('Text wurde kopiert: ' + textarea.value))
            .catch(err => console.error('Fehler beim Kopieren: ', err));
}
function selectAll() {
    jQuery("#select2 > option").prop("selected", true);
    jQuery("#select2").trigger("change");
}

function deselectAll() {
    jQuery("#select2 > option").prop("selected", false);
    jQuery("#select2").trigger("change");
}
jQuery(function ($) {

    setTimeout(function () {
        jQuery('.brainx_success-toast').removeClass('shownow');
    }, 2000);
    var entity_id = jQuery('select[name="entity_id"]').val();
    const url = new URL(window.location);
    const hasTab = url.searchParams.has('tab');
    if (entity_id && entity_id > 0) {
        var selectedText = jQuery('select[name="entity_id"] option:selected').text();
        jQuery('.modulename').html(selectedText);
        if (hasTab) {
            jQuery('.tablinks2').addClass('active');
            jQuery('#Settings').show();
        } else {
            jQuery('.tablinks1').addClass('active');
            jQuery('#Mapping').show();
        }
    } else {
        jQuery('.tablinks1').addClass('disabledtab');
        jQuery('.module_error').removeClass('hideit');
        jQuery('.tablinks2').addClass('active');
        jQuery('#Settings').show();
        const url = new URL(window.location);
        url.searchParams.set('tab', '1');
        window.history.pushState({}, '', url);
    }
    setTimeout(function () {
        if (jQuery('.success_messageremove').length > 0) {
            jQuery('.success_messageremove').remove();
        }
    }, 2000);

    if (jQuery('.entity_id_select').length > 0) {
        var entity_id_select = jQuery('.entity_id_select').val();
        var assigned_company_id = jQuery('.assigned_company_id').val();
        if (entity_id_select == '' || assigned_company_id == '') {
            jQuery('.tablinks2').addClass('active');
            jQuery('#Settings').show();
            jQuery('.tablinks1').attr('style', 'pointer-events:none;');
        }
    }

    jQuery('.testconnectionbrainx').click(function () {
        var server_url = jQuery('input[name="server_url"]').val();
        var is_error = 0;
        if (server_url == '') {
            jQuery('input[name="server_url"]').addClass('inputerror');
            is_error = 1;
        }
        var server_username = jQuery('input[name="server_username"]').val();
        if (server_username == '') {
            jQuery('input[name="server_username"]').addClass('inputerror');
            is_error = 1;
        }
        var server_password = jQuery('input[name="server_password"]').val();
        if (server_password == '') {
            jQuery('input[name="server_password"]').addClass('inputerror');
            is_error = 1;
        }
        var brainxapp_pass = '';
        if (jQuery('#brainx_two_factor').is(':checked')) {
            brainxapp_pass = jQuery('input[name="brainxapp_pass"]').val();
            if (brainxapp_pass == '') {
                jQuery('input[name="brainxapp_pass"]').addClass('inputerror');
                is_error = 1;
            }
        }
        setTimeout(function () {
            jQuery('input').removeClass('inputerror');
        }, 3000);
        if (is_error == 0) {
            var nonce = brainxAdminData.nonce;
            var ajaxurl = brainxAdminData.ajaxurl;
            jQuery.ajax({
                url: ajaxurl,
                type: 'POST',
                dataType: 'json',
                data: {
                    action: 'brainx_api_connection_check',
                    server_url, server_username, server_password, brainxapp_pass, nonce
                },
                success: function (response) {
                    if (response.status == 0) {
                        jQuery('.api_success').hide();
                        jQuery('.api_error').html(response.message);
                        jQuery('.api_error').show();
                    } else {
                        jQuery('.api_success').show();
                        jQuery('.api_error').html('');
                        jQuery('.api_error').hide();
                    }
                    setTimeout(function () {
                        jQuery('.api_success').hide();
                        jQuery('.api_error').html('');
                        jQuery('.api_error').hide();
                    }, 3000);
                },
                error: function (xhr, status, error) {
                }
            });
        }
    });

    jQuery('#brainx_two_factor').change(function () {
        if (jQuery(this).is(':checked')) {
            jQuery('.twofa').attr('style', '');
        } else {
            jQuery('.twofa').attr('style', 'display:none;');
        }
    });

//    setTimeout(function () {
//        $('.success_message').removeClass('show');
//    }, 2000);
    var nonce = brainxAdminData.nonce;
    var ajaxurl = brainxAdminData.ajaxurl;
    jQuery(document).on('change', '.bx-switch-input', function () {

        var $this = jQuery(this);
        var parent = $this.closest('.bx-switch');
        var form_id = parent.attr('data-form-id');
        var type_form = $this.attr('data-form');

        // 🔥 sauberer Wert
        var checked_val = $this.is(':checked') ? 'Enable' : 'Disable';

        // 🔥 UI sofort updaten
        parent.find('.bx-switch-status').text(
                checked_val === 'Enable' ? 'Aktiv' : 'Inaktiv'
                );

        // 🔥 optional: visuelles Feedback (micro UX)
        parent.addClass('is-loading');

        jQuery.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'brainx_form_enable_disable',
                form_id: form_id,
                checked_val: checked_val,
                type_form: type_form,
                nonce: nonce
            },
            success: function () {
                jQuery('.success_message').show();

                setTimeout(function () {
                    jQuery('.success_message').fadeOut();
                }, 1500);
            },
            complete: function () {
                parent.removeClass('is-loading');
            }
        });

    });

    jQuery(function () {
        jQuery('#select2').select2({
            closeOnSelect: false
        });
    });

    const buttons = document.querySelectorAll('.tab-button');
    const contents = document.querySelectorAll('.tab-content');

    buttons.forEach(button => {
        button.addEventListener('click', () => {
            // Remove active class from all buttons
            buttons.forEach(btn => btn.classList.remove('active'));
            // Add active class to clicked button
            button.classList.add('active');

            // Hide all content divs
            contents.forEach(content => content.classList.remove('active'));
            // Show the corresponding content div
            const tabId = button.getAttribute('data-tab');
            document.getElementById(tabId).classList.add('active');
        });
    });
    jQuery(document).on('click', '.form_tab_div', function () {
        jQuery(this).closest('.field_wrap_custom').find('table').toggleClass('hide_show');
    });
});

document.addEventListener("DOMContentLoaded", function () {
    const inputFields = document.querySelectorAll(".custom-value");

    inputFields.forEach(inputField => {
        const parentDiv = inputField.closest(".droppable");

        function toggleClass() {
            if (inputField.value.trim() !== "") {
                parentDiv.classList.add("default_value");
            } else {
                parentDiv.classList.remove("default_value");
            }
        }

        inputField.addEventListener("input", toggleClass);
        toggleClass(); // Initial prüfen
    });
});

jQuery(function ($) {

    function verify_field_contains_id() {
        if ($('.api_enabled_fields_select').val()?.includes('account_id')) {
            jQuery('input[name="enable_org_creation"]').attr('checked', true);
        } else {
            jQuery('input[name="enable_org_creation"]').attr('checked', false);
        }
    }
    verify_field_contains_id();
    $(document).on('change', '.api_enabled_fields_select', function () {
        verify_field_contains_id();
    });


//    jQuery(document).on('change', 'input[name="enable_org_creation"]', function () {
//        if (jQuery(this).is(':checked')) {
//            let $select = jQuery('.api_enabled_fields_select');
//            let values = $select.val() || []; // get current selected values
//
//            // if "account_id" exists as option and not already selected, add it
//            if ($select.find('option[value="account_id"]').length && !values.includes('account_id')) {
//                values.push('account_id');
//                $select.val(values).trigger('change'); // refresh Select2
//            }
//        }
//    });

    if (jQuery('.entity_id_select').length > 0) {
        function showhidedata(val) {
            if (val == 4) {

            } else {
                jQuery('input[name="enable_org_creation"]').attr('checked', false);
            }
        }
        var current_entity_id = jQuery('input[name="current_entity_id"]').val();
        showhidedata(current_entity_id);
        jQuery(document).on('change', '.entity_id_select', function () {
            var vv = jQuery(this).val();
            showhidedata(vv);
        });
    }
});
