@extends('layouts.appLayout')

@section('title', 'Gestor de equipo')

@section('content')
<div class="contenido">
    {{-- Filtros --}}
    <div class="filter-section py-4" style="background: url('{{ asset('img/header.jpg') }}') no-repeat center center; background-size: cover;">
        <div class="container">
            <div class="card p-4 rounded shadow">
                <form id="filtro-form" class="row g-3">

                    <!-- Buscar -->
                    <div class="col-md-6 col-lg-6">
                        <input type="text" name="buscar" id="buscar" class="form-control" placeholder="Buscar por nombre, apellido, apodo o correo">
                    </div>

                    <!-- Estado -->
                    <div class="col-md-6 col-lg-3">
                        <select name="estadoUsuario" id="estadoUsuario" class="form-select">
                            <option value="">Estado</option>
                            @foreach($enumValues as $estado)
                                <option value="{{ $estado }}">{{ $estado }}</option>
                            @endforeach
                        </select>
                    </div>

                    <!-- Rol -->
                    <div class="col-md-6 col-lg-3">
                        <select name="filtroPorRol" id="rol" class="form-select">
                            <option value="">Rol</option>
                            @foreach($roles as $rol)
                                <option value="{{ $rol->id }}">{{ $rol->name }}</option>
                            @endforeach
                        </select>
                    </div>

                    <!-- Cursos Completados -->
                    <div class="col-md-6 col-lg-4 mt-4">
                        <label for="completed-courses" class="form-label small">Cursos Completados</label>
                        <input type="range" id="completed-courses" class="form-range" min="0" value="0" step="1">
                        <span id="completed-courses-value" class="text-dark">0</span>
                    </div>

                    <!-- Cursos Comprados -->
                    <div class="col-md-6 col-lg-4 mt-4">
                        <label for="owned-courses" class="form-label small">Cursos Comprados</label>
                        <input type="range" id="owned-courses" class="form-range" min="0" value="0" step="1">
                        <span id="owned-courses-value" class="text-dark">0</span>
                    </div>

                    <!-- Orden -->
                    <div class="col-md-6 col-lg-4 mt-4">
                        <label for="orden" class="form-label small">Orden</label>
                        <select name="orden" id="orden" class="form-select">
                            <option value="desc">Descendente</option>
                            <option value="asc">Ascendente</option>
                        </select>
                    </div>

                    <!-- Planes de suscripción -->
                    <div class="col-12 mt-4 mb-3">
                        <label class="small mb-2">Planes de suscripción</label>
                        <div class="d-flex flex-wrap gap-3">
                            @foreach($subscriptionProducts as $plan)
                                <div class="form-check">
                                    <input class="form-check-input" type="checkbox" name="subscriptionPlans[]" value="{{ $plan->id }}" id="plan-{{ $plan->id }}">
                                    <label class="form-check-label" for="plan-{{ $plan->id }}">
                                        {{ $plan->name }}
                                    </label>
                                </div>
                            @endforeach
                        </div>
                    </div>

                    <!-- Botón Borrar filtros -->
                    <div class="card-footer bg-transparent border-top-0 pb-3 pt-0">
                        <button type="button" class="btn btn1 w-100 m-0" id="reset-filters">Borrar filtros</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    {{-- AÑADIR USUARIO --}}
    <div class="container">
        <div class="row">
            <div class="col-12 text-end">
                <button class="user-create-btn btn btn-warning btn-sm mt-3 mt-md-0" data-bs-toggle="modal" data-bs-target="#createUserModal">
                    Create
                </button>
            </div>
        </div>
    </div>
    <br>

    {{-- Usuarios --}}
    <div class="d-flex justify-content-center flex-wrap" id="usuarios-container">
    </div>

    {{-- EDITAR USUARIO --}}
    <div class="modal fade" id="editUserModal" tabindex="-1" aria-labelledby="editUserModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Edit User</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Cerrar"></button>
                </div>
                <div class="modal-body">
                    <form id="editUserForm">
                        @csrf
                        @method('PUT')
                        <input type="hidden" id="editUserId" name="id">
    
                        <div class="mb-3">
                            <label for="editUserName" class="form-label">Name</label>
                            <input type="text" class="form-control" id="editUserName" name="name" required>
                        </div>
    
                        <div class="mb-3">
                            <label for="editUserSurname" class="form-label">Surname</label>
                            <input type="text" class="form-control" id="editUserSurname" name="surname" required>
                        </div>
    
                        <div class="mb-3">
                            <label for="editUserUsername" class="form-label">Username</label>
                            <input type="text" class="form-control" id="editUserUsername" name="username" required>
                        </div>
    
                        <div class="mb-3">
                            <label for="editUserEmail" class="form-label">Email</label>
                            <input type="email" class="form-control" id="editUserEmail" name="email" required>
                        </div>

                        <div class="mb-3">
                            <label for="editUserPassword" class="form-label">Password</label>
                            <input type="password" class="form-control" id="editUserPassword" name="password">
                            @error('password')
                                <p class="error" style="color: red;">{{ $message }}</p>
                            @enderror
                        </div>
    
                        <div class="mb-3">
                            <label for="editUserRole" class="form-label">Role</label>
                            <select class="form-select" id="editUserRole" name="role_id" required>
                                <!-- Opciones se llenan dinámicamente -->
                                <option value="new">+ New Role</option>
                            </select>
                        </div>

                        <div class="mb-3">
                            <label for="editUserStatus" class="form-label">Status</label>
                            <select class="form-select" id="editUserStatus" name="status" required>
                                @foreach($enumValues as $estado)
                                    <option value="{{ $estado }}">{{ $estado }}</option>
                                @endforeach
                            </select>
                        </div>
    
                        <div class="mb-3">
                            <label for="editUserSubscriptions" class="form-label">Subscriptions</label>
                            <select multiple class="form-select" id="editUserSubscriptions" name="subscriptions[]">
                                <!-- Opciones se llenan dinámicamente -->
                            </select>
                        </div>
    
                        <button type="submit" class="btn btn-warning">Update</button>
                    </form>
                </div>
            </div>
        </div>
    </div>

    {{-- AÑADIR ROL --}}
    <div class="modal fade" id="newRoleModal" tabindex="-1" aria-labelledby="newRoleModalLabel" aria-hidden="true" style="background-color: rgba(0, 0, 0, 0.5);">
        <div class="modal-dialog modal-dialog-centered" style="margin-left: 510px">
            <div class="modal-content">
                <form id="newRoleForm">
                    @csrf
                    <div class="modal-header">
                        <h5 class="modal-title" id="newRoleModalLabel">New Role</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Cerrar"></button>
                    </div>
                    <div class="modal-body">
                        <div class="mb-3">
                            <label for="newRoleName" class="form-label">Nombre del rol</label>
                            <input type="text" class="form-control" id="newRoleName" name="name" required>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="submit" class="btn btn-success">Create and assign</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    {{-- AÑADIR USUARIO --}}
    @if ($errors->any())
        <script>
            window.showCreateUserModal = true;
        </script>
    @endif
    <div class="modal fade" id="createUserModal" tabindex="-1" aria-labelledby="createUserModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">New User</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Cerrar"></button>
                </div>
                <div class="modal-body">
                    <form id="createUserForm" method="POST">
                        @csrf    
                        <div class="mb-3">
                            <label for="createUserName" class="form-label">Name</label>
                            <input type="text" class="form-control" id="createUserName" name="name" value="{{ old('name') }}">
                            @error('name')
                                <p class="error" style="color: red;">{{ $message }}</p>
                            @enderror
                        </div>
    
                        <div class="mb-3">
                            <label for="createUserSurname" class="form-label">Surname</label>
                            <input type="text" class="form-control" id="createUserSurname" name="surname" value="{{ old('surname') }}">
                            @error('surname')
                                <p class="error" style="color: red;">{{ $message }}</p>
                            @enderror
                        </div>
    
                        <div class="mb-3">
                            <label for="createUserUsername" class="form-label">Username</label>
                            <input type="text" class="form-control" id="createUserUsername" name="username" value="{{ old('username') }}">
                            @error('username')
                                <p class="error" style="color: red;">{{ $message }}</p>
                            @enderror
                        </div>
    
                        <div class="mb-3">
                            <label for="createUserEmail" class="form-label">Email</label>
                            <input type="email" class="form-control" id="createUserEmail" name="email" value="{{ old('email') }}">
                            @error('email')
                                <p class="error" style="color: red;">{{ $message }}</p>
                            @enderror
                        </div>
    
                        <div class="mb-3">
                            <label for="createUserPassword" class="form-label">Password</label>
                            <input type="password" class="form-control" id="createUserPassword" name="password">
                            @error('password')
                                <p class="error" style="color: red;">{{ $message }}</p>
                            @enderror
                        </div>
    
                        <div class="mb-3">
                            <label for="createUserPasswordConfirmation" class="form-label">Password Confirmation</label>
                            <input type="password" class="form-control" id="createUserPasswordConfirmation" name="password_confirmation">
                            @error('password_confirmation')
                                <p class="error" style="color: red;">{{ $message }}</p>
                            @enderror
                        </div>
    
                        <div class="mb-3">
                            <label for="createUserRole" class="form-label">Role</label>
                            <select class="form-select" id="createUserRole" name="role_id">
                                <!-- Roles dinámicas -->
                                {{-- Roles del servidor --}}
                                <option value="" selected disabled>Select a role</option>
                                @isset($roles)
                                    @foreach ($roles as $rol)
                                        <option value="{{ $rol->id }}" {{ old('role_id') == $rol->id ? 'selected' : '' }}>{{ $rol->name }}</option>
                                    @endforeach
                                @endisset
                                <option value="new">+ New Role</option>
                            </select>
                            @error('role_id')
                                <p class="error" style="color: red;">{{ $message }}</p>
                            @enderror
                        </div>
    
                        <div class="mb-3">
                            <label for="createUserStatus" class="form-label">Status</label>
                            <select class="form-select" id="createUserStatus" name="status">
                                <option value="" selected disabled>Select a status</option>
                                @foreach($enumValues as $estado)
                                    <option value="{{ $estado }}" {{ old('status') == $estado ? 'selected' : '' }}>{{ $estado }}</option>
                                @endforeach
                            </select>
                            @error('status')
                                <p class="error" style="color: red;">{{ $message }}</p>
                            @enderror
                        </div>
    
                        <div class="mb-3">
                            <label for="createUserSubscriptions" class="form-label">Subscriptions</label>
                            <select multiple class="form-select" id="createUserSubscriptions" name="subscriptions[]">
                                <option value="" selected disabled>Select a subscription</option>
                                @isset($subscriptionProducts)
                                    @foreach ($subscriptionProducts as $subscription)
                                        <option value="{{ $subscription->id }}" {{ is_array(old('subscriptions')) && in_array($subscription->id, old('subscriptions')) ? 'selected' : '' }}>{{ $subscription->name }}</option>
                                    @endforeach
                                @endisset
                            </select>
                            @error('subscriptions')
                                <p class="error" style="color: red;">{{ $message }}</p>
                            @enderror
                        </div>
    
                        <button type="submit" class="btn btn-warning">Create</button>
                    </form>
                </div>
            </div>
        </div>
    </div>
    
    
