@extends('adminlte::page')

@section('title', 'Usuarios' . ' | ' . config('app.name'))

@section('content_header')
   <div class="w-100">
    @php
            $breadcrumbs = [
                ['name' => 'Inicio', 'route' => 'dashboard', 'icon' => 'fa-home'],
                ['name' => 'Usuarios', 'route' => 'users.index'],
                ['name' => 'Lista de Usuarios'],
            ];
        @endphp

        <nav aria-label="breadcrumb">
            <ol class="breadcrumb bg-light p-2 rounded shadow-sm">
                @foreach ($breadcrumbs as $breadcrumb)
                    @if (isset($breadcrumb['route']))
                        <li class="breadcrumb-item">
                            <a href="{{ route($breadcrumb['route']) }}">
                                @if (isset($breadcrumb['icon']))
                                    <i class="fas {{ $breadcrumb['icon'] }} mr-1"></i>
                                @endif
                                {{ $breadcrumb['name'] }}
                            </a>
                        </li>
                    @else
                        <li class="breadcrumb-item active" aria-current="page">{{ $breadcrumb['name'] }}</li>
                    @endif
                @endforeach
            </ol>
        </nav>
   </div>
@stop

@section('content')

    <div class="m-0">
        <div class="card shadow-sm">
            <div class="card-header">
                <div class="row align-items-center">
                    <!-- Título -->
                    <div class="col-12 col-md-6">
                        <h5 class="mb-md-0">Gestión de Usuarios</h5>
                    </div>

                    <!-- Botón -->
                    <div class="col-12 col-md-6 text-md-right">
                        <button class="btn btn-success btn-sm" id="btnAdd">
                            <i class="fas fa-user-plus"></i> Nuevo Usuario
                        </button>
                    </div>
                </div>
            </div>

            <div class="card-body p-2">
                <table class="table table-bordered table-hover" id="users-table" style="width: 100%;">
                    <thead class="thead-light">
                        <tr>
                            <th style="width: 5%"></th> <!-- Columna para el signo + -->
                            <th style="width: 5%">ID</th>
                            <th style="width: 30%">Nombre</th>
                            <th style="width: 30%">Email</th>
                            <th style="width: 20%">Creado</th>
                            <th style="width: 10%">Acciones</th>
                        </tr>
                    </thead>
                </table>
            </div>
        </div>
    </div>


    <!-- Modal -->
    <div class="modal fade" id="userModal" tabindex="-1">
        <div class="modal-dialog">
            <form id="formUser">
                @csrf
                <div class="modal-content">
                    <div class="modal-header bg-primary text-white">
                        <h5 class="modal-title">Usuario</h5>
                        <button type="button" class="close" data-dismiss="modal">&times;</button>
                    </div>
                    <div class="modal-body">
                        <input type="hidden" name="id" id="user_id">
                        <div class="form-group">
                            <label>Nombre</label>
                            <input type="text" name="name" id="name" class="form-control">
                        </div>
                        <div class="form-group">
                            <label>Email</label>
                            <input type="email" name="email" id="email" class="form-control">
                        </div>
                        <div class="form-group">
                            <label>Contraseña</label>
                            <input type="password" name="password" id="password" class="form-control">
                            <small class="text-muted">Dejar vacío para no cambiar</small>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="submit" class="btn btn-primary">Guardar</button>
                    </div>
                </div>
            </form>
        </div>
    </div>


@stop

@section('css')
    {{-- Add here extra stylesheets --}}
    {{-- <link rel="stylesheet" href="/css/admin_custom.css"> --}}
@stop

@push('js')
    <script>
        let table;

        $(function() {
            table = $('#users-table').DataTable({
                responsive: {
                    details: {
                        type: 'column', // el signo + en la primera columna
                        target: 0 // en qué columna colocar el signo +
                    }
                },
                columnDefs: [{
                    className: 'dtr-control', // clase obligatoria para el botón de expandir
                    orderable: false,
                    targets: 0
                }],
                processing: true,
                serverSide: true,
                ajax: "{{ route('users.data') }}",
                columns: [{
                        data: null,
                        defaultContent: ''
                    },
                    {
                        data: 'id'
                    },
                    {
                        data: 'name'
                    },
                    {
                        data: 'email'
                    },
                    {
                        data: 'created_at'
                    },
                    {
                        data: 'actions',
                        orderable: false,
                        searchable: false
                    }
                ],
                 order: [
                    [1, 'desc']
                ], // <-- orden descendente por la columna "orden"
            });

            // Nuevo usuario
            $('#btnAdd').click(function() {
                $('#formUser')[0].reset();
                $('#user_id').val('');
                $('#userModal').modal('show');
            });

            // Editar
            $(document).on('click', '.editUser', function() {
                let id = $(this).data('id');
                $.get("{{ url('admin/users/edit') }}/" + id, function(data) {
                    $('#user_id').val(data.id);
                    $('#name').val(data.name);
                    $('#email').val(data.email);
                    $('#password').val('');
                    $('#userModal').modal('show');
                });
            });

            // Guardar
            $('#formUser').submit(function(e) {
                e.preventDefault();
                $.ajax({
                    url: "{{ route('users.store') }}",
                    method: "POST",
                    data: $(this).serialize(),
                    success: function(res) {
                        $('#userModal').modal('hide');
                        table.ajax.reload();
                        Toast.fire({
                            icon: 'success',
                            title: res.success
                        });
                    },
                    error: function(xhr) {
                        let msg = xhr.responseJSON.message || 'Error en el servidor';
                        Toast.fire({
                            icon: 'error',
                            title: msg
                        });
                    }
                });
            });

            // Eliminar
            $(document).on('click', '.deleteUser', function() {
                let id = $(this).data('id');
                Swal.fire({
                    title: '¿Eliminar usuario?',
                    icon: 'warning',
                    showCancelButton: true,
                    confirmButtonText: 'Sí, eliminar'
                }).then((result) => {
                    if (result.isConfirmed) {
                        $.ajax({
                            url: "{{ url('admin/users/delete') }}/" + id,
                            method: 'DELETE',
                            data: {
                                _token: '{{ csrf_token() }}'
                            },
                            success: function(res) {
                                table.ajax.reload();
                                Toast.fire({
                                    icon: 'success',
                                    title: res.success
                                });
                            }
                        });
                    }
                });
            });
        });
    </script>
@endpush
