{{ Get_title({
	'index.php?r=alms/communication/showCategories' : Lang_translate('_CATEGORY', 'communication'),
	'':Lang_translate('_CATEGORIES', 'communication')
},false) }}

<table class="table table-bordered display" style="width:100%" id="categorieslist"></table>
<br>
{% if permissions.add_category == true %}
    <a id="addcategory_bottom"  onclick="event.preventDefault();openModal();" href="#" class="ico-wt-sprite subs_add" title="{{ Lang_translate('_ADD', 'standard') }}"><span>{{ Lang_translate('_ADD', 'standard') }}</span></a>
{% endif %}
{% include 'partials/modal_confirm.html.twig' %}
{% include 'partials/modal_category.html.twig' %}

<script>
    let permissions = {{ permissions | json_encode(constant('JSON_HEX_APOS')) | raw }};
    let t = null;
    var delFunc = function(id, count, element) {

            var selector = "#confirmModal";
            var message = "{{ Lang_translate('_AREYOUSURE', 'standard') }}";

            let $element = $(element);
            let url = $element.attr('href');
            var deleteFunction = function() {
                    $.ajax({
                        type: 'POST',
                        url: url,
                        data: { idCategory: id },
                        success: function(response) {
                           var result = JSON.parse(response);
                            if(result.success == true) {
                                t._datatable.row($element.parents('tr')).remove().draw();
                            } else {
                               alert(result.message);
                            }
                        }
                    });
            };
            if(count > 0) {
                message = '{{ Lang_translate('_CATEGORY_WITH_POSTS', 'communication') }}';
                deleteFunction = null;
            }
            confirmDialog(selector , message, deleteFunction);
        };

          var confirmDialog = function (modalSelector, message, onConfirm) {
            var fClose = function() {
                modal.modal("hide");
            };
            var modal = $(modalSelector);
            modal.modal("show");
            modal.find("*[data-val=body]").empty().append(message);
            if(onConfirm !== null) {
                modal.find("*[data-val=yes]").show();
                modal.find("*[data-val=yes]").unbind().one('click', onConfirm).one('click', fClose);
            } else {
                modal.find("*[data-val=yes]").hide();
            }
            
            modal.find("*[data-val=no]").unbind().one("click", fClose);
        }
    $(function () {
      
        var body = {{ categoriesList | json_encode(constant('JSON_HEX_APOS')) | raw }};

        var columns = [
            {data: 'label', title: '{{ Lang_translate('_LABEL', 'communication') }}', sortable: true},
            {data: 'parentLabel', title: '{{ Lang_translate('_PARENT', 'communication') }}', sortable: false},
            {data: 'countCommunications', title: '{{ Lang_translate('_COUNT', 'communication') }}', sortable: true},
            {data: 'filterUrl', title: '<span class="ico-sprite subs_download"><span>{{ Lang_translate('_FILTER', 'communication') }}', sortable: false}
        ];

          if(permissions['mod_category'] == true ) {
            columns.push({data: 'editUrl', title: '<span class="ico-sprite subs_mod"><span>{{ Lang_translate("_MOD", "admin_lang") }}</span></span>', sortable: true});
        }
        if(permissions['del_category'] == true ) {
            columns.push({data: 'deleteUrl', title: '<span class="ico-sprite subs_del"><span>{{ Lang_translate("_DEL", "admin_lang") }}</span></span>', sortable: true});
        }
        var rows = [];

        body.forEach(function (item, k) {
           link = '<a id="'+item.id+'" href="'+item.filterUrl+'" class="ico-sprite subs_download" title="{{ Lang_translate("_FILTER", "communication") }}"><span></span></a>'
            item.filterUrl = link;
            link = '<a id="'+item.id+'"  href="'+item.editUrl+'" class="ico-sprite subs_mod" title="{{ Lang_translate("_MOD", "admin_lang") }}"><span></span></a>'
            item.editUrl = link;
            link = '<a id="'+item.id+'" onclick="event.preventDefault();delFunc(' + item.id + ',' + item.countCommunications + ', this )" href="'+item.deleteUrl+'" class="ico-sprite subs_del" title="{{ Lang_translate("_DEL", "admin_lang") }}"><span></span></a>'
            item.deleteUrl = link;

            rows.push(Object.assign({}, item));
        });

        t = $('#categorieslist').FormaTable({
            rowId: function (row) {
                return row[0];
            },  // cambia
            scrollX: true,
            processing: true,
            serverSide: false,
            paging: true,
            searching: true,
            columns,
            data: rows,
            dom: 'Bfrtip',
            stateSave: true,
            deferRender: true,
        });
    });

    var openModal = function() {

		var modalSelector = '#categoryModal';
		var modal = $(modalSelector);
		var fClose = function() {
			modal.modal("hide");
		};

		 modal.modal("show");
	};

      var editModal = function() {

		var modalSelector = '#categoryModal';
		var modal = $(modalSelector);

        

		var fClose = function() {
			modal.modal("hide");
		};

		 modal.modal("show");
	};

    var data = {{ categoriesDropdownData | json_encode(constant('JSON_HEX_APOS')) | raw }};
    var dropPlaceholder = '{{ Lang_translate('_OPTION','communication') }}';
  
    const categoryDropdown = new window.frontend.modules.Select2($("#category"),{
 
    data: data,
    width:"100%",
    allowClear : true,
    dropdownParent: $('#categoryModal'),
  //  minimumResultsForSearch: 3,
     formatSelection: function(item) {
      return item.text
    },
    formatResult: function(item) {
      return item.text
    },
    templateResult: function(item) {
         var $result = $('<span style="padding-left:' + (20 * item.level) + 'px;">' + item.text + '</span>');
    return $result;
    },
    placeholder: dropPlaceholder,

  });


 $('input[name=save]').on('click', function(e) {
    e.preventDefault();
    e.stopPropagation();

    let $form = $(this).parents('form');
    var modalSelector = '#categoryModal';
    let modal = $(modalSelector);
    
    $.ajax({
        type:  $form.attr("method"),
        url:  $form.attr("action"),
        data: $form.serialize() ,
        dataType : 'json', // changing data type to json
        success: function (data) { // here I'm adding data as a parameter which stores the response
            if(data.success === true)  {
                modal.modal("hide");
                t._datatable.row.add( {
                "label": data.node.label,
                "parentLabel": data.node.parentLabel,
                "countCommunications": data.node.countObjects,
                "filterUrl": '<a id="'+data.node.id+'" href="'+data.node.filterUrl+'" class="ico-sprite subs_download" title="{{ Lang_translate("_EXPORT_XML", "admin_lang") }}"><span></span></a>',
                "editUrl": '<a id="'+data.node.id+'" href="'+data.node.editUrl+'" class="ico-sprite subs_mod" title="{{ Lang_translate("_MOD", "admin_lang") }}"><span></span></a>',
                "deleteUrl": '<a id="'+data.node.id+'" onclick="event.preventDefault();delFunc(' + data.node.id + ',' + data.node.countCommunications + ', this )" href="'+data.node.deleteUrl+'" class="ico-sprite subs_del" title="{{ Lang_translate("_DEL", "admin_lang") }}"><span></span></a>'
                } ).draw();
            }
        }
    });


 
 })


    
</script>