<!-- Moment.js -->
<script src="assets/plugins/moment/moment.min.js"></script>
<!-- FormValidation -->
<script src="assets/plugins/formvalidation/FormValidation.min.js"></script>
<script src="assets/plugins/formvalidation/plugins/Bootstrap5.min.js"></script>
<!-- DataTable -->
<script src="assets/js/libs/datatable-btns.js?ver=3.3.0"></script>
<!-- Repeater -->
<script src="assets/plugins/jquery.repeater/jquery.repeater.js"></script>
<!-- Accordion JS -->
<link rel="stylesheet" href="assets/plugins/accordion/accordion.css">
<script src="assets/plugins/accordion/accordion.min.js"></script>
<!--  -->
<script>
    var Acl = function () {
        const module = './?a=config.modules';
        //
        const language = {
            search: "",
            searchPlaceholder: "Escriba para buscar",
            lengthMenu: "<span class='d-none d-sm-inline-block'>Mostrar</span><div class='form-control-select'> _MENU_ </div>",
            info: "_START_ -_END_ de _TOTAL_",
            infoEmpty: "0",
            infoFiltered: "( Total _MAX_  )",
            paginate: {
                "first": "<<",
                "last": ">>",
                "next": ">",
                "previous": "<"
            }
        };
        //
        const modules = function () {
            var tableEl,
                table;
            //
            var modalEl,
                modalTitleEl,
                modal;
            //
            var moduleFormEl,
                moduleFormFv;
            //
            const initDataTable = function () {
                //
                const statusFormatter = function ( data, type, row, meta ) {
                    if ( data === 'unknown' ) {
                        return `<div class="badge badge-dim bg-warning">Unknown</div>`;
                    }
                    if ( data !== '' ) {
                        var html = `<div class="badge badge-dim bg-danger">Inactivo</div>`;
                        if ( data === "active" ) {
                            html = `<div class="badge badge-dim bg-success">Activo</div>`;
                        }
                        return html;
                    }
                }
                //
                const moduleFormatter = function ( data, type, row, meta ) {
                    if ( !row.registered_module ) {
                        return `<a href="#" class="btn btn-dim btn-outline-primary btn-sm" title="Registrar" onclick="Acl.modules.register('${ row.directory }','${ row.file }','${ row.folder }');"><i class="icon ni ni-edit"></i></a>`;
                    } else {
                        let options = [];
                        //
                        options.push( `<a class="btn btn-dim btn-outline-primary" title="Editar" onclick="Acl.modules.get('${ row.id }')"><i class="icon ni ni-edit"></i></a>` );
                        options.push( `<a class="btn btn-dim btn-outline-primary" title="Eliminar módulo" onclick="Acl.modules.remove('${ row.id }', '${ row.name }')"><i class="icon ni ni-trash"></i></a>` );
                        //
                        return `<div class="btn-group btn-group-sm" aria-label="">${options.join('')}</div>`;
                    }
                }
                //
                table = NioApp.DataTable('#table-config-modules', {
                    ajax: {
                        url: module,
                        type: 'POST',
                        data: function (d) {
                            d.acc = 'getModules';
                        }
                    },
                    columns: [
                        {
                            title: 'Nombre',
                            data: 'name'
                        },
                        {
                            title: 'Directorio',
                            data: 'directory'
                        },
                        {
                            title: 'Archivo',
                            data: 'file'
                        },
                        {
                            title: 'URI',
                            data: 'folder'
                        },
                        {
                            title: 'Registrado',
                            data: 'registered_module',
                            render: function (data, type, row, meta) {
                                if (!data) {
                                    return `<span class="badge badge-dim bg-danger">No registrado</span>`;
                                }
                                return `<span class="badge badge-dim bg-success">Registrado</span>`;
                            }
                        },
                        {
                            title: 'Fecha',
                            data: 'timestamp',
                            render: function (data, type, row, meta) {
                                if (data !== null) {
                                    return moment(data).format('DD/MM/YYYY');
                                }
                                return '';
                            }
                        },
                        {
                            title: 'Estatus',
                            data: 'status',
                            render: statusFormatter
                        },
                        {
                            title: 'Opciones',
                            data: null,
                            render: moduleFormatter
                        }
                    ],
                    searching: true,
                    pageLength: 10,
                    responsive: {
                        details: true
                    },
                    language
                });
            }
            //
            const handleForm = function () {
                moduleFormFv = FormValidation.formValidation(
                    moduleFormEl,
                    {
                        fields: {
                            'name': {
                                validators: {
                                    notEmpty: {
                                        message: 'El campo "Nombre" es requerido.'
                                    }
                                }
                            },
                            'file': {
                                validators: {
                                    notEmpty: {
                                        message: 'El campo "Archivo" es requerido.'
                                    }
                                }
                            },
                            'folder': {
                                validators: {
                                    notEmpty: {
                                        message: 'El campo "URI" es requerido.'
                                    }
                                }
                            },
                        },
                        plugins: {
                            trigger: new FormValidation.plugins.Trigger(),
                            bootstrap: new FormValidation.plugins.Bootstrap5( {
                                rowSelector: '.form-group'
                            } )
                        }
                    }
                );
                //
                const submitButton = modalEl.querySelector( '[data-modal-action="submit"]' );
                submitButton.addEventListener( 'click', function ( ev ) {
                    ev.preventDefault();
                    //
                    moduleFormFv.validate().then( function ( status ) {
                        if ( status === 'Valid' ) {
                            let formData = new FormData( moduleFormEl );
                            if ( moduleFormEl.querySelector( '[name="module_id"]' ).value === '' ) {
                                formData.append( 'acc', 'registerModule' );
                            } else {
                                formData.append( 'acc', 'updateModule' );
                            }
                            //
                            submitRequest( module, formData )
                                .then( ( response ) => {
                                    modal.hide();
                                    //
                                    Swal.fire( {
                                        title: 'Éxito',
                                        text: response.message,
                                        icon: 'success',
                                        allowOutsideClick: false,
                                        allowEscapeKey: false
                                    } ).then( ( result ) => {
                                        table.ajax.reload();
                                    } );
                                } )
                                .catch( ( error ) => {
                                    Swal.fire( { title: 'Error', text: error, icon: 'error' } );
                                } );
                        }
                    } );
                } );
            }
            //
            const handleModal = function () {
                modalEl.addEventListener( 'hide.bs.modal', function ( ev ) {
                    modalTitleEl.innerText = 'Registrar Módulo';
                    moduleFormEl.querySelector('[name="module_id"]').value = '';
                    //
                    moduleFormFv.resetForm( true );
                    moduleFormEl.reset();
                } );
            }
            //
            return {
                init: function () {
                    tableEl = document.getElementById( 'table-config-modules' );
                    //
                    modalEl = document.getElementById( 'moduleModal' );
                    modalTitleEl = modalEl.querySelector( '#moduleModalLabel' );
                    modal = new bootstrap.Modal( modalEl );
                    //
                    moduleFormEl = modalEl.querySelector( '#moduleForm' );
                    //
                    initDataTable();
                    //
                    handleModal();
                    handleForm();
                },
                register: function ( directory, file, uri ) {
                    modalEl.querySelector( '[name="directory"]' ).value = directory;
                    modalEl.querySelector( '[name="file"]' ).value = file;
                    modalEl.querySelector( '[name="folder"]' ).value = uri;
                    // Mostramos el modal
                    modal.show();
                },
                get: function ( module_id ) {
                    let formData = new FormData();
                    formData.append( 'acc', 'getModule' );
                    formData.append( 'module_id', module_id );
                    //
                    submitRequest( module, formData )
                        .then( ( response ) => {
                            modalTitleEl.innerText = 'Actualizar Módulo';
                            moduleFormEl.querySelector('[name="module_id"]').value = module_id;
                            //
                            for ( const [ field, value ] of Object.entries( response.data ) ) {
                                let input = moduleFormEl.querySelector( `[name="${ field }"]` );
                                if ( input ) {
                                    input.value = value;
                                }
                            }
                            //
                            modal.show();
                        } )
                        .catch( ( error ) => {
                            Swal.fire( { title: 'Error', text: error, icon: 'error' } );
                        } );
                },
                remove: function ( module_id, module_name ) {
                    Swal.fire( {
                        title: '¿Desea eliminar módulo seleccionado?',
                        text: module_name,
                        icon: 'question',
                        confirmButtonText: 'Si',
                        showCancelButton: true,
                        cancelButtonText: 'No',
                        allowOutsideClick: false,
                        allowEscapeKey: false,
                    } ).then( ( result ) => {
                        if ( result.isConfirmed ) {
                            let formData = new FormData();
                            formData.append( 'acc', 'removeModule' );
                            formData.append( 'module_id', module_id );
                            //
                            submitRequest( module, formData )
                                .then( ( response ) => {
                                    // Mostramos el mensaje de éxito
                                    Swal.fire( {
                                        title: 'Éxito',
                                        text: response.message,
                                        icon: 'success',
                                        didClose: () => {
                                            table.ajax.reload();
                                        }
                                    } );
                                } )
                                .catch( ( error ) => {
                                    Swal.fire( { title: '', text: error, icon: 'error' } );
                                } );
                        }
                    } );
                }
            }
        }();
        //
        const dropdownMenu = function () {
            var tableEl,
                table;
            //
            var modalEl,
                modalTitleEl,
                modal,
                formEl,
                formFv,
                repeaterEl,
                repeater;
            //
            const handleForm = function () {
                formFv = FormValidation.formValidation(
                    formEl,
                    {
                        fields: {
                            'name': {
                                validators: {
                                    notEmpty: {
                                        message: 'El campo "Nombre" es requerido.'
                                    }
                                }
                            },
                            'icon': {
                                validators: {
                                    notEmpty: {
                                        message: 'El campo "Icono" es requerido.'
                                    }
                                }
                            }
                        },
                        plugins: {
                            trigger: new FormValidation.plugins.Trigger(),
                            bootstrap: new FormValidation.plugins.Bootstrap5( {
                                rowSelector: '.col-md-6'
                            } )
                        }
                    }
                );
                //
                const submitButton = modalEl.querySelector( '[data-modal-action="submit"]' );
                submitButton.addEventListener( 'click', function ( ev ) {
                    ev.preventDefault();
                    //
                    formFv.validate().then( function ( status ) {
                        if ( status === 'Valid' ) {
                            let formData = new FormData( formEl );

                            // Ensure the specific checkbox is handled correctly
                            const checkDropDownMenuForm = formEl.querySelector('#checkDropDownMenuForm');
                            if (!checkDropDownMenuForm.checked) {
                                formData.set(checkDropDownMenuForm.name, 'false');
                            }

                            if ( formEl.querySelector( '[name="dropdown_menu_id"]' ).value === '' ) {
                                formData.append( 'acc', 'registerDropdownMenu' );
                            } else {
                                formData.append( 'acc', 'updateDropdownMenu' );
                            }
                            //
                            submitRequest( module, formData )
                                .then( ( response ) => {
                                    modal.hide();
                                    //
                                    Swal.fire( {
                                        title: 'Éxito',
                                        text: response.message,
                                        icon: 'success',
                                        allowOutsideClick: false,
                                        allowEscapeKey: false
                                    } ).then( ( result ) => {
                                        table.ajax.reload();
                                    } );
                                } )
                                .catch( ( error ) => {
                                    Swal.fire( { title: 'Error', text: error, icon: 'error' } );
                                } );
                        }
                    } );
                } );
            }
            //
            const handleModal = function () {
                modalEl.addEventListener( 'hide.bs.modal', function ( ev ) {
                    modalTitleEl.innerText = 'Registrar menu desplegable';
                    formEl.querySelector( '[name="dropdown_menu_id"]' ).value = '';
                    //
                    formFv.resetForm( true );
                    formEl.reset();
                } );
            }
            //
            const initDataTable = function () {
                //
                const statusFormatter = function ( data, type, row, meta ) {
                    if ( data === 'unknown' ) {
                        return `<div class="badge badge-dim bg-warning">Unknown</div>`;
                    }
                    if ( data !== '' ) {
                        var html = `<div class="badge badge-dim bg-danger">Inactivo</div>`;
                        if ( data === "active" ) {
                            html = `<div class="badge badge-dim bg-success">Activo</div>`;
                        }
                        return html;
                    }
                }
                //
                const menuFormatter = function ( data, type, row, meta ) {
                    let options = [];
                    //
                    options.push( `<a class="btn btn-dim btn-outline-primary" title="Editar" onclick="Acl.dropdownMenu.get('${ row.id }')"><i class="icon ni ni-edit"></i></a>` );
                    options.push( `<a class="btn btn-dim btn-outline-primary" title="Eliminar menú" onclick="Acl.dropdownMenu.remove('${ row.id }', '${ row.name }')"><i class="icon ni ni-trash"></i></a>` );
                    //
                    return `<div class="btn-group btn-group-sm" aria-label="">${options.join('')}</div>`;
                }
                //
                table = NioApp.DataTable('#table-config-menu-desplegable', {
                    ajax: {
                        url: module,
                        type: 'POST',
                        data: function (d) {
                            d.acc = 'getDropdownMenus';
                        }
                    },
                    serverSide: true,
                    processing: true,
                    buttons: [
                        {
                            text: 'Agregar',
                            action: function (e, dt, node, config) {
                                modal.show();
                            },
                            className: 'btn btn-outline-secondary btn-sm',
                            init: function (api, node, config) {
                                $(node).removeClass('btn-secondary');
                            }
                        }
                    ],
                    createdRow: function (row, data, dataIndex) {
                        $(row).addClass('text-center');
                    },
                    columns: [
                        {
                            title: 'Nombre',
                            data: 'name'
                        },
                        {
                            title: 'Icono',
                            data: 'icon',
                            render: function (icon, type, row, meta) {
                                return `<i class="icon ${icon}"></i>`;
                            },
                            orderable: false
                        },
                        {
                            title: 'Nro. de Módulos',
                            data: 'module',
                            render: function (module, type, row, meta) {
                                return Object.keys(module).length;
                            }
                        },
                        {
                            title: 'Fecha',
                            data: 'slm.timestamp',
                            render: function (data, type, row, meta) {
                                if (data !== null) {
                                    return moment(data).format('DD/MM/YYYY');
                                }
                                return '';
                            }
                        },
                        {
                            title: 'Estatus',
                            data: 'status',
                            render: statusFormatter
                        },
                        {
                            title: 'Opciones',
                            data: null,
                            render: menuFormatter
                        }
                    ],
                    searching: true,
                    pageLength: 10,
                    responsive: {
                        details: true
                    },
                    language
                });
            }
            //
            const initRepeater = function () {
                repeater = $( repeaterEl ).repeater( {
                    show: function () {
                        $( this ).slideDown();
                    },
                    hide: function ( deleteElement ) {
                        if ( confirm( '¿Está seguro de que desea eliminar este elemento?' ) ) {
                            $( this ).slideUp( deleteElement );
                        }
                    },
                    isFirstItemUndeletable: true
                } );
            }
            //
            return {
                init: function () {
                    tableEl = document.getElementById( 'table-config-menu-desplegable' );
                    //
                    modalEl = document.getElementById( 'dropdownMenuModal' );
                    modalTitleEl = modalEl.querySelector( '#dropdownMenuModalLabel' );
                    modal = new bootstrap.Modal( modalEl );
                    //
                    formEl = modalEl.querySelector( '#dropdownMenuForm' );
                    //
                    repeaterEl = formEl.querySelector( '.repeater' );
                    //
                    initDataTable();
                    initRepeater();
                    //
                    handleModal();
                    handleForm();
                },
                get: function ( dropdown_menu_id ) {
                    let formData = new FormData();
                    formData.append( 'acc', 'getDropdownMenu' );
                    formData.append( 'dropdown_menu_id', dropdown_menu_id );
                    //
                    submitRequest( module, formData )
                        .then( ( response ) => {
                            modalTitleEl.innerText = 'Actualizar menu desplegable';
                            formEl.querySelector( '[name="dropdown_menu_id"]' ).value = dropdown_menu_id;
                            //
                            for ( const [ field, value ] of Object.entries( response.data ) ) {
                                let input = formEl.querySelector( `[name="${ field }"]` );
                                if ( input ) {
                                    input.value = value;
                                }
                            }
                            //
                            repeater.setList(response.data.module);
                            //
                            modal.show();
                        } )
                        .catch( ( error ) => {
                            Swal.fire( { title: 'Error', text: error, icon: 'error' } );
                        } );
                },
                remove: function ( dropdown_menu_id, dropdown_menu_name ) {
                    Swal.fire( {
                        title: '¿Desea eliminar el menú seleccionado?',
                        text: dropdown_menu_name,
                        icon: 'question',
                        confirmButtonText: 'Si',
                        showCancelButton: true,
                        cancelButtonText: 'No',
                        allowOutsideClick: false,
                        allowEscapeKey: false,
                    } ).then( ( result ) => {
                        if ( result.isConfirmed ) {
                            let formData = new FormData();
                            formData.append( 'acc', 'removeDropdownMenu' );
                            formData.append( 'dropdown_menu_id', dropdown_menu_id );
                            //
                            submitRequest( module, formData )
                                .then( ( response ) => {
                                    // Mostramos el mensaje de éxito
                                    Swal.fire( {
                                        title: 'Éxito',
                                        text: response.message,
                                        icon: 'success',
                                        didClose: () => {
                                            table.ajax.reload();
                                        }
                                    } );
                                } )
                                .catch( ( error ) => {
                                    Swal.fire( { title: '', text: error, icon: 'error' } );
                                } );
                        }
                    } );
                }
            }
        }();
        //
        const simpleMenu = function () {
            var tableEl,
                table;
            //
            var modalEl,
                modalTitleEl,
                modal,
                formEl,
                formFv;
            //
            const handleForm = function () {
                formFv = FormValidation.formValidation(
                    formEl,
                    {
                        fields: {
                            'name': {
                                validators: {
                                    notEmpty: {
                                        message: 'El campo "Nombre" es requerido.'
                                    }
                                }
                            },
                            'icon': {
                                validators: {
                                    notEmpty: {
                                        message: 'El campo "Icono" es requerido.'
                                    }
                                }
                            },
                            'folder': {
                                validators: {
                                    notEmpty: {
                                        message: 'El campo "URI" es requerido.'
                                    }
                                }
                            },
                        },
                        plugins: {
                            trigger: new FormValidation.plugins.Trigger(),
                            bootstrap: new FormValidation.plugins.Bootstrap5( {
                                rowSelector: '.form-group'
                            } )
                        }
                    }
                );
                //
                const submitButton = modalEl.querySelector( '[data-modal-action="submit"]' );
                submitButton.addEventListener( 'click', function ( ev ) {
                    ev.preventDefault();
                    //
                    formFv.validate().then( function ( status ) {
                        if ( status === 'Valid' ) {
                            let formData = new FormData( formEl );
                            if ( formEl.querySelector( '[name="simple_menu_id"]' ).value === '' ) {
                                formData.append( 'acc', 'registerSimpleMenu' );
                            } else {
                                formData.append( 'acc', 'updateSimpleMenu' );
                            }
                            //
                            submitRequest( module, formData )
                                .then( ( response ) => {
                                    modal.hide();
                                    //
                                    Swal.fire( {
                                        title: 'Éxito',
                                        text: response.message,
                                        icon: 'success',
                                        allowOutsideClick: false,
                                        allowEscapeKey: false
                                    } ).then( ( result ) => {
                                        table.ajax.reload();
                                    } );
                                } )
                                .catch( ( error ) => {
                                    Swal.fire( { title: 'Error', text: error, icon: 'error' } );
                                } );
                        }
                    } );
                } );
            }
            //
            const handleModal = function () {
                modalEl.addEventListener( 'hide.bs.modal', function ( ev ) {
                    modalTitleEl.innerText = 'Registrar menu simple';
                    formEl.querySelector( '[name="simple_menu_id"]' ).value = '';
                    //
                    formFv.resetForm( true );
                    formEl.reset();
                } );
            }
            //
            const initDataTable = function () {
                //
                const statusFormatter = function ( data, type, row, meta ) {
                    if ( data === 'unknown' ) {
                        return `<div class="badge badge-dim bg-warning">Unknown</div>`;
                    }
                    if ( data !== '' ) {
                        var html = `<div class="badge badge-dim bg-danger">Inactivo</div>`;
                        if ( data === "active" ) {
                            html = `<div class="badge badge-dim bg-success">Activo</div>`;
                        }
                        return html;
                    }
                }
                //
                const simpleMenuFormatter = function ( data, type, row, meta ) {
                    let options = [];
                    //
                    options.push( `<a class="btn btn-dim btn-outline-primary" title="Editar" onclick="Acl.simpleMenu.get('${ row.id }')"><i class="icon ni ni-edit"></i></a>` );
                    options.push( `<a class="btn btn-dim btn-outline-primary" title="Eliminar módulo" onclick="Acl.simpleMenu.remove('${ row.id }', '${ row.name }')"><i class="icon ni ni-trash"></i></a>` );
                    //
                    return `<div class="btn-group btn-group-sm" aria-label="">${options.join('')}</div>`;
                }
                //
                table = NioApp.DataTable('#table-config-menu-simple', {
                    ajax: {
                        url: module,
                        type: 'POST',
                        data: function ( d ) {
                            d.acc = 'getSimpleMenus';
                        }
                    },
                    serverSide: true,
                    processing: true,
                    buttons: [
                        {
                            text: 'Agregar',
                            action: function ( e, dt, node, config ) {
                                modal.show();
                            },
                            className: 'btn btn-outline-secondary btn-sm',
                            init: function (api, node, config) {
                                $(node).removeClass('btn-secondary');
                            }
                        }
                    ],
                    createdRow: function ( row, data, dataIndex ) {
                        $( row ).addClass( 'text-center' );
                    },
                    columns: [
                        {
                            title: 'Nombre',
                            data: 'name'
                        },
                        {
                            title: 'Icono',
                            data: 'icon',
                            render: function ( icon, type, row, meta ) {
                                return `<i class="icon ${ icon }"></i>`;
                            },
                            orderable: false
                        },
                        {
                            title: 'URI',
                            data: 'folder',
                            render: function ( folder, type, row, meta ) {
                                return folder.folder;
                            }
                        },
                        {
                            title: 'Visible',
                            data: 'display',
                            render: function ( display, type, row, meta ) {
                                if ( display ) {
                                    return `<i class="icon ni ni-eye"></i>`;
                                }
                                return `<i class="icon ni ni-eye-off"></i>`;
                            }
                        },
                        {
                            title: 'Fecha',
                            data: 'slm.timestamp',
                            render: function ( data, type, row, meta ) {
                                if ( data !== null ) {
                                    return moment( data ).format( 'DD/MM/YYYY' );
                                }
                                return '';
                            }
                        },
                        {
                            title: 'Estatus',
                            data: 'status',
                            render: statusFormatter
                        },
                        {
                            title: 'Opciones',
                            data: null,
                            render: simpleMenuFormatter,
                            orderable: false
                        }
                    ],
                    searching: true,
                    pageLength: 10,
                    responsive: {
                        details: true
                    },
                    language
                } );
            }
            //
            return {
                init: function () {
                    tableEl = document.getElementById( 'table-config-menu-simple' );
                    //
                    modalEl = document.getElementById( 'menuSimpleModal' );
                    modalTitleEl = modalEl.querySelector( '#menuSimpleModalLabel' );
                    modal = new bootstrap.Modal( modalEl );
                    //
                    formEl = modalEl.querySelector( '#menuSimpleForm' );
                    //
                    initDataTable();
                    //
                    handleModal();
                    handleForm();
                },
                get: function ( simple_menu_id ) {
                    let formData = new FormData();
                    formData.append( 'acc', 'getSimpleMenu' );
                    formData.append( 'simple_menu_id', simple_menu_id );
                    //
                    submitRequest( module, formData )
                        .then( ( response ) => {
                            modalTitleEl.innerText = 'Actualizar menu simple';
                            formEl.querySelector( '[name="simple_menu_id"]' ).value = simple_menu_id;
                            //
                            for ( const [ field, value ] of Object.entries( response.data ) ) {
                                let input = formEl.querySelector( `[name="${ field }"]` );
                                if ( input ) {
                                    input.value = value;
                                }
                            }
                            //
                            modal.show();
                        } )
                        .catch( ( error ) => {
                            Swal.fire( { title: 'Error', text: error, icon: 'error' } );
                        } );
                },
                remove: function ( simple_menu_id, simple_menu_name ) {
                    Swal.fire( {
                        title: '¿Desea eliminar el menú seleccionado?',
                        text: simple_menu_name,
                        icon: 'question',
                        confirmButtonText: 'Si',
                        showCancelButton: true,
                        cancelButtonText: 'No',
                        allowOutsideClick: false,
                        allowEscapeKey: false,
                    } ).then( ( result ) => {
                        if ( result.isConfirmed ) {
                            let formData = new FormData();
                            formData.append( 'acc', 'removeSimpleMenu' );
                            formData.append( 'simple_menu_id', simple_menu_id );
                            //
                            submitRequest( module, formData )
                                .then( ( response ) => {
                                    // Mostramos el mensaje de éxito
                                    Swal.fire( {
                                        title: 'Éxito',
                                        text: response.message,
                                        icon: 'success',
                                        didClose: () => {
                                            table.ajax.reload();
                                        }
                                    } );
                                } )
                                .catch( ( error ) => {
                                    Swal.fire( { title: '', text: error, icon: 'error' } );
                                } );
                        }
                    } );
                }
            }
        }();
        //
        const groups = function () {
            var tableEl,
                table;
            //
            var modalEl,
                modalTitleEl,
                modal,
                formEl,
                formFv,
                repeaterEl,
                repeater;
            //
            const handleForm = function () {
                formFv = FormValidation.formValidation(
                    formEl,
                    {
                        "fields": {
                            "title": {
                                "validators": {
                                    "notEmpty": {
                                        "message": 'El campo "Nombre" es requerido.'
                                    }
                                }
                            }
                        },
                        "plugins": {
                            "trigger": new FormValidation.plugins.Trigger(),
                            "bootstrap": new FormValidation.plugins.Bootstrap5( {
                                "rowSelector": ".form-group"
                            } )
                        }
                    }
                );
                //
                const orderInput = formEl.querySelector( '[name="order"]' );
                orderInput.addEventListener( 'input', function ( e ) {
                    let value = this.value;
                    // Eliminar cualquier caracter que no sea un número
                    value = value.replace( /[^0-9]/g, '' );
                    // Actualizar el valor del campo de entrada
                    this.value = value;
                } );
                //
                const submitButton = modalEl.querySelector( '[data-modal-action="submit"]' );
                submitButton.addEventListener( 'click', function ( ev ) {
                    ev.preventDefault();
                    //
                    formFv.validate().then( function ( status ) {
                        if ( status === 'Valid' ) {
                            let formData = new FormData( formEl );
                            if ( formEl.querySelector( '[name="group_menu_id"]' ).value === '' ) {
                                formData.append( 'acc', 'registerGroupMenu' );
                            } else {
                                formData.append( 'acc', 'updateGroupMenu' );
                            }
                            //
                            submitRequest( module, formData )
                                .then( ( response ) => {
                                    modal.hide();
                                    //
                                    Swal.fire( {
                                        title: 'Éxito',
                                        text: response.message,
                                        icon: 'success',
                                        allowOutsideClick: false,
                                        allowEscapeKey: false
                                    } ).then( ( result ) => {
                                        table.ajax.reload();
                                    } );
                                } )
                                .catch( ( error ) => {
                                    Swal.fire( { title: 'Error', text: error, icon: 'error' } );
                                } );
                        }
                    } );
                } );
            }
            //
            const handleModal = function () {
                modalEl.addEventListener( 'hide.bs.modal', function ( ev ) {
                    modalTitleEl.innerText = 'Registrar Grupo';
                    formEl.querySelector( '[name="group_menu_id"]' ).value = '';
                    //
                    formFv.resetForm( true );
                    formEl.reset();
                } );
            }
            //
            const initDataTable = function () {
                //
                const statusFormatter = function ( data, type, row, meta ) {
                    if ( data === 'unknown' ) {
                        return `<div class="badge badge-dim bg-warning">Unknown</div>`;
                    }
                    if ( data !== '' ) {
                        var html = `<div class="badge badge-dim bg-danger">Inactivo</div>`;
                        if ( data === "active" ) {
                            html = `<div class="badge badge-dim bg-success">Activo</div>`;
                        }
                        return html;
                    }
                }
                //
                const menuFormatter = function ( data, type, row, meta ) {
                    let options = [];
                    //
                    options.push( `<a class="btn btn-dim btn-outline-primary" title="Editar" onclick="Acl.groups.get('${ row.id }')"><i class="icon ni ni-edit"></i></a>` );
                    options.push( `<a class="btn btn-dim btn-outline-primary" title="Eliminar módulo" onclick="Acl.groups.remove('${ row.id }', '${ row.title }')"><i class="icon ni ni-trash"></i></a>` );
                    //
                    return `<div class="btn-group btn-group-sm" aria-label="">${options.join('')}</div>`;
                }
                //
                table = NioApp.DataTable('#table-config-groups', {
                    ajax: {
                        url: module,
                        type: 'POST',
                        data: function ( d ) {
                            d.acc = 'getGroups';
                        }
                    },
                    serverSide: true,
                    processing: true,
                    buttons: [
                        {
                            text: 'Agregar',
                            action: function ( e, dt, node, config ) {
                                modal.show();
                            },
                            className: 'btn btn-outline-secondary btn-sm',
                            init: function (api, node, config) {
                                $(node).removeClass('btn-secondary');
                            }
                        }
                    ],
                    createdRow: function ( row, data, dataIndex ) {
                        $( row ).addClass( 'text-center' );
                    },
                    columns: [
                        {
                            title: 'Nombre',
                            data: 'title'
                        },
                        {
                            title: 'Orden',
                            data: 'order'
                        },
                        {
                            title: 'Nro. de Menús',
                            data: 'menu',
                            render: function (menu, type, row, meta) {
                                return Object.keys(menu).length;
                            }
                        },
                        {
                            title: 'Visible',
                            data: 'display',
                            render: function ( display, type, row, meta ) {
                                if ( display ) {
                                    return `<i class="icon ni ni-eye"></i>`;
                                }
                                return `<i class="icon ni ni-eye-off"></i>`;
                            }
                        },
                        {
                            title: 'Fecha',
                            data: 'slm.timestamp',
                            render: function ( data, type, row, meta ) {
                                if ( data !== null ) {
                                    return moment( data ).format( 'DD/MM/YYYY' );
                                }
                                return '';
                            }
                        },
                        {
                            title: 'Estatus',
                            data: 'status',
                            render: statusFormatter
                        },
                        {
                            title: 'Opciones',
                            data: null,
                            render: menuFormatter
                        }
                    ],
                    searching: true,
                    pageLength: 10,
                    order: [ [ 1, 'asc' ] ],
                    responsive: {
                        details: true
                    },
                    language
                } );
            }
            //
            const initRepeater = function () {
                repeater = $( repeaterEl ).repeater( {
                    show: function () {
                        $( this ).slideDown();
                    },
                    hide: function ( deleteElement ) {
                        if ( confirm( '¿Está seguro de que desea eliminar este elemento?' ) ) {
                            $( this ).slideUp( deleteElement );
                        }
                    },
                    isFirstItemUndeletable: true
                } );
            }
            //
            return {
                init: function () {
                    tableEl = document.getElementById( 'table-config-groups' );
                    //
                    modalEl = document.getElementById( 'groupsModal' );
                    modalTitleEl = modalEl.querySelector( '#groupsModalLabel' );
                    modal = new bootstrap.Modal( modalEl );
                    //
                    formEl = modalEl.querySelector( '#groupsForm' );
                    //
                    repeaterEl = formEl.querySelector( '.repeater' );
                    //
                    initDataTable();
                    initRepeater();
                    //
                    handleModal();
                    handleForm();
                },
                get: function ( group_menu_id ) {
                    let formData = new FormData();
                    formData.append( 'acc', 'getGroupMenu' );
                    formData.append( 'group_menu_id', group_menu_id );
                    //
                    submitRequest( module, formData )
                        .then( ( response ) => {
                            modalTitleEl.innerText = 'Actualizar Grupo';
                            formEl.querySelector( '[name="group_menu_id"]' ).value = group_menu_id;
                            //
                            for ( const [ field, value ] of Object.entries( response.data ) ) {
                                let input = formEl.querySelector( `[name="${ field }"]` );
                                if ( input ) {
                                    if ( field === 'display' ) {
                                        input.checked = value;
                                    } else {
                                        input.value = value;
                                    }
                                }
                            }
                            //
                            repeater.setList(response.data.menu);
                            //
                            modal.show();
                        } )
                        .catch( ( error ) => {
                            Swal.fire( { title: 'Error', text: error, icon: 'error' } );
                        } );
                },
                remove: function ( group_menu_id, group_menu_name ) {
                    Swal.fire( {
                        title: '¿Desea eliminar el grupo seleccionado?',
                        text: group_menu_name,
                        icon: 'question',
                        confirmButtonText: 'Si',
                        showCancelButton: true,
                        cancelButtonText: 'No',
                        allowOutsideClick: false,
                        allowEscapeKey: false,
                    } ).then( ( result ) => {
                        if ( result.isConfirmed ) {
                            let formData = new FormData();
                            formData.append( 'acc', 'removeGroupMenu' );
                            formData.append( 'group_menu_id', group_menu_id );
                            //
                            submitRequest( module, formData )
                                .then( ( response ) => {
                                    // Mostramos el mensaje de éxito
                                    Swal.fire( {
                                        title: 'Éxito',
                                        text: response.message,
                                        icon: 'success',
                                        didClose: () => {
                                            table.ajax.reload();
                                        }
                                    } );
                                } )
                                .catch( ( error ) => {
                                    Swal.fire( { title: '', text: error, icon: 'error' } );
                                } );
                        }
                    } );
                }
            }
        }();
        //
        const submitRequest = async function ( module, formData ) {
            try {
                $( "#global-loader" ).show()
                const response = await fetch( module, {
                    method: 'POST',
                    body: formData
                } );

                if ( !response.ok ) {
                    throw `HTTP error, status = ${ response.status }`;
                }

                const respuesta = await response.json();
                if ( respuesta.error ) {
                    throw respuesta.message;
                }

                return respuesta;
            } catch ( error ) {
                console.error( error );
                throw error;
            } finally {
                $( '#global-loader' ).hide();
            }
        }
        //
        return {
            init: function () {
                modules.init();
                dropdownMenu.init();
                simpleMenu.init();
                groups.init();
                //
                $( ".demo-accordion" ).accordionjs();
            },
            modules,
            dropdownMenu,
            simpleMenu,
            groups
        }
    }();
    //
    document.addEventListener( 'DOMContentLoaded', function ( ev ) {
        Acl.init();
    } );
</script>