(function ($) {
    $.field_phonenumber = function (element, options) {
        var defaults = {
            list_country: [],
            input_name: ""
        }
        var plugin = this;
        
        plugin.settings = {}
        var $element = $(element), 
            element = element;
        plugin.init = function () {
            plugin.settings = $.extend({}, defaults, options);
            $element.find('.wrapper-phone-number input.countries').select2({
                formatResult: plugin.format,
                formatSelection: plugin.format,
                templateResult: function (data) {
                    let $result = "";
                    if (typeof data.id !== "undefined") {
                        $result = $(
                            `<div class="row">
                                <div class="col-md-3"><img src="${wpbookingpro_root_url_plugin}/admin/resources/flags/${data.code.toLowerCase()}.png"></div>
                                <div class="col-md-9">${data.text}</div>
                            </div>`
                        );
                    }
                    return $result;
                },
                templateSelection: function (data) {
                    let $result = $(
                        `<img src="${wpbookingpro_root_url_plugin}/admin/resources/flags/${data.code.toLowerCase()}.png"> <span>${data.text}</span>`
                    );
                    return $result;
                },
                escapeMarkup: function (m) {
                    return m;
                },
                data: plugin.settings.list_country,
                dropdownCssClass: "phone-number-field",
            });
        };
        plugin.format = function (state) {
            
            if (!state.id) return state.text; 
            return `<img class='flag' src=admin/resources/flags/${state.id.toLowerCase()}.png/>${state.text}`;
        }
        plugin.example_function = function () {
        };
        plugin.init();
    }
    
    $.fn.field_phonenumber = function (options) {
        
        return this.each(function () {
            
            if (undefined == $(this).data('field_phonenumber')) {
                var plugin = new $.field_phonenumber(this, options);
                $(this).data('field_phonenumber', plugin);
            }
        });
    }
})(jQuery);

