<!-- Moment.js -->
<script src="assets/plugins/moment/moment.min.js"></script>
<!-- DataTable -->
<script src="assets/js/libs/datatable-btns.js?ver=3.3.0"></script>
<!-- Accordion JS -->
<link rel="stylesheet" href="assets/plugins/accordion/accordion.css">
<script src="assets/plugins/accordion/accordion.min.js"></script>
<script>
    var ProfileUsers = function () {
        const module = './?a=config.profile';

        var modalAclV2El,
            modalAclV2Title,
            modalAclV2,
            formAclV2;

        var modalUsersEl,
            modalUsers,
            profile_id;

        var table_profileEl,
            table_profile,
            table_usersEl,
            table_users;

        const isFormDataEmpty = function ( formData ) {
            let iterator = formData.entries();
            return iterator.next().done;
        }

        const initDataTable = function () {
            const loadingTemplate = function ( message ) {
                return `<div class="d-flex justify-content-center">
                        <div class="spinner-border" role="status">
                            <span class="visually-hidden">${ message }</span>
                        </div>
                    </div>`;
            }

            const responseHandler = function ( response, jqXHR ) {
                if ( response.error && response.message === "Not access" ) {
                    return {
                        total: 0,
                        rows: []
                    }
                }

                return response;
            }

            const statusFormatter = function ( data, type, row, meta ) {
                var html = `<div class="badge bg-danger">Inactivo</div>`;
                if ( data === "active" ) {
                    html = `<div class="badge bg-success">Activo</div>`;
                }
                return html;
            }

            const optionsProfileFormatter = function ( data, type, row, meta ) {
                var options = [
                    `<a class="btn btn-outline-primary" onclick="ProfileUsers.getUsers('${ data }')" title="Administración de usuarios"><i class="icon ni ni-users"></i></a>`,
                    `<a class="btn btn-outline-primary" onclick="ProfileUsers.getProfile('${ data }', 'edit')" title="Editar perfil"><i class="icon ni ni-edit-alt"></i></a>`,
                    `<a class="btn btn-outline-primary" onclick="ProfileUsers.deleteProfile('${ data }')" title="Eliminar perfil"><i class="icon ni ni-trash"></i></a>`,
                    `<a class="btn btn-outline-primary" onclick="ProfileUsers.getProfile('${ data }', 'clone')" title="Clonar perfil"><i class="icon ni ni-copy"></i></a>`
                ].join( '' );

                return `<div class="btn-group btn-group-sm">${ options }</div>`;
            }

            const optionsUserFormatter = function ( data, type, row, meta ) {
                return `<button class="btn btn-dim btn-outline-danger" title="Remover este usuario" onclick="ProfileUsers.removeUserProfile('${ data }', '${ row.email }')"><em class="icon ni ni-user-cross"></em></button>`;
            }

            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": "<"
                }
            };

            NioApp.DataTable('#table-config-profiles', {
                ajax: {
                    url: module,
                    type: 'POST',
                    data: function (d) {
                        d.acc = 'getProfiles';
                    }
                },
                columns: [
                    {
                        title: 'Nombre',
                        data: 'name'
                    },
                    {
                        title: 'Descripción',
                        data: 'description'
                    },
                    {
                        title: 'Fecha de registro',
                        data: 'slm.timestamp',
                        render: function (data, type, row, meta) {
                            return moment(data).format('DD/MM/YYYY');
                        }
                    },
                    {
                        title: 'Estatus',
                        data: 'status',
                        render: statusFormatter
                    },
                    {
                        title: 'Opciones',
                        data: 'id',
                        render: optionsProfileFormatter
                    }
                ],
                serverSide: true,
                processing: true,
                buttons: [
                    <?php if (in_array("create", $securityModule ?? [])) : ?>
                    {
                        text: '<em class="icon ni ni-user-add-fill"></em>&nbsp;Agregar Perfil',
                        action: function (e, dt, node, config) {
                            modalAclV2.show();
                        },
                        className: 'btn btn-outline-secondary btn-sm',
                        init: function (api, node, config) {
                            $(node).removeClass('btn-secondary');
                        }
                    }
                    <?php endif; ?>
                ],
                searching: true,
                pageLength: 10,
                responsive: {
                    details: true
                },
                language
            });

            NioApp.DataTable('#table-config-users', {
                ajax: {
                    url: module,
                    type: 'POST',
                    data: function (d) {
                        d.acc = 'getUsers';
                        if (modalUsersEl.querySelector('[name="profile_id"]').value) {
                            d.profile_id = modalUsersEl.querySelector('[name="profile_id"]').value;
                        }
                    }
                },
                serverSide: true,
                processing: true,
                lengthChange: false,
                columns: [
                    {
                        title: 'Nombre',
                        data: 'name'
                    },
                    {
                        title: 'Correo',
                        data: 'email'
                    },
                    {
                        title: 'Acciones',
                        data: 'id',
                        render: optionsUserFormatter
                    }
                ],
                searching: false,
                scrollCollapse: true,
                autoWidth: false,
                responsive: {
                    details: true
                },
                language
            });
        }

        const handleForm = function () {
            [ ...formAclV2.querySelectorAll( '.btn-group' ) ].map( ( group ) => {
                let checkboxAll = group.querySelector( '[id^="all_"]' );
                if ( checkboxAll ) {
                    checkboxAll.addEventListener( 'click', function ( ev ) {
                        let actions = [ 'read', 'create', 'delete', 'update' ];
                        actions.map( ( value ) => {
                            group.querySelector( `[value="${ value }"]` ).click();
                        } );
                    } );
                }
            } );

            const aclSubmitButton = formAclV2.querySelector( '[data-modal-action="submit"]' );
            aclSubmitButton.addEventListener( 'click', function ( ev ) {
                ev.preventDefault();
                //
                const formData = new FormData( formAclV2 );
                if ( formAclV2.querySelector( '[name="profile_id"]' ).value ) {
                    formData.append( 'acc', 'updateProfile' );
                } else {
                    formData.append( 'acc', 'createProfile' );
                }
                //
                submitRequest( module, formData, '#modal_ACL_v2' )
                    .then( ( response ) => {
                        if ( response.error ) {
                            Swal.fire( { title: 'Error', text: response.message, icon: 'error' } );
                            return;
                        }
                        let icon = response.icon ? response.icon : 'success';
                        let title = response.title ? response.title : '';
                        let msg = response.message ? response.message : 'Hubo un error, intente de nuevo más tarde.';

                        if ( response.closeModal ) {
                            modalAclV2.hide();
                        }

                        if ( response.reloadTable ) {
                            $('#table-config-profiles').DataTable().ajax.reload();
                        }

                        Swal.fire( {
                            title: title,
                            text: msg,
                            icon: icon
                        } ).then( function () {
                            if ( response.reload ) {
                                location.reload();
                            }
                        } );
                    } )
                    .catch( ( error ) => {
                        Swal.fire( { title: 'Error', text: error, icon: 'error' } );
                    } );
            } );
        }

        const submitRequest = async function ( module, formData, el = '.side-app' ) {
            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 () {
                table_profileEl = document.getElementById( 'table-config-profiles' );
                table_usersEl = document.getElementById( 'table-config-users' );

                modalAclV2El = document.getElementById( 'modal_ACL_v2' );
                formAclV2 = modalAclV2El.querySelector( '#form_ACL_v2' );
                modalAclV2 = new bootstrap.Modal( modalAclV2El );
                modalAclV2Title = modalAclV2El.querySelector( '.modal-title' );

                $( ".demo-accordion" ).accordionjs();

                modalAclV2El.addEventListener( 'hidden.bs.modal', function ( event ) {
                    // Reseteamos el formulario
                    formAclV2.reset();
                    // Restablecemos el título del modal
                    modalAclV2Title.innerText = 'Nuevo perfil';
                    // El identificador del perfil lo vaciamos
                    modalAclV2El.querySelector( '[name="profile_id"]' ).value = '';
                } );

                handleForm();

                modalUsersEl = document.getElementById( 'modal_table_users_profile' );
                modalUsers = new bootstrap.Modal( modalUsersEl );

                modalUsersEl.addEventListener( 'show.bs.modal', function ( ev ) {
                    $(table_usersEl).DataTable().columns.adjust().draw();
                    //
                    $('#table-config-users').DataTable().ajax.reload();
                } );

                profile_id = modalUsersEl.querySelector( '[name="profile_id"]' );

                initDataTable();
            },
            getUsers: function ( id ) {
                profile_id.value = id;
                //
                $(table_usersEl).DataTable().columns.adjust().draw();
                //
                modalUsers.show();
            },
            getProfile: function ( id, action ) {
                //
                let formData = new FormData();
                formData.append( 'acc', 'getProfile' );
                formData.append( 'profile_id', id );
                //
                submitRequest( module, formData )
                    .then( ( response ) => {
                        let profile = response.data;
                        //
                        if ( action === 'edit' ) {
                            modalAclV2Title.innerText = 'Editar perfil';
                            modalAclV2El.querySelector( '[name="profile_id"]' ).value = id;
                            modalAclV2El.querySelector( '[name="name"]' ).value = profile.name;
                        } else if ( action === 'clone' ) {
                            modalAclV2Title.innerText = 'Clonar perfil';
                            modalAclV2El.querySelector( '[name="name"]' ).value = `${ profile.name } - copia`;
                        }
                        //
                        modalAclV2El.querySelector( '[name="description"]' ).value = profile.description;
                        modalAclV2El.querySelector( '[name="default_view"]' ).value = profile.default_view;
                        //
                        // Iterar sobre todas las entradas en el objeto 'profile.acl'
                        // 'group' será la clave del grupo,
                        // 'modules' será el valor, otro objeto de pares clave-valor
                        for ( const [ group, modules ] of Object.entries( profile.acl ) ) {
                            // Iterar sobre cada módulo en 'modules'
                            // 'vista' es la clave de cada entrada (nombre de la vista),
                            // 'permisos' es el valor, que es una lista de permisos para esa vista específica.
                            for ( const [ vista, permisos ] of Object.entries( modules ) ) {
                                // Buscar un elemento en el DOM con la clase 'btn-group'
                                // y el atributo 'aria-label' igual a `${vista}_${group}`
                                // es decir, la concatenación de 'vista' y 'group'
                                const btnGroupEl = modalAclV2El.querySelector( `.btn-group[aria-label="${ vista }_${ group }"]` );
                                // Si el elemento 'btnGroupEl' existe
                                if ( btnGroupEl ) {
                                    // Iterar sobre cada 'permiso' en 'permisos'
                                    permisos.forEach( ( permiso ) => {
                                        // Para cada 'permiso', buscar un elemento en 'btnGroupEl'
                                        // que tiene el atributo 'value' igual a 'permiso'
                                        // Si se encuentra tal elemento, establecer su propiedad 'checked' a 'true'
                                        btnGroupEl.querySelector( `[value="${ permiso }"]` ).checked = true
                                    } );
                                }
                            }
                        }
                        modalAclV2.show();
                    } )
                    .catch( ( error ) => {
                        Swal.fire( { title: '', text: error, icon: 'error' } );
                    } );
            },
            deleteProfile: function ( id ) {
                Swal.fire( {
                    title: '¿Estas seguro de querer eliminar este perfil?',
                    text: '',
                    icon: 'warning',
                    showCancelButton: true,
                    confirmButtonText: 'Si, eliminar',
                    cancelButtonText: 'No, cancelar',
                    showLoaderOnConfirm: true,
                    preConfirm: async function () {
                        const data = new FormData();
                        data.append( 'acc', 'deleteProfile' );
                        data.append( 'profile_id', id );

                        try {
                            var response = await fetch( module, { method: 'POST', body: data } );

                            if ( !response.ok ) {
                                throw new Error( response.statusText );
                            }

                            var respuesta = await response.json();
                            if ( respuesta.error ) {
                                throw new Error( respuesta.message );
                            }

                            return respuesta;
                        } catch ( e ) {
                            Swal.showValidationMessage( e )
                        }
                    },
                    allowOutsideClick: false,
                    allowEscapeKey: false
                } ).then( function ( result ) {
                    if ( result.isConfirmed ) {
                        Swal.fire( {
                            title: result.value.message,
                            icon: 'success',
                            didOpen: function () {
                                // table_profile.bootstrapTable( 'refresh' );
                                $('#table-config-profiles').DataTable().ajax.reload(null, false);
                            }
                        } );
                    }
                } );
            },
            removeUserProfile: function ( user_id, email ) {
                Swal.fire( {
                    title: '¿Estas seguro de querer remover este perfil del usuario?',
                    text: email,
                    icon: 'warning',
                    showCancelButton: true,
                    confirmButtonText: 'Si',
                    cancelButtonText: 'No, cancelar',
                    showLoaderOnConfirm: true,
                    preConfirm: async function () {
                        const data = new FormData();
                        data.append( 'acc', 'removeUserProfile' );
                        data.append( 'user_id', user_id );

                        try {
                            var response = await fetch( module, { method: 'POST', body: data } );

                            if ( !response.ok ) {
                                throw response.statusText;
                            }

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

                            return respuesta;
                        } catch ( e ) {
                            Swal.showValidationMessage( e )
                        }
                    },
                    allowOutsideClick: false,
                    allowEscapeKey: false
                } ).then( function ( result ) {
                    if ( result.isConfirmed ) {
                        Swal.fire( {
                            title: result.value.message,
                            icon: 'success',
                            didOpen: function () {
                                $('#table-config-users').DataTable().ajax.reload( null, false );
                                $('#table-config-profiles').DataTable().ajax.reload( null, false );
                            }
                        } );
                    }
                } );
            }
        }
    }();

    window.addEventListener( 'DOMContentLoaded', function ( e ) {
        ProfileUsers.init();
    } );
</script>
