<?= $this->extend('layouts/master') ?>

<?= $this->section('title') ?>
Usuarios
<?= $this->endSection() ?>

<?= $this->section('css') ?>
<link rel="stylesheet" href="https://cdn.datatables.net/1.13.4/css/dataTables.bootstrap5.min.css">
<?= $this->endSection() ?>

<?= $this->section('pageContent') ?>

<div class="card">
    <div class="card-body">

        <h5 class="card-title fw-semibold mb-4">Usuarios</h5>
        <?php 
            if(permiso('Usuario','Crear')){
        ?>
            <a href="/usuario/create" class="btn btn-primary mb-3">Crear Usuario</a>
        <?php 
            }
        ?>
        <table id="tablaUsuarios" class="table table-striped" style="width:100%">
            <thead>
                <tr>
                    <th>ID</th>
                    <th>Nombre</th>
                    <th>Email</th>
                    <th>RUT</th>
                    <th>Activo</th>
                    <th style="width: 150px;">Acciones</th>
                </tr>
            </thead>
        </table>

    </div>
</div>

<?= $this->endSection() ?>

<?= $this->section('scripts') ?>

<script src="https://cdn.datatables.net/1.13.4/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.13.4/js/dataTables.bootstrap5.min.js"></script>

<script>
$(document).ready(function() {

    $('#tablaUsuarios').DataTable({
        processing: true,
        serverSide: true,
        language: {
            url: "//cdn.datatables.net/plug-ins/1.13.6/i18n/es-ES.json"
        },
        ajax: {
            url: '/usuario/datatable',
            type: 'POST'
        },
        columns: [
            { data: 'id' },
            { data: 'nombre' },
            { data: 'email' },
            { data: 'rut' },
            { 
                data: 'activo',
                render: function(value) {
                    return value == 1 
                        ? '<span class="badge bg-success">Sí</span>' 
                        : '<span class="badge bg-danger">No</span>';
                }
            },
            { 
                data: 'id', 
                orderable: false,
                render: function(id) {
                    return `
                        <?php if(permiso('Usuario','Editar')){?><a href="/usuario/edit/${id}" class="btn btn-sm btn-warning">Editar</a><?php } ?>
                        <?php if(permiso('Usuario','Eliminar')){?><a href="/usuario/delete/${id}" class="btn btn-sm btn-danger" onclick="return confirm('¿Eliminar?')">Eliminar</a><?php } ?>
                    `;
                }
            }
        ],
        order: [[0, 'desc']]
    });

});
</script>

<?= $this->endSection() ?>
