<!-- 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 Users = function () {
        const module = './?a=config.users';

        var modalEl,
            modalTitle,
            modal,
            form;

        var filterModalEl,
            filterModal;

        var tableEl,
            table;

        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 ( status, row, index ) {
                var html = `<div class="badge bg-danger">Inactivo</div>`;
                if ( status === "active" )
                    html = `<div class="badge bg-success">Activo</div>`;

                return html;
            }

            const optionsUserFormatter = function ( id, type, row, meta ) {
                let title,
                    action,
                    icon,
                    icon_class;
                if ( row.status === "active" ) {
                    title = "Deshabilitar usuario";
                    action = "disable";
                    icon = "ni ni-user-check";
                    icon_class = "text-success";
                } else {
                    title = "Habilitar usuario";
                    action = "enable";
                    icon = "ni ni-user-cross";
                    icon_class = "text-danger";
                }
                let buttons = [
                    `<button class="btn btn-outline-primary" onclick="Users.edit('${ id }')" title="Editar usuario"><em class="icon ni ni-edit"></em></button>`,
                    `<button class="btn btn-outline-primary" onclick="Users.switchStatus('${ row.name }' ,'${ id }', '${ action }')" title="${ title }"><em class="icon ${ icon } ${ icon_class }"></em></button>`,
                    `<button class="btn btn-outline-primary" onclick="Users.resetPassword('${ row.email }', '${ id }')" title="Restablecer contraseña"><em class="icon ni ni-unlock"></em></button>`,
                    `<button class="btn btn-outline-primary" onclick="Users.destroySessions('${ id }')" title="Cerrar sesiones"><em class="icon ni ni-signout"></em></button>`,
                ].join( '' );
                return `<div class="btn-group btn-group-sm">${ buttons }</div>`;
            }

            table = NioApp.DataTable('#table-config-users', {
                ajax: {
                    url: module,
                    type: 'POST',
                    data: function (d) {
                        d.acc = 'getUsers';
                    }
                },
                columns: [
                    {
                        title: 'Nombre',
                        data: 'id',
                        render: function (data, type, row, meta) {
                            return `${row.name} ${row.lastname}`;
                        }
                    },
                    {
                        title: 'Correo',
                        data: 'email'
                    },
                    {
                        title: 'Teléfono',
                        data: 'telephone_number',
                        render: function (data, type, row, meta) {
                            if (row.hasOwnProperty('telephone_number')) {
                                let country_code = row.hasOwnProperty('country_code') ? `+${row.country_code}` : '';
                                return `${country_code}${row.telephone_number}`;
                            }
                        }
                    },
                    {
                        title: 'Perfil',
                        data: 'profile',
                        render: function (data, type, row, meta) {
                            return data.name;
                        }
                    },
                    {
                        title: 'Fecha de registro',
                        data: 'slm.timestamp',
                        render: function (data, type, row, meta) {
                            return moment(data).format('DD/MM/YYYY');
                        }
                    },
                    {
                        title: 'Estado',
                        data: 'status',
                        render: statusFormatter
                    },
                    {
                        title: 'Opciones',
                        data: 'id',
                        render: optionsUserFormatter
                    },
                ],
                buttons: [
                    <?php if (in_array("create", $securityModule ?? [])) : ?>
                    {
                        text: '<em class="icon ni ni-user-add"></em> Agregar usuario',
                        action: function (e, dt, node, config) {
                            Users.add();
                        },
                        className: 'btn btn-outline-secondary btn-sm',
                        init: function (api, node, config) {
                            $(node).removeClass('btn-secondary');
                        }
                    }
                    <?php endif; ?>
                ],
                serverSide: true,
                processing: true,
                stateSave: false,
                searching: true,
                pageLength: 10,
                responsive: {
                    details: true
                },
                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 handleModal = function () {
            modalEl.addEventListener( 'hide.bs.modal', function ( e ) {
                // Limpiamos el selector de los perfiles
                form.querySelector( '[name="profile"]' ).innerHTML = '';
                form.reset();
            } );
            //
            filterModalEl.addEventListener( 'show.bs.modal', function ( ev ) {
                let formData = new FormData();
                formData.append( 'acc', 'getProfiles' );
                formData.append( 'length', '50' );
                //
                submitRequest( module, formData )
                    .then( ( response ) => {
                        let options = '<option label="Seleccione"></option>';
                        let profiles = response.data.profiles.data;
                        for ( const [ index, profile ] of Object.entries( profiles ) ) {
                            options += `<option value="${ profile.id }">${ profile.name }</option>`;
                        }
                        //
                        filterModalEl.querySelector('#profile').innerHTML = options;
                    } )
                    .catch( ( error ) => {
                        Swal.fire( { title: 'Error', text: error, icon: 'error' } );
                    } );
            } );
            //
            filterModalEl.addEventListener( 'hide.bs.modal', function ( ev ) {

            } );
        }

        const handleForm = function () {
            const filterButton = filterModalEl.querySelector( '[data-modal-action="filter"]' );
            filterButton.addEventListener( 'click', function ( ev ) {
                ev.preventDefault();
                //
                var params = {};
                [ ...filterModalEl.querySelectorAll( '.datatable-input' ) ].map( ( input ) => {
                    let index = input.dataset.colIndex;
                    let field = input.dataset.esField;
                    if ( field ) {
                        if ( input.value ) {
                            if ( params[index] ) {
                                params[index] += field.includes( 'keyword' ) ? `|${ field }:"${ input.value }"` : `|${ field }:${ input.value }|${ field }:*${ input.value }|${ field }:${ input.value }*`;
                            } else {
                                params[index] = field.includes( 'keyword' ) ? `${ field }:"${ input.value }"` : `|${ field }:${ input.value }|${ field }:*${ input.value }|${ field }:${ input.value }*`;
                            }
                        } else {
                            params[index] = '';
                        }
                    }
                } );
                //
                $.each( params, function ( index, value ) {
                    if ( value.indexOf( "|" ) >= 0 ) {
                        let str = value.split( "|" );
                        let string = "";
                        $.each( str, function ( i, v ) {
                            if ( v ) {
                                if ( string === "" ) {
                                    string = `(${ v })`;
                                } else {
                                    string += `OR(${ v })`;
                                }
                            }
                        } );
                        //Ejemplo: (promo_code.keyword:test50)OR(promo_code.keyword:test100)OR(promo_code.keyword:test500)
                        params[index] = string;
                    }
                } );
                //
                $.each( params, function ( i, val ) {
                    // apply search params to datatable
                    table.column( i ).search( val ? val : '', false, false );
                } );
                table.table().draw();
                //
            } );
            //
            const submitButton = form.querySelector( '[data-modal-action="submit"]' );
            submitButton.addEventListener( 'click', function ( ev ) {
                ev.preventDefault();
                //
                const formData = new FormData( form );
                if ( form.querySelector( '[name="user_id"]' ).value ) {
                    formData.append( 'acc', 'updateUser' );
                } else {
                    formData.append( 'acc', 'createUser' );
                }
                //
                submitRequest( module, formData, '#userModal' )
                    .then( ( response ) => {
                        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.close_modal ) {
                            modal.hide();
                        }

                        if ( response.reload_table ) {
                            table.ajax.reload(null, false);
                        }

                        Swal.fire( {
                            title: title,
                            text: msg,
                            icon: icon
                        } ).then( function () {
                            if ( response.reload ) {
                                location.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 () {
                tableEl = document.getElementById( 'table-config-users' );

                modalEl = document.getElementById( 'userModal' );
                modalTitle = modalEl.querySelector( '.modal-title' );
                modal = new bootstrap.Modal( modalEl );

                form = modalEl.querySelector( '#userForm' );

                filterModalEl = document.getElementById( 'filterModal' );
                filterModal = new bootstrap.Modal( filterModalEl );

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

                handleForm();
                handleModal();
                initDataTable();
            },
            filterReset: function () {
                [ ...filterModalEl.querySelectorAll( '.datatable-input' ) ].map( ( input ) => {
                    input.value = '';
                    table.column( input.dataset.colIndex ).search( '', false, false );
                } );
                table.table().draw();
            },
            add: function () {
                // Consultamos los perfiles disponibles
                let formData = new FormData();
                formData.append( 'acc', 'getProfiles' );
                formData.append( 'length', '50' );
                //
                submitRequest( module, formData )
                    .then( ( response ) => {
                        const profiles = response.data.profiles;
                        form.querySelector( '[name="profile"]' ).appendChild( new Option( 'Seleccione un perfil', '', false, false ) );
                        for ( const [ index, obj ] of Object.entries( profiles.data ) ) {
                            form.querySelector( '[name="profile"]' ).appendChild( new Option( obj.name, obj.id, false, false ) );
                        }

                        modalTitle.innerText = 'Nuevo Usuario';
                        modal.show();
                    } )
                    .catch( ( error ) => {
                        Swal.fire( { title: '', text: error, icon: 'error' } );
                    } );
            },
            edit: function ( id ) {
                let formData = new FormData();
                formData.append( 'acc', 'getUser' );
                formData.append( 'id', id );
                formData.append( 'length', '50' );
                //
                submitRequest( module, formData )
                    .then( ( response ) => {
                        const user = response.data.user;
                        //
                        form.querySelector( '[name="user_id"]' ).value = id;
                        form.querySelector( '[name="name"]' ).value = user.name;
                        form.querySelector( '[name="lastname"]' ).value = user.lastname;
                        form.querySelector( '[name="email"]' ).value = user.email;
                        form.querySelector( '[name="country_code"]' ).value = user?.country_code;
                        form.querySelector( '[name="telephone_number"]' ).value = user?.telephone_number;
                        // Limpiamos las opciones previas
                        form.querySelector( '[name="profile"]' ).innerHTML = '';
                        // Agregamos una opción por default
                        form.querySelector( '[name="profile"]' ).appendChild( new Option( 'Seleccione un perfil', '', false, false ) );
                        //
                        const profiles = response.data.profiles;
                        for ( const [ index, obj ] of Object.entries( profiles.data ) ) {
                            form.querySelector( '[name="profile"]' ).appendChild( new Option( obj.name, obj.id, true, obj.id === user.profile ) );
                        }
                        //
                        modalTitle.innerText = 'Actualizar Usuario';
                        modal.show();
                    } )
                    .catch( ( error ) => {
                        Swal.fire( { title: '', text: error, icon: 'error' } );
                    } );
            },
            switchStatus: function ( name, id, status ) {
                let typeStatus = status === 'enable' ? 'habilitar' : 'deshabilitar';

                Swal.fire( {
                    title: `¿Está seguro de querer ${ typeStatus } al usuario ${ name }?`,
                    icon: 'warning',
                    showCancelButton: true,
                    reverseButtons: true,
                    showLoaderOnConfirm: true,
                    preConfirm: async () => {
                        const data = new FormData();
                        data.append( 'acc', 'switchUserStatus' );
                        data.append( 'user_id', id );
                        data.append( 'status', status );

                        try {
                            var response = await fetch( module, {
                                headers: { "X-Custom-Fetch": "true" },
                                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: () => !Swal.isLoading(),
                    backdrop: true
                } ).then( ( result ) => {
                    if ( result.isConfirmed ) {
                        Swal.fire( {
                            title: result.value.message,
                            icon: 'success',
                            showConfirmButton: false,
                            timer: 2000,
                            timerProgressBar: true,
                            allowOutsideClick: false,
                            allowEscapeKey: false,
                            didDestroy: () => {
                                table.ajax.reload(null, false);
                            }
                        } );
                    }
                } );
            },
            resetPassword: function ( email, id ) {
                Swal.fire( {
                    title: `¿Está seguro de querer restablecer la contraseña del usuario ${ email }?`,
                    icon: 'warning',
                    confirmButtonText: 'Si',
                    showCancelButton: true,
                    cancelButtonText: 'No',
                    focusCancel: true,
                    showLoaderOnConfirm: true,
                    allowEscapeKey: false,
                    preConfirm: async () => {
                        const data = new FormData();
                        data.append( 'acc', 'restartPassword' );
                        data.append( 'user_id', id );

                        try {
                            var response = await fetch( module, {
                                headers: { "X-Custom-Fetch": "true" },
                                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: () => !Swal.isLoading(),
                    backdrop: true
                } ).then( ( result ) => {
                    if ( result.isConfirmed ) {
                        Swal.fire( {
                            title: result.value.message,
                            icon: "success"
                        } ).then( ( result ) => {
                            if ( result.isConfirmed ) {
                                table.ajax.reload(null, false);
                            }
                        } );
                    }
                } );
            },
            destroySessions: function ( id ) {

            }
        }
    }();

    window.addEventListener( 'DOMContentLoaded', function ( e ) {
        Users.init();
    } );

    // ===== MANEJO DE PERMISOS PERSONALIZADOS =====

    // Variable global para almacenar ACL del perfil actual
    window.currentProfileACL = null;

    // Toggle de container de permisos personalizados
    document.addEventListener('DOMContentLoaded', function() {
        const hasCustomACLCheckbox = document.getElementById('hasCustomACL');
        if (hasCustomACLCheckbox) {
            hasCustomACLCheckbox.addEventListener('change', function(e) {
                const container = document.getElementById('custom-acl-container');
                if (e.target.checked) {
                    container.style.display = 'block';
                } else {
                    container.style.display = 'none';
                    // Limpiar checkboxes si se desmarca
                    container.querySelectorAll('input[type="checkbox"]').forEach(cb => cb.checked = false);
                }
            });
        }
    });

    /**
     * Compara permisos de usuario vs perfil y actualiza badges de estado
     */
    function compareWithProfilePermissions(userACL, profileACL) {
        document.querySelectorAll('.permission-status').forEach(badge => {
            const module = badge.dataset.module;
            const group = badge.dataset.group;

            const userPerms = userACL?.[group]?.[module] || null;
            const profilePerms = profileACL?.[group]?.[module] || null;

            if (userPerms === null) {
                // Heredado del perfil (sin override)
                badge.className = 'badge bg-success permission-status';
                badge.textContent = 'Heredado';
            } else if (JSON.stringify(userPerms) === JSON.stringify(profilePerms)) {
                // Igual al perfil (redundante, sin cambios)
                badge.className = 'badge bg-info permission-status';
                badge.textContent = 'Sin cambios';
            } else if (userPerms.length === 0) {
                // Revocado explícitamente
                badge.className = 'badge bg-danger permission-status';
                badge.textContent = 'Revocado';
            } else if (profilePerms === null) {
                // Permiso adicional no presente en perfil
                badge.className = 'badge bg-primary permission-status';
                badge.textContent = 'Adicional';
            } else {
                // Modificado (override)
                badge.className = 'badge bg-warning permission-status';
                badge.textContent = 'Modificado';
            }
        });
    }

    /**
     * Carga checkboxes de ACL desde datos
     */
    function loadACLCheckboxes(acl) {
        // Limpiar todos los checkboxes primero
        document.querySelectorAll('input[name^="acl["]').forEach(cb => cb.checked = false);

        // Marcar checkboxes según ACL
        for (const groupId in acl) {
            for (const moduleKey in acl[groupId]) {
                const permissions = acl[groupId][moduleKey];
                if (Array.isArray(permissions)) {
                    permissions.forEach(perm => {
                        const checkbox = document.querySelector(
                            `input[name="acl[${groupId}][${moduleKey}][]"][value="${perm}"]`
                        );
                        if (checkbox) {
                            checkbox.checked = true;
                        }
                    });
                }
            }
        }
    }

    // Extender la función edit existente
    const originalEdit = Users.edit;
    Users.edit = function(user_id) {
        // Llamar a la función original
        originalEdit.call(this, user_id);

        // Después de cargar usuario, manejar permisos personalizados
        let formData = new FormData();
        formData.append('acc', 'getUser');
        formData.append('id', user_id);

        fetch('./?a=config.users', {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(response => {
            const user = response.data.user;
            const profileACL = response.data.profile_acl;

            // Guardar ACL del perfil en variable global
            window.currentProfileACL = profileACL;

            // Si tiene ACL personalizado
            if (user.acl) {
                document.getElementById('hasCustomACL').checked = true;
                document.getElementById('custom-acl-container').style.display = 'block';

                loadACLCheckboxes(user.acl);
                compareWithProfilePermissions(user.acl, profileACL);
            } else {
                document.getElementById('hasCustomACL').checked = false;
                document.getElementById('custom-acl-container').style.display = 'none';
            }
        })
        .catch(error => {
            console.error('Error loading user ACL:', error);
        });
    };

    // Al cambiar permisos, actualizar badges
    document.addEventListener('change', function(e) {
        if (e.target.matches('input[name^="acl["]')) {
            // Recopilar ACL actual del formulario
            const currentACL = {};
            document.querySelectorAll('input[name^="acl["]:checked').forEach(cb => {
                // Parsear name: acl[GROUP_ID][MODULE_KEY][]
                const match = cb.name.match(/acl\[([^\]]+)\]\[([^\]]+)\]\[\]/);
                if (match) {
                    const [, groupId, moduleKey] = match;
                    if (!currentACL[groupId]) currentACL[groupId] = {};
                    if (!currentACL[groupId][moduleKey]) currentACL[groupId][moduleKey] = [];
                    currentACL[groupId][moduleKey].push(cb.value);
                }
            });

            // Obtener ACL del perfil (guardado en variable global al cargar)
            if (window.currentProfileACL) {
                compareWithProfilePermissions(currentACL, window.currentProfileACL);
            }
        }
    });
</script>