@extends('layouts.master')
@section('title') Inicio @endsection
@section('content')
<!-- this is breadcrumbs -->
@component('components.breadcrumb')
@slot('li_1') Inicio @endslot
@slot('li_2') Panel Configuración @endslot
@slot('title') Roles @endslot
@endcomponent

<!-- start page content -->
<div class="row">
    <div class="col-12">
        <div class="card">
            <div class="card-body mb-n3">
                <button type="button" class="btn btn-de-primary btn-sm px-4 mt-0 mb-3" 
                    data-bs-toggle="modal" 
                    data-bs-target="#modalCrearUsuario">
                    <i class="fas fa-plus"></i> Nuevo Usuario
                </button>
                <div class="table-responsive">
                    <table id="tablaRoles" class="table table-striped mb-0 table-hover">
                        <thead class="thead-light">
                            <tr>
                                <th>#</th>
                                <th>Nombre</th>
                                <th>Email</th>
                                <th>Roles</th>
                                <th>Fecha Registro</th>
                                <th>Acciones</th>
                            </tr>
                        </thead>
                        <tbody>
                            @foreach ($users as $user)
                                <tr>
                                    <td>{{ $loop->iteration }}</td>
                                    <td>{{ $user->name }}</td>
                                    <td>{{ $user->email }}</td>

                                    <!-- Mostrar roles -->
                                    <td>
                                        @forelse ($user->roles as $role)
                                            <span class="badge bg-info">{{ $role->name }}</span>
                                        @empty
                                            <span class="text-muted">Sin rol</span>
                                        @endforelse
                                    </td>

                                    <td>{{ $user->created_at?->format('d/m/Y H:i') }}</td>
                                    <td>
                                        <!-- Botón Editar -->
                                        <a href="#"
                                            class="text-warning me-2"
                                            data-bs-toggle="modal"
                                            data-bs-target="#modalEditarUsuario"
                                            data-id="{{ $user->id }}"
                                            data-nombre="{{ $user->name }}"
                                            data-email="{{ $user->email }}"
                                            data-roles='@json($user->roles->pluck("id"))'>
                                            <i class="las la-pen font-18"></i>
                                        </a>

                                        <!-- Botón Eliminar -->
                                        <button type="button"
                                                class="btn btn-link text-danger p-0 m-0 btn-eliminar-usuario"
                                                data-id="{{ $user->id }}">
                                            <i class="las la-trash-alt font-18"></i>
                                        </button>
                                    </td>
                                </tr>
                            @endforeach
                        </tbody>
                    </table>



                </div>
            </div>
            <!--end card-body-->
        </div>
        <!--end card-->
    </div>
    <!--end col-->
</div>

<!-- Modal de agregar -->
<div class="modal fade" id="modalCrearUsuario" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
        <div class="modal-header bg-primary text-white">
            <h5 class="modal-title">Nuevo Usuario</h5>
            <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
        </div>
        <form id="formCrearUsuario">
            @csrf
            <div class="modal-body">
                <div class="mb-3">
                    <label for="name" class="form-label">Nombre</label>
                    <input type="text" class="form-control" name="name" required>
                </div>
                <div class="mb-3">
                    <label for="email" class="form-label">Correo</label>
                    <input type="email" class="form-control" name="email" required>
                </div>
                <div class="mb-3">
                    <label for="password" class="form-label">Contraseña</label>
                    <input type="password" class="form-control" name="password" required>
                </div>

                <!-- Roles en checkboxes -->
                <div class="mb-3">
                    <label class="form-label">Roles</label>
                    <div class="row">
                        @foreach($roles as $rol)
                            <div class="col-6">
                                <div class="form-check">
                                    <input class="form-check-input"
                                           type="checkbox"
                                           name="roles[]"
                                           value="{{ $rol->id }}"
                                           id="rol{{ $rol->id }}">
                                    <label class="form-check-label" for="rol{{ $rol->id }}">
                                        {{ $rol->name }}
                                    </label>
                                </div>
                            </div>
                        @endforeach
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-light" data-bs-dismiss="modal">Cancelar</button>
                <button type="submit" class="btn btn-primary">Guardar</button>
            </div>
        </form>
    </div>
  </div>