</div>

<script>
    var formulario = document.getElementById("filtro-form");
    var contenedorUsuarios = document.getElementById("usuarios-container");
    var botonResetear = document.getElementById("reset-filters");
    var completedCoursesRange = document.getElementById("completed-courses");
    var ownedCoursesRange = document.getElementById("owned-courses");
    var completedCoursesValue = document.getElementById("completed-courses-value");
    var ownedCoursesValue = document.getElementById("owned-courses-value");

    
    // Mostrar valor del slider de los completados
    completedCoursesRange.oninput = function () {
        completedCoursesValue.textContent = completedCoursesRange.value;
    };

    // Mostrar valor del slider de los comprados
    ownedCoursesRange.oninput = function () {
        ownedCoursesValue.textContent = ownedCoursesRange.value;
    };
    
    var csrf = document.querySelector('meta[name="csrf-token"]');
    var csrfToken = csrf.getAttribute('content');

    function cargarUsuarios() {

        var formData = new FormData(formulario);
        formData.append('completedCourses', completedCoursesRange.value);
        formData.append('ownedCourses', ownedCoursesRange.value);
        var planesSeleccionados = Array.from(document.querySelectorAll('input[name="subscriptionPlans[]"]:checked')).map(sp => sp.value);
        planesSeleccionados.forEach(planId => formData.append('subscriptionPlans[]', planId));

        var formString = new URLSearchParams(formData).toString();

        fetch("{{ route('crudUsuarios') }}" + "?" + formString, {
            headers: { "accept": "application/json" }
        })
        .then(response => response.json())
        .then(data => {
            contenedorUsuarios.innerHTML = "";

            if (data.usuarios.length === 0) {
                contenedorUsuarios.innerHTML = "<p>No hay usuarios disponibles.</p>";
                return;
            }

            var wrapper = document.createElement("div");
            wrapper.classList.add("table-responsive");

            var tabla = document.createElement("table");
            tabla.classList.add("table", "table-striped", "table-bordered", "mb-0");

            // Encabezado
            tabla.innerHTML = `
                <thead class="thead-dark">
                    <tr>
                        <th>Name</th>
                        <th>Surname</th>
                        <th>Username</th>
                        <th>Email</th>
                        <th>Role</th>
                        <th>Status</th>
                        <th>Completed Courses</th>
                        <th>Owned Courses</th>
                        <th>Suscription</th>
                        <th>Edit</th>
                        <th>Delete</th>
                    </tr>
                </thead>
                <tbody id="userTableBody"></tbody>
                <br>
            `;

            var tbody = tabla.querySelector("tbody");

            // Rellenar filas
            data.usuarios.forEach(usuario => {

                var tr = document.createElement("tr");

                tr.innerHTML = 
                    "<td>" + usuario.name + "</td>" +
                    "<td>" + usuario.surname + "</td>" +
                    "<td>" + usuario.username + "</td>" +
                    "<td>" + usuario.email + "</td>" +
                    "<td>" + (usuario.role ? usuario.role.name : "No Role") + "</td>" +
                    "<td>" + usuario.status + "</td>" +
                    "<td>" + (usuario.completed_courses > 0 ? usuario.completed_courses : "None") + "</td>" +
                    "<td>" + (usuario.owned_courses_count > 0 ? usuario.owned_courses_count : "None") + "</td>" +
                    "<td>" + (usuario.subscriptions && usuario.subscriptions.length > 0 ? 
                                usuario.subscriptions.map(function(s) { 
                                    return s.subscription_product ? s.subscription_product.name : ""; 
                                }).join(', ') : "None") + "</td>" +
                    "<td><button class='user-edit-btn btn btn-warning btn-sm' " + "data-bs-toggle='modal' data-bs-target='#editUserModal' " + "data-id='" + usuario.id + "' " + "data-name='" + usuario.name + "' " + "data-surname='" + usuario.surname + "' " + "data-username='" + usuario.username + "' " + "data-email='" + usuario.email + "' " + "data-role-id='" + usuario.role.id + "' " + "data-status='" + usuario.status + "' " + "data-subscriptions='" + JSON.stringify(usuario.subscriptions) + "'>" + "Edit</button></td>" +
                    "<td><button class='btn btn-danger btn-sm eliminar-usuario' data-user-id='" + usuario.id + "'>Delete</button></td>";

                tbody.appendChild(tr);
            });

            wrapper.appendChild(tabla);
            contenedorUsuarios.appendChild(wrapper);

            // EDITAR
            // Delegación de eventos por si los botones se agregan dinámicamente
            tbody.addEventListener("click", function (e) {
                if (e.target && e.target.classList.contains("user-edit-btn")) {
                    const button = e.target;

                    document.getElementById("editUserId").value = button.dataset.id;
                    document.getElementById("editUserName").value = button.dataset.name;
                    document.getElementById("editUserSurname").value = button.dataset.surname;
                    document.getElementById("editUserUsername").value = button.dataset.username;
                    document.getElementById("editUserEmail").value = button.dataset.email;
                    document.getElementById("editUserStatus").value = button.dataset.status;

                    // Roles
                    fetch("/rolesJSON").then(res => res.json()).then(roles => {
                        const select = document.getElementById("editUserRole");
                        select.innerHTML = "";
                        roles.roles.forEach(role => {
                            const option = document.createElement("option");
                            option.value = role.id;
                            option.textContent = role.name;
                            if (role.id == button.dataset.roleId) option.selected = true;
                            select.appendChild(option);
                        });

                        // Agregar la opción "Crear nuevo rol"
                        const newOption = document.createElement("option");
                        newOption.value = "new";
                        newOption.textContent = "+ New role";
                        select.appendChild(newOption);

                    });

                    // Suscripciones
                    fetch("/subscriptionsJSON").then(res => res.json()).then(products => {
                        const currentSubs = JSON.parse(button.dataset.subscriptions).map(s => s.subscription_product_id);
                        const select = document.getElementById("editUserSubscriptions");
                        select.innerHTML = "";
                        products.products.forEach(product => {
                            const option = document.createElement("option");
                            option.value = product.id;
                            option.textContent = product.name;
                            if (currentSubs.includes(product.id)) option.selected = true;
                            select.appendChild(option);
                        });
                    });
                }
            });

            // Envío del formulario
            document.getElementById("editUserForm").addEventListener("submit", function (e) {

                e.preventDefault();
                const form = e.target;
                const userId = document.getElementById("editUserId").value;
                const formData = new FormData(form);

                formData.append('_method', 'PUT');

                fetch(`/users/${userId}`, {
                    method: "POST",
                    body: formData,
                    headers: {
                        'X-CSRF-TOKEN': document.querySelector('input[name="_token"]').value,
                    }
                }).then(res => {
                    if (res.ok) {
                        location.reload();
                    } else {
                        alert("Error al actualizar usuario.");
                    }
                });
            });


            // AÑADIR ROL Y ASIGNARLO AL USUARIO
            document.querySelectorAll('#editUserRole, #createUserRole').forEach(select => {
                select.addEventListener('change', function () {
                    if (this.value === 'new') {

                        window.activeRoleSelect = this;

                        const roleModalEl = document.getElementById("newRoleModal");
                        const roleModal = new bootstrap.Modal(roleModalEl);

                        // Subir z-index antes de mostrar
                        roleModalEl.addEventListener('show.bs.modal', function () {
                            roleModalEl.style.zIndex = '1060';
                        });

                        // Limpiar z-index al cerrar
                        roleModalEl.addEventListener('hidden.bs.modal', function () {
                            roleModalEl.style.zIndex = '';
                        });

                        roleModal.show();
                    }
                });
            });

            document.getElementById("newRoleForm").addEventListener("submit", function (e) {
                e.preventDefault();

                const form = e.target;
                const formData = new FormData(form);

                fetch("/createRole", {
                    method: "POST",
                    body: formData,
                    headers: {
                        'X-CSRF-TOKEN': document.querySelector('input[name="_token"]').value
                    }
                }).then(res => res.json())
                .then(data => {
                    if (data.id) {
                        // Usa el select activo (crear o editar)
                        const select = window.activeRoleSelect;
                        const newOption = document.createElement("option");
                        newOption.value = data.id;
                        newOption.textContent = data.name;
                        select.appendChild(newOption);
                        select.value = data.id;

                        bootstrap.Modal.getInstance(document.getElementById("newRoleModal")).hide();
                        form.reset();
                    } else {
                        alert("Error creating new role");
                    }
                });
            });


            // ELIMINAR
            tbody.addEventListener("click", function (e) {
                if (e.target && e.target.classList.contains("eliminar-usuario")) {
                    const userId = e.target.getAttribute('data-user-id');

                    Swal.fire({
                        title: '¿Are you sure?',
                        text: 'You will delete this user and all his relations',
                        icon: 'warning',
                        showCancelButton: true,
                        confirmButtonColor: '#d33',
                        cancelButtonColor: '#3085d6',
                        confirmButtonText: 'Delete',
                        cancelButtonText: 'Cancel'
                    }).then((result) => {
                        if (result.isConfirmed) {
                            fetch(`/deleteUser`, {
                                method: 'POST',
                                headers: {
                                    'Content-Type': 'application/json',
                                    'X-CSRF-TOKEN': csrfToken
                                },
                                body: JSON.stringify({ id: userId })
                            })
                            .then(res => res.json())
                            .then(data => {
                                Swal.fire('Deleted', data.message, 'success');
                                cargarUsuarios();
                            })
                            .catch(err => {
                                console.error('Error deleting this user:', err);
                                Swal.fire('Error', "Couldn't delete this user", 'error');
                            });
                        }
                    });
                }
            })
        })
        .catch(error => console.error("Error cargando usuarios:", error));
    }

    // Llamar a la función cuando cambian los filtros
    formulario.onchange = cargarUsuarios;

    // Búsqueda dinámica mientras se escribe
    document.getElementById("buscar").oninput = cargarUsuarios;

    // Resetear filtros
    botonResetear.onclick = () => {
        formulario.reset();
        completedCoursesRange.value = 0;
        completedCoursesValue.textContent = 0;
        ownedCoursesRange.value = 0;
        ownedCoursesValue.textContent = 0;
        cargarUsuarios();
    };

    // Cargar usuarios al inicio
    cargarUsuarios();

    document.addEventListener('DOMContentLoaded', function () {
        const createBtn = document.querySelector('.user-create-btn');
        const createUserModal = new bootstrap.Modal(document.getElementById('createUserModal'));

        if (createBtn) {
            createBtn.onclick = function () {
                const roleSelect = document.getElementById('createUserRole');
                const subSelect = document.getElementById('createUserSubscriptions');

                if (roleSelect.options.length === 0) {
                    fetch('/rolesJSON')
                        .then(res => res.json())
                        .then(data => {
                            data.roles.forEach(role => {
                                const option = document.createElement('option');
                                option.value = role.id;
                                option.textContent = role.name;
                                roleSelect.appendChild(option);
                            });

                            // Agregar la opción "Crear nuevo rol"
                            const newOption = document.createElement("option");
                            newOption.value = "new";
                            newOption.textContent = "+ New role";
                            roleSelect.appendChild(newOption);
                        });
                }

                if (subSelect.options.length === 0) {
                    fetch('/subscriptionsJSON')
                        .then(res => res.json())
                        .then(data => {
                            data.products.forEach(sub => {
                                const option = document.createElement('option');
                                option.value = sub.id;
                                option.textContent = sub.name;
                                subSelect.appendChild(option);
                            });
                        });
                }

                createUserModal.show();
            };
        }

        if (window.showCreateUserModal) {
            createUserModal.show();
        }
    });

    // VALIDACIONES JS CREAR
    nameField = document.getElementById('createUserName');
    surnameField = document.getElementById('createUserSurname');
    usernameField = document.getElementById('createUserUsername');
    emailField = document.getElementById('createUserEmail');
    passwordField = document.getElementById('createUserPassword');
    repeatPasswordField = document.getElementById('createUserPasswordConfirmation');
    roleField = document.getElementById('createUserRole');
    statusField = document.getElementById('createUserStatus');
    subscriptionsField = document.getElementById('createUserSubscriptions');

    function validateField(field) {
        errorMessage = document.createElement('p');
        errorMessage.style.color = 'red';

        if (field.nextElementSibling && field.nextElementSibling.tagName === 'P') {
            field.nextElementSibling.remove();
            field.style.border = '2px solid #ccc'; 
        }

        if (field.value.trim() === '') {
            errorMessage.textContent = `Your ${field.name} is required`;
            field.style.border = '3px solid red';
            field.parentNode.appendChild(errorMessage); 
            return false;
        }

        field.style.border = '3px solid green';
        return true;
    }

    function validateName() {

        if (!validateField(nameField)) {
            return false;
        }

        var errorMessage = document.createElement('p');
        errorMessage.style.color = 'red';

        var pattern = /^[A-Z][a-zA-Z]*$/;
        if (!pattern.test(nameField.value.trim())) {
            errorMessage.textContent = "Name must start with a capital letter and contain only letters";
            nameField.style.border = '3px solid red';
            nameField.parentNode.appendChild(errorMessage);
            return false;
        }

        nameField.style.border = '3px solid green';
        return true;
    }


    function validateSurname() {

        if (!validateField(surnameField)) {
            return false;
        }

        var errorMessage = document.createElement('p');
        errorMessage.style.color = 'red';

        // var pattern = /^([A-Z][a-zA-Z]*\s){1}[A-Z][a-zA-Z]*$/;
        // if (!pattern.test(surnameField.value.trim())) {
        //     errorMessage.textContent = "Surname must contain two words, both starting with capital letters";
        //     surnameField.style.border = '3px solid red';
        //     surnameField.parentNode.appendChild(errorMessage);
        //     return false;
        // }

        surnameField.style.border = '3px solid green';
        return true;
    }


    function validateUsername() {

        if (!validateField(usernameField)) {
            return false;
        }

        var errorMessage = document.createElement('p');
        errorMessage.style.color = 'red';

        var pattern = /^[a-z]+$/;
        if (!pattern.test(usernameField.value.trim())) {
            errorMessage.textContent = "Username must contain only lowercase letters";
            usernameField.style.border = '3px solid red';
            usernameField.parentNode.appendChild(errorMessage);
            return false;
        }

        usernameField.style.border = '3px solid green';
        return true;
    }


    function validateEmail() {

        if (!validateField(emailField)) {
            return false;
        }

        errorMessage = document.createElement('p');
        errorMessage.style.color = 'red';

        var emailPattern = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
        if (!emailPattern.test(emailField.value.trim())) {
            errorMessage.textContent = "This email format is not valid";
            emailField.style.border = '3px solid red';
            emailField.parentNode.appendChild(errorMessage);
            return false;
        }

        emailField.style.border = '3px solid green';
        return true;
    }

    function validatePassword() {
        
        if (!validateField(passwordField)) {
            return false;
        }

        errorMessage = document.createElement('p');
        errorMessage.style.color = 'red';

        if (passwordField.value.length < 8) {
            errorMessage.textContent = "Password must have at least 8 characters";
            passwordField.style.border = '3px solid red';
            passwordField.parentNode.appendChild(errorMessage);
            return false;
        }

        passwordField.style.border = '3px solid green';
        return true;
    }

    function validatePasswordMatch() {

        if (!validateField(repeatPasswordField)) {
            return false;
        }

        errorMessage = document.createElement('p');
        errorMessage.style.color = 'red';

        if (passwordField.value !== repeatPasswordField.value) {
            errorMessage.textContent = "Passwords do not match";
            repeatPasswordField.style.border = '3px solid red';
            repeatPasswordField.parentNode.appendChild(errorMessage);
            return false;
        }

        repeatPasswordField.style.border = '3px solid green';
        return true;
    }

    function validateRole() {
        if (!validateField(roleField)) {
            return false;
        }
    }

    function validateStatus() {
        if (!validateField(statusField)) {
            return false;
        }
    }

    function validateSubscription() {
        if (!validateField(subscriptionsField)) {
            return false;
        }
    }

    emailField.onblur = validateEmail;
    passwordField.onblur = validatePassword;
    repeatPasswordField.onblur = validatePasswordMatch;
    nameField.onblur = validateName;
    surnameField.onblur = validateSurname;
    usernameField.onblur = validateUsername;
    roleField.onblur = validateRole;
    statusField.onblur = validateStatus;
    subscriptionsField.onblur = validateSubscription;



    // VALIDACIONES JS EDITAR
    nameField2 = document.getElementById('editUserName');
    surnameField2 = document.getElementById('editUserSurname');
    usernameField2 = document.getElementById('editUserUsername');
    emailField2 = document.getElementById('editUserEmail');
    passwordField2 = document.getElementById('editUserPassword');
    roleField2 = document.getElementById('editUserRole');
    statusField2 = document.getElementById('editUserStatus');
    subscriptionsField2 = document.getElementById('editUserSubscriptions');

    function validateField2(field) {
        errorMessage = document.createElement('p');
        errorMessage.style.color = 'red';

        if (field.nextElementSibling && field.nextElementSibling.tagName === 'P') {
            field.nextElementSibling.remove();
            field.style.border = '2px solid #ccc'; 
        }

        if (field.value.trim() === '') {
            errorMessage.textContent = `Your ${field.name} is required`;
            field.style.border = '3px solid red';
            field.parentNode.appendChild(errorMessage); 
            return false;
        }

        field.style.border = '3px solid green';
        return true;
    }

    function validateName2() {

        if (!validateField2(nameField2)) {
            return false;
        }

        var errorMessage = document.createElement('p');
        errorMessage.style.color = 'red';

        var pattern = /^[A-Z][a-zA-Z]*$/;
        if (!pattern.test(nameField2.value.trim())) {
            errorMessage.textContent = "Name must start with a capital letter and contain only letters";
            nameField2.style.border = '3px solid red';
            nameField2.parentNode.appendChild(errorMessage);
            return false;
        }

        nameField2.style.border = '3px solid green';
        return true;
    }


    function validateSurname2() {

        if (!validateField2(surnameField2)) {
            return false;
        }

        var errorMessage = document.createElement('p');
        errorMessage.style.color = 'red';

        // var pattern = /^([A-Z][a-zA-Z]*\s){1}[A-Z][a-zA-Z]*$/;
        // if (!pattern.test(surnameField2.value.trim())) {
        //     errorMessage.textContent = "Surname must contain two words, both starting with capital letters";
        //     surnameField2.style.border = '3px solid red';
        //     surnameField2.parentNode.appendChild(errorMessage);
        //     return false;
        // }

        surnameField2.style.border = '3px solid green';
        return true;
    }


    function validateUsername2() {

        if (!validateField2(usernameField2)) {
            return false;
        }

        var errorMessage = document.createElement('p');
        errorMessage.style.color = 'red';

        var pattern = /^[a-z]+$/;
        if (!pattern.test(usernameField2.value.trim())) {
            errorMessage.textContent = "Username must contain only lowercase letters";
            usernameField2.style.border = '3px solid red';
            usernameField2.parentNode.appendChild(errorMessage);
            return false;
        }

        usernameField2.style.border = '3px solid green';
        return true;
    }


    function validateEmail2() {

        if (!validateField2(emailField2)) {
            return false;
        }

        errorMessage = document.createElement('p');
        errorMessage.style.color = 'red';

        var emailPattern = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
        if (!emailPattern.test(emailField2.value.trim())) {
            errorMessage.textContent = "This email format is not valid";
            emailField2.style.border = '3px solid red';
            emailField2.parentNode.appendChild(errorMessage);
            return false;
        }

        emailField2.style.border = '3px solid green';
        return true;
    }

    function validatePassword2() {

        errorMessage = document.createElement('p');
        errorMessage.style.color = 'red';

        if (passwordField2.value.length < 8) {
            errorMessage.textContent = "Password must have at least 8 characters";
            passwordField2.style.border = '3px solid red';
            passwordField2.parentNode.appendChild(errorMessage);
            return false;
        }

        passwordField2.style.border = '3px solid green';
        return true;
    }

    function validateRole2() {
        if (!validateField2(roleField2)) {
            return false;
        }
    }

    function validateStatus2() {
        if (!validateField2(statusField2)) {
            return false;
        }
    }

    function validateSubscription2() {
        if (!validateField2(subscriptionsField2)) {
            return false;
        }
    }

    emailField2.onblur = validateEmail2;
    passwordField2.onblur = validatePassword2;
    nameField2.onblur = validateName2;
    surnameField2.onblur = validateSurname2;
    usernameField2.onblur = validateUsername2;
    roleField2.onblur = validateRole2;
    statusField2.onblur = validateStatus2;
    subscriptionsField2.onblur = validateSubscription2;

    // Envío del formulario
    document.getElementById("createUserForm").onsubmit = function (e) {
        e.preventDefault();
        const form = e.target;
        const formData = new FormData(form);

        fetch(`/createUser`, {
            method: "POST",
            body: formData,
            headers: {
                'X-CSRF-TOKEN': document.querySelector('input[name="_token"]').value,
            }
        }).then(async res => {
            if (res.ok) {
                location.reload();
            } else {
                Swal.fire({
                    icon: 'error',
                    title: 'Error creating user',
                    html: 'Fill in all fields with the correct data',
                }).then(() => location.reload());
            }
        });
    };

</script>

<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

@endsection