<!-- Container Principal -->
<div x-data="modals" @keydown.escape="closeModal" class="bg-white rounded-lg shadow">
    <div class="container mx-auto p-6 w-full">
        <!-- Page header -->
        <div class="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4 mb-6">
            <div>
                <h1 class="text-2xl font-bold">Roles</h1>
                <p class="text-xs text-slate-500 mt-0.5">Gestión de roles y permisos</p>
            </div>
            <div class="flex items-center gap-3">
                <!-- Búsqueda -->
                <div class="relative">
                    <div class="absolute left-2.5 top-1/2 -translate-y-1/2 text-slate-400 pointer-events-none">
                        <svg xmlns="http://www.w3.org/2000/svg" class="h-3.5 w-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
                            <path stroke-linecap="round" stroke-linejoin="round" d="M21 21l-5.197-5.197m0 0A7.5 7.5 0 105.196 5.196a7.5 7.5 0 0010.607 10.607z"/>
                        </svg>
                    </div>
                    <input type="text" x-model="searchQuery" placeholder="Buscar..."
                           class="border border-gray-300 rounded w-full md:w-56" @input="loadRegister()">
                    <div x-show="isLoading" class="absolute right-2.5 top-1/2 -translate-y-1/2">
                        <svg class="animate-spin h-3.5 w-3.5 text-slate-400" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                            <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                            <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8v4a4 4 0 00-4 4H4z"></path>
                        </svg>
                    </div>
                </div>
                <!-- Nuevo -->
                <button class="flex items-center gap-2 text-white text-sm font-medium px-4 py-2 rounded-lg transition-colors"
                        style="background-color:#8eb02f"
                        onmouseover="this.style.backgroundColor='#6d8c24'"
                        onmouseout="this.style.backgroundColor='#8eb02f'"
                        x-on:click="addModal=true">
                    <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2.5">
                        <path stroke-linecap="round" stroke-linejoin="round" d="M12 4.5v15m7.5-7.5h-15"/>
                    </svg>
                    Nuevo rol
                </button>
            </div>
        </div>

        <!-- Agregar el GIF de carga -->
        <div x-show="loading" class="fixed inset-0 bg-gray-800 bg-opacity-75 flex z-50 justify-center items-center">
            <img src="../img/loading.gif" alt="Cargando..." class="w-16 h-16" />
        </div>

        <div class="overflow-x-auto max-w-full">
            <!-- Tabla de registros -->
            <table class=" table-auto w-full">
                <thead class="text-sm  text-left py-4  border-b border-gray-300">
                    <tr class="text-left font-semibold border-collapse">
                        <th class="py-2 px-4 border-b w-52 ">Nombre</th>
                        <th class="py-2 px-4 border-b">Descripción</th>
                        <th class="py-2 px-4 border-b">Submodulos</th>
                        <th class="py-2 px-4 border-b w-28">Portal</th>
                        <th class="py-2 px-4 border-b w-40">Página principal</th>
                        <th class="py-2 px-4 border-b w-32"></th>
                    </tr>
                </thead>
                <tbody class="text-gray-500 select-none text-sm ">
                    <!-- Mensaje de Carga Inicial -->
                    <tr class="hover:bg-gray-100" x-show="isLoading">
                        <td colspan="" class="py-2 px-4 border-b text-center w-full">
                            <div class="text-center mx-auto justify-center flex space-x-2">
                                <!-- SVG de cargando (puedes reemplazarlo con un botón si lo prefieres) -->
                                <svg class="animate-spin h-5 w-5 mx-1 text-gray-500" xmlns="http://www.w3.org/2000/svg"
                                    fill="none" viewBox="0 0 24 24">
                                    <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor"
                                        stroke-width="4">
                                    </circle>
                                    <path class="opacity-75" fill="currentColor"
                                        d="M4 12a8 8 0 018-8v4a4 4 0 00-4 4H4z">
                                    </path>
                                </svg>
                                Cargando registros...
                            </div>
                        </td>
                    </tr>
                    <!-- Itera sobre los roles -->
                    <template x-for="registro in registros" :key="registro.ID">
                        <tr class="hover:bg-gray-100" :data-role-id="registro.ID">
                            <td class="py-3 text-xs px-4 border-b" x-text="registro.name"></td>
                            <td class="py-3 text-xs px-4 border-b" x-text="registro.description"></td>
                            <td class="py-3 text-xs px-4 border-b">
                                <!-- Itera sobre los submódulos de un rol -->
                                <template x-for="submodule in registro.submodules" :key="submodule.ID">
                                    <span x-text="submodule.title"
                                        class="rounded bg-green-100 text-green-600 p-1 mr-2 mb-1 inline-block">
                                    </span>
                                </template>
                            </td>
                            <td class="py-3 text-xs px-4 border-b">
                                <div class="flex flex-col gap-1">
                                    <template x-if="registro.es_portal_cliente">
                                        <span class="bg-blue-100 text-blue-700 px-2 py-0.5 rounded text-xs font-medium">Usuario Final</span>
                                    </template>
                                    <template x-if="registro.es_portal_partner">
                                        <span class="bg-purple-100 text-purple-700 px-2 py-0.5 rounded text-xs font-medium">Partner</span>
                                    </template>
                                </div>
                            </td>
                            <td class="py-3 text-xs px-4 border-b">
                                <span x-text="registro.home_url || 'Predeterminada'" class="text-xs text-slate-500"></span>
                            </td>
                            <td class="py-3 text-xs px-4 border-b ">
                                <div class="flex justify-between space-x-1">
                                    <button
                                        @click="viewModal = true; Name = registro.name; Description = registro.description; Submodules = registro.submodules;"
                                        title="Ver">
                                        <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24"
                                            stroke-width="1.5" stroke="currentColor" class="w-5 text-[#8eb02f]">
                                            <path stroke-linecap="round" stroke-linejoin="round"
                                                d="M2.036 12.322a1.012 1.012 0 0 1 0-.639C3.423 7.51 7.36 4.5 12 4.5c4.638 0 8.573 3.007 9.963 7.178.07.207.07.431 0 .639C20.577 16.49 16.64 19.5 12 19.5c-4.638 0-8.573-3.007-9.963-7.178Z" />
                                            <path stroke-linecap="round" stroke-linejoin="round"
                                                d="M15 12a3 3 0 1 1-6 0 3 3 0 0 1 6 0Z" />
                                        </svg>
                                    </button>
                                    <button @click="
                                    editModal = true;
                                    Id = registro.ID;
                                    Name = registro.name;
                                    Description = registro.description;
                                    Submodules = [...registro.submodules];
                                    ConxDBs = [...(registro.conx_dbs || [])];
                                    EsPortalCliente = registro.es_portal_cliente || false;
                                    EsPortalPartner = registro.es_portal_partner || false;
                                    HomeUrl = registro.home_url || '';
                                    modulos.forEach(modulo => {
                                        modulo.submodules.forEach(submodulo => {
                                            submodulo.checked = Submodules.some(sm => sm.ID === submodulo.ID);
                                        });
                                    });
                                    " title="Editar">
                                        <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24"
                                            stroke-width="1.5" stroke="currentColor" class="w-5">
                                            <path stroke-linecap="round" stroke-linejoin="round"
                                                d="m16.862 4.487 1.687-1.688a1.875 1.875 0 1 1 2.652 2.652L10.582 16.07a4.5 4.5 0 0 1-1.897 1.13L6 18l.8-2.685a4.5 4.5 0 0 1 1.13-1.897l8.932-8.931Zm0 0L19.5 7.125M18 14v4.75A2.25 2.25 0 0 1 15.75 21H5.25A2.25 2.25 0 0 1 3 18.75V8.25A2.25 2.25 0 0 1 5.25 6H10" />
                                        </svg>
                                    </button>
                                    <button @click="showConfirmModal = true; deleteId = registro.ID;" title="Eliminar">
                                        <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24"
                                            stroke-width="1.5" stroke="currentColor" class="w-5 text-red-500">
                                            <path stroke-linecap="round" stroke-linejoin="round"
                                                d="m14.74 9-.346 9m-4.788 0L9.26 9m9.968-3.21c.342.052.682.107 1.022.166m-1.022-.165L18.16 19.673a2.25 2.25 0 0 1-2.244 2.077H8.084a2.25 2.25 0 0 1-2.244-2.077L4.772 5.79m14.456 0a48.108 48.108 0 0 0-3.478-.397m-12 .562c.34-.059.68-.114 1.022-.165m0 0a48.11 48.11 0 0 1 3.478-.397m7.5 0v-.916c0-1.18-.91-2.164-2.09-2.201a51.964 51.964 0 0 0-3.32 0c-1.18.037-2.09 1.022-2.09 2.201v.916m7.5 0a48.667 48.667 0 0 0-7.5 0" />
                                        </svg>
                                    </button>

                                </div>

                            </td>
                        </tr>
                    </template>

                    <tr x-show="sinregistro">
                        <td colspan="3" class="py-2 px-4 border-b text-center">No hay registros disponibles.</td>
                    </tr>
                </tbody>
            </table>
        </div>

        <div>
            <!-- Los botones de paginación se generarán aquí -->
            <div id="pagination" class="flex justify-left my-4 text-sm">
            </div>
            <!-- Mostrar conteo de registros -->
            <div id="recordCountDiv" class="text-sm text-gray-700 ml-4">

            </div>
        </div>
    </div>

    <!-- Modal Ver -->
    <div x-cloak x-show="viewModal" x-transition
        class="fixed inset-0 bg-gray-800 bg-opacity-75 flex z-40 justify-center items-center text-sm">
        <div class="bg-white p-6 rounded shadow-lg max-w-lg w-full overflow-y-auto max-h-full">
            <h2 class="text-xl font-bold mb-2">Ver registro</h2>
            <p class="font-semibold" x-text="Name"></p>
            <p class="mt-2" x-text="Description"></p>

            <h3 class="mt-4 font-bold">Submódulos:</h3>

            <div class="mt-2 flex flex-wrap gap-2">
                <template x-for="submodule in Submodules" :key="submodule.ID">
                    <span x-text="submodule.title" class="block rounded bg-green-100 text-green-600 p-1"></span>
                </template>
            </div>

            <button class="mt-4 bg-[#8eb02f] text-white px-4 py-2 rounded"
                x-on:click="viewModal = false">Cerrar</button>
        </div>
    </div>


    <!-- Modal Editar -->
    <div x-cloak x-show="editModal" x-transition
        class="fixed inset-0 bg-gray-800 bg-opacity-75 flex z-40 justify-center items-center text-sm">
        <div class="bg-white p-6 rounded shadow-lg max-w-lg w-full overflow-y-auto max-h-full">
            <h2 class="text-xl font-bold mb-2">Editar registro</h2>
            <form @submit.prevent="submitEdit">
                <label class="block mb-2" for="editName">Nombre</label>
                <input type="text" id="editName" x-model="Name" placeholder="Nombre"
                    class="border border-gray-300 rounded w-full p-2" required>
                <label class="block mt-4 mb-2" for="editDescription">Descripción</label>
                <textarea id="editDescription" x-model="Description" placeholder="Descripción"
                    class="border border-gray-300 rounded w-full p-2" required></textarea>
                <div class="mt-4">
                    <label class="block mt-4 mb-2 col-span-2">Seleccionar Submódulos</label>

                    <template x-for="modulo in modulos" :key="modulo.ID">
                        <div>
                            <!-- Nombre del módulo -->
                            <div class="mb-1">
                                <label :for="'modulo-' + modulo.ID" x-text="modulo.title"
                                    class="font-bold text-sm"></label>
                            </div>
    
                            <!-- Lista de submódulos -->
                            <div class="grid grid-cols-2 gap-1 p-2 mb-2 border rounded-md">
                                <template x-for="submodulo in modulo.submodules" :key="submodulo.ID">
                                    <div>
                                        <!-- Sincronizar el estado del checkbox con los submódulos seleccionados -->
                                        <input type="checkbox" :value="submodulo.ID" :id="'submodulo-' + submodulo.ID"
                                            x-model="submodulo.checked"
                                            :checked="Submodules.some(sm => sm.ID === submodulo.ID)" class="mr-2">
                                        <label :for="'submodulo-' + submodulo.ID" x-text="submodulo.title"></label>
                                    </div>
                                </template>
                            </div>
                        </div>
                    </template>
                </div>
                <div class="mt-4 p-3 border rounded-md bg-slate-50">
                    <p class="font-semibold text-sm mb-2">Tipo de acceso Portal</p>
                    <div class="flex gap-6">
                        <label class="flex items-center gap-2 text-sm cursor-pointer">
                            <input type="checkbox" x-model="EsPortalCliente" @change="if(EsPortalCliente) EsPortalPartner=false" class="rounded">
                            Usuario Final (Cliente)
                        </label>
                        <label class="flex items-center gap-2 text-sm cursor-pointer">
                            <input type="checkbox" x-model="EsPortalPartner" @change="if(EsPortalPartner) EsPortalCliente=false" class="rounded">
                            Partner
                        </label>
                    </div>
                </div>
                <div class="mt-4 p-3 border rounded-md bg-slate-50">
                    <label class="font-semibold text-sm mb-2 block" for="editHomeUrl">Página principal después del login</label>
                    <select id="editHomeUrl" x-model="HomeUrl"
                        class="border border-gray-300 rounded w-full p-2 text-sm">
                        <option value="">Predeterminada (/app/servidor)</option>
                        <template x-for="modulo in modulos" :key="modulo.ID">
                            <optgroup :label="modulo.title">
                                <template x-for="submodulo in modulo.submodules" :key="submodulo.ID">
                                    <option :value="submodulo.url" x-text="submodulo.title + ' (' + submodulo.url + ')'"></option>
                                </template>
                            </optgroup>
                        </template>
                    </select>
                </div>
                <div class="mt-4 p-3 border rounded-md bg-slate-50">
                    <p class="font-semibold text-sm mb-2">Bases de datos permitidas (Query Runner)</p>
                    <div class="grid grid-cols-2 gap-1 max-h-32 overflow-y-auto">
                        <template x-for="con in conexiones" :key="con.ID">
                            <div>
                                <input type="checkbox" :value="con.ID" :id="'edit-conxdb-' + con.ID"
                                    :checked="ConxDBs.some(c => c.ID === con.ID)"
                                    @change="if($event.target.checked) { ConxDBs.push(con) } else { ConxDBs = ConxDBs.filter(c => c.ID !== con.ID) }"
                                    class="mr-2">
                                <label :for="'edit-conxdb-' + con.ID" x-text="con.nombre" class="text-xs"></label>
                            </div>
                        </template>
                    </div>
                </div>
                <div class="mt-4 flex justify-between">
                    <button type="submit" class="bg-[#8eb02f] text-white px-4 py-2 rounded">Guardar Cambios</button>
                    <button type="button" class="bg-gray-600 text-white px-4 py-2 rounded"
                        x-on:click="editModal = false">Cancelar</button>
                </div>
            </form>
        </div>
    </div>


    <!-- Modal Añadir -->
    <div x-cloak x-show="addModal" x-transition
        class="fixed inset-0 bg-gray-800 bg-opacity-75 flex z-40 justify-center items-center text-sm">
        <div class="bg-white p-6 rounded shadow-lg max-w-lg w-full overflow-y-auto max-h-full">
            <h2 class="text-xl font-bold mb-2">Agregar registro</h2>
            <form @submit.prevent="submitAdd">
                <label class="block mb-2" for="name">Título</label>
                <input type="text" id="name" x-model="newName" placeholder="Nombre"
                    class="border border-gray-300 rounded w-full p-2" required>

                <label class="block mt-4 mb-2" for="description">Descripción</label>
                <textarea id="description" x-model="newDescription" placeholder="Descripción"
                    class="border border-gray-300 rounded w-full p-2" required></textarea>

                <!-- Checkboxes para seleccionar submódulos -->
                <label class="block mt-4 mb-2 col-span-2">Seleccionar Submódulos</label>

                <template x-for="modulo in modulos" :key="modulo.ID">
                    <div>
                        <div class="mb-1">
                            <label :for="'modulo-' + modulo.ID" x-text="modulo.title" class="font-bold text-sm"></label>
                        </div>

                        <div class="grid grid-cols-2 gap-1 p-2 mb-2 border rounded-md">
                            <template x-for="submodulo in modulo.submodules" :key="submodulo.ID">
                                <div>
                                    <input type="checkbox" :value="submodulo.ID" :id="'submodulo-' + submodulo.ID"
                                        x-model="submodulo.checked" class="mr-2">
                                    <label :for="'submodulo-' + submodulo.ID" x-text="submodulo.title"></label>
                                </div>
                            </template>
                        </div>
                    </div>
                </template>
                <div class="mt-4 p-3 border rounded-md bg-slate-50">
                    <p class="font-semibold text-sm mb-2">Tipo de acceso Portal</p>
                    <div class="flex gap-6">
                        <label class="flex items-center gap-2 text-sm cursor-pointer">
                            <input type="checkbox" x-model="newEsPortalCliente" @change="if(newEsPortalCliente) newEsPortalPartner=false" class="rounded">
                            Usuario Final (Cliente)
                        </label>
                        <label class="flex items-center gap-2 text-sm cursor-pointer">
                            <input type="checkbox" x-model="newEsPortalPartner" @change="if(newEsPortalPartner) newEsPortalCliente=false" class="rounded">
                            Partner
                        </label>
                    </div>
                </div>

                <div class="mt-4 p-3 border rounded-md bg-slate-50">
                    <label class="font-semibold text-sm mb-2 block" for="addHomeUrl">Página principal después del login</label>
                    <select id="addHomeUrl" x-model="newHomeUrl"
                        class="border border-gray-300 rounded w-full p-2 text-sm">
                        <option value="">Predeterminada (/app/servidor)</option>
                        <template x-for="modulo in modulos" :key="modulo.ID">
                            <optgroup :label="modulo.title">
                                <template x-for="submodulo in modulo.submodules" :key="submodulo.ID">
                                    <option :value="submodulo.url" x-text="submodulo.title + ' (' + submodulo.url + ')'"></option>
                                </template>
                            </optgroup>
                        </template>
                    </select>
                </div>
                <div class="mt-4 p-3 border rounded-md bg-slate-50">
                    <p class="font-semibold text-sm mb-2">Bases de datos permitidas (Query Runner)</p>
                    <div class="grid grid-cols-2 gap-1 max-h-32 overflow-y-auto">
                        <template x-for="con in conexiones" :key="con.ID">
                            <div>
                                <input type="checkbox" :value="con.ID" :id="'add-conxdb-' + con.ID"
                                    :checked="newConxDBs.some(c => c.ID === con.ID)"
                                    @change="if($event.target.checked) { newConxDBs.push(con) } else { newConxDBs = newConxDBs.filter(c => c.ID !== con.ID) }"
                                    class="mr-2">
                                <label :for="'add-conxdb-' + con.ID" x-text="con.nombre" class="text-xs"></label>
                            </div>
                        </template>
                    </div>
                </div>
                <div class="mt-4 flex justify-between">
                    <button type="submit" class="bg-[#8eb02f] text-white px-4 py-2 rounded">Guardar</button>
                    <button type="button" class="bg-gray-600 text-white px-4 py-2 rounded"
                        x-on:click="closeModal">Cancelar</button>
                </div>
            </form>
        </div>
    </div>


    <!-- Modal Confirmar Eliminación -->
    <div x-cloak x-show="showConfirmModal" x-transition
        class="fixed inset-0 bg-gray-800 bg-opacity-75 flex z-40 justify-center items-center text-sm">
        <div class="bg-white p-6 rounded shadow-lg max-w-sm w-full overflow-y-auto max-h-full">
            <h2 class="text-xl font-bold mb-4">Confirmar Eliminación</h2>
            <p>¿Estás seguro de que deseas eliminar este registro?</p>
            <div class="mt-4 flex justify-end">
                <button class="bg-red-500 text-white px-4 py-2 rounded mr-2" @click="deleteItem()">Eliminar</button>
                <button @click="closeModal" class="bg-gray-600 text-white px-4 py-2 rounded">Cancelar</button>
            </div>
        </div>
    </div>

    <!-- Alpine.js Script -->



    <script>
        document.addEventListener('alpine:init', () => {
            Alpine.data('modals', () => ({
                viewModal: false,
                addModal: false,
                editModal: false,
                showConfirmModal: false,

                newName: '',
                newDescription: '',
                newEsPortalCliente: false,
                newEsPortalPartner: false,
                newHomeUrl: '',

                Name: '',
                Description: '',
                EsPortalCliente: false,
                EsPortalPartner: false,
                HomeUrl: '',
                modulos: [],
                Submodules: [],
                submodulos: [],

                sinregistro: '',
                modules: [],
                conexiones: [],
                ConxDBs: [],
                newConxDBs: [],



                Id: null,
                deleteId: null,
                loading: false,
                totalRecords: 0, // Agregar esta línea
                isLoading: false,
                selectedModules: '',
                selectedSubmodules: '',
                registros: '',


                init() {
                    this.loadRegister();
                },
                //CARGAR registros
                searchQuery: '', // Agrega esta línea dentro del objeto Alpine

                // Modifica la función loadRegister para incluir la búsqueda
                loadRegister(page = 1) {
                    this.isLoading = true;
                    //this.loading = true;
                    const search = this.searchQuery ? `&search=${this.searchQuery}` : '';
                    fetch(`/app/loadroles?page=${page}${search}`)
                        .then(response => response.json())
                        .then(data => {
                            this.totalRecords = data.total;
                            this.modulos = data.modules;
                            this.registros = data.roles;
                            this.conexiones = data.conexiones || [];
                            this.totalPages = data.totalPages;
                            this.createPagination(this.totalPages, page);
                            if (data.roles.length === 0) {
                                this.sinregistro = true;
                            } else {
                                // Lógica de paginación
                                const totalPages = Math.ceil(this.totalRecords / data.limit);
                                this.createPagination(totalPages, page)
                            }
                        })
                        .catch(error => console.error('Error:', error))
                        .finally(() => {
                            this.isLoading = false; // Ocultar el GIF de carga
                        });
                },
                createPagination(totalPages, currentPage) {
                    const paginationContainer = document.getElementById('pagination');
                    paginationContainer.innerHTML = ''; // Limpiar la paginación actual

                    // Crear un contenedor para los botones de paginación
                    const paginationButtonsContainer = document.createElement('div');
                    paginationButtonsContainer.className = "md:flex mx-auto mb-2 md:justify-between items-center w-full"; // Alinear los botones

                    // Función para crear un botón
                    const createButton = (text, isDisabled, onClick, additionalClasses = '') => {
                        const button = document.createElement('button');
                        button.textContent = text;
                        button.disabled = isDisabled;
                        button.className = `px-4 py-2 text-black bg-gray-200 ${additionalClasses} ${isDisabled ? 'opacity-50 cursor-not-allowed' : 'hover:bg-gray-300'}`;
                        if (!isDisabled) {
                            button.onclick = onClick;
                        }
                        return button;
                    };

                    // Botones de paginación
                    const leftContainer = document.createElement('div');
                    leftContainer.className = "md:flex text-center mb-2"; // Contenedor para los botones de paginación a la izquierda
                    leftContainer.appendChild(createButton('Anterior', currentPage === 1, () => this.loadRegister(currentPage - 1), 'rounded-l-md'));

                    for (let i = 1; i <= totalPages; i++) {
                        const pageButton = createButton(i, false, () => this.loadRegister(i), `mx-1 ${i === currentPage ? 'bg-black text-gray-50' : 'bg-white text-black'} rounded-md`);
                        leftContainer.appendChild(pageButton);
                    }

                    leftContainer.appendChild(createButton('Siguiente', currentPage === totalPages, () => this.loadRegister(currentPage + 1), 'rounded-r-md'));

                    paginationButtonsContainer.appendChild(leftContainer);

                    // Agregar el conteo de registros a la derecha
                    const recordCountDiv = document.createElement('div');
                    const startRecord = (currentPage - 1) * 10 + 1; // Primer registro de la página actual
                    const endRecord = Math.min(currentPage * 10, this.totalRecords); // Último registro mostrado
                    recordCountDiv.className = "text-sm text-gray-700 text-center md:ml-auto"; // Sin margen para alineación a la izquierda
                    recordCountDiv.innerHTML = `Mostrando ${startRecord} a ${endRecord} de ${this.totalRecords} registros`;

                    paginationButtonsContainer.appendChild(recordCountDiv);

                    // Agregar los botones de paginación al contenedor principal
                    paginationContainer.appendChild(paginationButtonsContainer);
                },

                //CERRAR MODALES
                closeModal() {
                    this.addModal = false;
                    this.editModal = false;
                    this.viewModal = false;
                    this.showConfirmModal = false;
                },
                //CREAR
                submitAdd() {
                    this.loading = true;

                    const selectedSubmodules = this.modulos
                        .map(modulo => {
                            return {
                                ...modulo, 
                                submodules: modulo.submodules.filter(submodulo => submodulo.checked) 
                            };
                        })
                        .filter(modulo => modulo.submodules.length > 0);

                    const requestData = {
                        name: this.newName,
                        description: this.newDescription,
                        es_portal_cliente: this.newEsPortalCliente,
                        es_portal_partner: this.newEsPortalPartner,
                        home_url: this.newHomeUrl,
                        submodules: selectedSubmodules.flatMap(modulo => modulo.submodules),
                        conx_dbs: this.newConxDBs
                    };

                    fetch('/app/roles', {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify(requestData)
                    })
                        .then(response => response.json())
                        .then(() => {
                            this.newName = '';
                            this.newDescription = '';
                            this.newEsPortalCliente = false;
                            this.newEsPortalPartner = false;
                            this.newConxDBs = [];
                            this.modulos.forEach(modulo => {
                                modulo.submodules.forEach(submodulo => submodulo.checked = false);
                            });

                            this.closeModal();
                            this.loadRegister();
                        })
                        .catch(error => console.error('Error:', error))
                        .finally(() => {
                            this.loading = false;
                        });
                }
                ,

                //ACTUALIZAR
                submitEdit() {
                    this.loading = true;

                    const submodulosSeleccionados = new Set();

                    this.modulos.forEach(modulo => {
                        modulo.submodules.forEach(submodulo => {
                            if (submodulo.checked) {
                                submodulosSeleccionados.add(submodulo.ID);
                            }
                        });
                    });

                    if (submodulosSeleccionados.size === 0) {
                        this.submodulos = [];
                    } else {
                        this.submodulos = Array.from(submodulosSeleccionados).map(id => {
                            return this.modulos.flatMap(modulo => modulo.submodules).find(sub => sub.ID === id);
                        });
                    }

                    console.log('Submódulos seleccionados despues:', this.submodulos);

                    fetch(`/app/roles/${this.Id}`, {
                        method: 'PUT',
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify({
                            name: this.Name,
                            description: this.Description,
                            es_portal_cliente: this.EsPortalCliente,
                            es_portal_partner: this.EsPortalPartner,
                            home_url: this.HomeUrl,
                            submodules: this.submodulos,
                            conx_dbs: this.ConxDBs
                        })
                    })
                        .then(response => response.json())
                        .then(() => {
                            this.Name = '';
                            this.Description = '';
                            this.EsPortalCliente = false;
                            this.EsPortalPartner = false;
                            this.submodulos = [];
                            this.ConxDBs = [];
                            this.modulos.forEach(modulo => {
                                modulo.submodules.forEach(submodulo => {
                                    submodulo.checked = false; 
                                });
                            });
                            this.closeModal();
                            this.loadRegister();
                        })
                        .catch(error => console.error('Error:', error))
                        .finally(() => {
                            this.loading = false;
                        });
                },

                //ELIMINAR
                deleteItem() {
                    this.loading = true;
                    fetch(`/app/roles/${this.deleteId}`, {
                        method: 'DELETE',
                        headers: { 'Content-Type': 'application/json' }
                    })
                        .then(() => {
                            this.closeModal();
                            this.loadRegister();
                        })
                        .catch(error => console.error('Error:', error))
                        .finally(() => {
                            this.loading = false; // Ocultar el GIF de carga
                        });
                },
            }));
        });
    </script>
</div>