</div>



<!-- Modal de Edición -->

<!-- Modal: Editar -->
<div class="modal fade" id="modalEditarUsuario" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
        <div class="modal-header bg-warning text-white">
            <h5 class="modal-title">Editar Usuario</h5>
            <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
        </div>
        <form id="formEditarUsuario">
            @csrf
            @method('PUT')
            <input type="hidden" name="id" id="editar_id">

            <div class="modal-body">
                <div class="mb-3">
                    <label for="editar_name" class="form-label">Nombre</label>
                    <input type="text" class="form-control" id="editar_name" name="name" required>
                </div>
                <div class="mb-3">
                    <label for="editar_email" class="form-label">Correo</label>
                    <input type="email" class="form-control" id="editar_email" name="email" required>
                </div>
                <div class="mb-3">
                    <label for="editar_password" class="form-label">Contraseña <small>(dejar en blanco si no cambia)</small></label>
                    <input type="password" class="form-control" id="editar_password" name="password">
                </div>

                <div class="mb-3">
                    <label class="form-label">Roles</label>
                    <div class="row">
                        @foreach($roles as $role)
                            <div class="col-6">
                                <div class="form-check">
                                    <input class="form-check-input role-checkbox-editar" 
                                           type="checkbox" 
                                           name="roles[]" 
                                           value="{{ $role->id }}" 
                                           id="editar_rol_{{ $role->id }}">
                                    <label class="form-check-label" for="editar_rol_{{ $role->id }}">
                                        {{ $role->name }}
                                    </label>
                                </div>
                            </div>
                        @endforeach
                    </div>
                </div>
            </div>

            <div class="modal-footer">
                <button type="button" class="btn btn-light" data-bs-dismiss="modal">Cancelar</button>
                <button type="submit" class="btn btn-warning">Actualizar</button>
            </div>
        </form>
    </div>
  </div>
</div>






<!--end row-->


@endsection
@section('script')
<!-- jQuery y DataTables -->

<!-- jQuery y DataTables -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>

<!-- DataTables Buttons -->
<script src="https://cdn.datatables.net/buttons/2.3.6/js/dataTables.buttons.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.1/jszip.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.2.7/pdfmake.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.2.7/vfs_fonts.js"></script>
<script src="https://cdn.datatables.net/buttons/2.3.6/js/buttons.html5.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.3.6/js/buttons.print.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.3.6/js/buttons.colVis.min.js"></script>

<!-- DataTables CSS -->
<link rel="stylesheet" href="https://cdn.datatables.net/1.13.6/css/jquery.dataTables.min.css">
<link rel="stylesheet" href="https://cdn.datatables.net/buttons/2.3.6/css/buttons.dataTables.min.css">
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<!-- tablas -->
<script>
    $(document).ready(function () {
        $("#tablaRoles").DataTable({
            "responsive": true,
            "lengthChange": true,
            "autoWidth": false,
            "buttons": [
                {
                    extend: 'collection',
                    text: 'Opciones',
                    buttons: [
                        { extend: 'copy', text: 'Copiar' },
                        { extend: 'csv', text: 'CSV' },
                        { extend: 'excel', text: 'Excel', title: 'Periodos Académicos' },
                        { extend: 'pdf', text: 'PDF' },
                        { extend: 'print', text: 'Imprimir' }
                    ]
                },
                { extend: 'colvis', text: 'Visibilidad de Columna' }
            ],
            "paging": true,
            "searching": true,
            "info": true,
            "language": {
                "search": "Buscar:",
                "lengthMenu": "Mostrar _MENU_ registros por página",
                "info": "Mostrando _START_ a _END_ de _TOTAL_ entradas",
                "paginate": {
                    "first": "Primero",
                    "previous": "Anterior",
                    "next": "Siguiente",
                    "last": "Último"
                }
            }
        }).buttons().container().appendTo('#tablaRoles_wrapper .col-md-6:eq(0)');
    });
</script>
<!-- agregar -->
<script>
$(document).ready(function () {

    // Crear Usuario
    $('#formCrearUsuario').on('submit', function (e) {
        e.preventDefault();

        let form = $(this);
        let url = "{{ route('users.store') }}"; // ruta backend
        let data = form.serialize(); // serializa todo (incluye roles[])

        $.ajax({
            url: url,
            method: "POST",
            data: data,
            success: function (response) {
                Swal.fire({
                    icon: 'success',
                    title: 'Usuario creado',
                    text: response.message || 'El usuario se registró correctamente',
                    showConfirmButton: false,
                    timer: 1500
                });

                // Cerrar modal
                $('#modalCrearUsuario').modal('hide');

                // Resetear formulario
                form[0].reset();

                // Recargar la tabla (puedes usar DataTables o recargar la página)
                setTimeout(() => {
                    location.reload();
                }, 1500);
            },
            error: function (xhr) {
                let errors = xhr.responseJSON?.errors;
                let message = "Ocurrió un error";

                if (errors) {
                    message = Object.values(errors).join("\n");
                }

                Swal.fire({
                    icon: 'error',
                    title: 'Error',
                    text: message
                });
            }
        });
    });

    // Eliminar usuario
    $(document).on('click', '.btn-eliminar-usuario', function () {
        let userId = $(this).data('id');

        Swal.fire({
            title: '¿Eliminar usuario?',
            text: "Esta acción no se puede deshacer",
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#d33',
            cancelButtonColor: '#6c757d',
            confirmButtonText: 'Sí, eliminar'
        }).then((result) => {
            if (result.isConfirmed) {
                $.ajax({
                    url: `/users/${userId}`,
                    type: 'DELETE',
                    data: {
                        _token: '{{ csrf_token() }}'
                    },
                    success: function (response) {
                        Swal.fire({
                            icon: 'success',
                            title: 'Eliminado',
                            text: response.message || 'El usuario fue eliminado'
                        });

                        // Recargar tabla
                        setTimeout(() => {
                            location.reload();
                        }, 1000);
                    },
                    error: function () {
                        Swal.fire({
                            icon: 'error',
                            title: 'Error',
                            text: 'No se pudo eliminar el usuario'
                        });
                    }
                });
            }
        });
    });

});
</script>


<!-- editar-->
<script>
// Detectar clic en botón editar
$(document).on("click", "[data-bs-target='#modalEditarUsuario']", function () {
    let id = $(this).data("id");
    let nombre = $(this).data("nombre");
    let email = $(this).data("email");
    let roles = $(this).data("roles"); // aquí mandamos los IDs de roles desde blade

    // Cargar en inputs
    $("#editar_id").val(id);
    $("#editar_name").val(nombre);
    $("#editar_email").val(email);
    $("#editar_password").val("");

    // Resetear checkboxes
    $(".role-checkbox-editar").prop("checked", false);

    // Marcar roles del usuario
    if (roles) {
        roles.forEach(r => {
            $("#editar_rol_" + r).prop("checked", true);
        });
    }
});

// Envío AJAX para actualizar
$("#formEditarUsuario").submit(function(e){
    e.preventDefault();

    let id = $("#editar_id").val();
    let formData = $(this).serialize();

    $.ajax({
        url: "/users/" + id,
        type: "POST",
        data: formData,
        success: function(resp){
            Swal.fire("Éxito", "Usuario actualizado correctamente", "success")
                .then(() => location.reload());
        },
        error: function(){
            Swal.fire("Error", "No se pudo actualizar el usuario", "error");
        }
    });
});

</script>




@endsection
