<?php
$db = new clsbdd();

// Procesar eliminación
if(isset($_GET['eliminar_id'])){
    $id_el = intval($_GET['eliminar_id']);
    // No permitir que el usuario se elimine a sí mismo
    if($id_el != $_SESSION['usu_id']){
        $db->ejecutar("DELETE FROM car_usuarios WHERE usu_id = $id_el");
    }
    echo "<script>window.location='index.php?page=usuarios/listar';</script>";
}

$sql = "SELECT * FROM car_usuarios ORDER BY usu_nombre ASC";
$res = $db->ejecutar($sql);
?>

<div class="container-fluid">
    <div class="row mb-3 align-items-center">
        <div class="col-md-8">
            <h4 class="fw-bold text-primary"><i class="fas fa-user-shield me-2"></i>Usuarios del Sistema</h4>
        </div>
        <div class="col-md-4 text-end">
            <button class="btn btn-primary shadow-sm" data-bs-toggle="modal" data-bs-target="#modalUsuario" onclick="nuevoUsuario()">
                <i class="fas fa-user-plus me-1"></i> Registrar Usuario
            </button>
        </div>
    </div>

    <div class="row">
        <?php while($u = $res->fetch_assoc()): 
            // Lógica de colores según el rol almacenado
            $rol = $u['usu_rol'];
            $rol_bg = 'bg-secondary';
            if($rol == 'Administrador General' || $rol == 'AdminG' || $rol == 'Admin') $rol_bg = 'bg-danger';
            if($rol == 'Administrador Local' || $rol == 'AdminL') $rol_bg = 'bg-primary';
            if($rol == 'Operario' || $rol == 'Oper') $rol_bg = 'bg-success';
        ?>
        <div class="col-md-4 mb-4">
            <div class="card border-0 shadow-sm h-100 overflow-hidden">
                <div class="card-body">
                    <div class="d-flex align-items-center mb-3">
                        <img src="https://ui-avatars.com/api/?name=<?= urlencode($u['usu_nombre']) ?>&background=random" class="rounded-circle me-3" width="55" height="55">
                        <div class="overflow-hidden">
                            <h6 class="mb-0 fw-bold text-truncate"><?= $u['usu_nombre'] ?></h6>
                            <span class="badge <?= $rol_bg ?> rounded-pill" style="font-size: 0.65rem;">
                                <?= strtoupper($rol) ?>
                            </span>
                        </div>
                    </div>
                    <div class="small text-muted mb-1"><i class="fas fa-id-card-alt me-2"></i>ID: <b><?= $u['usu_usuario'] ?></b></div>
                    <div class="small text-muted"><i class="fas fa-envelope me-2"></i><?= $u['usu_correo'] ?: 'Sin correo' ?></div>
                </div>
                <div class="card-footer bg-light border-0 d-flex justify-content-around py-2">
                    <button class="btn btn-sm btn-link text-primary text-decoration-none fw-bold" 
                            onclick='abrirEditar(<?= json_encode($u) ?>)'>
                        <i class="fas fa-edit me-1"></i> Editar
                    </button>
                    
                    <?php if($u['usu_id'] != 1 && $u['usu_id'] != $_SESSION['usu_id']): ?>
                    <a href="index.php?page=usuarios/listar&eliminar_id=<?= $u['usu_id'] ?>" 
                       class="btn btn-sm btn-link text-danger text-decoration-none fw-bold" 
                       onclick="return confirm('¿Está seguro de eliminar este acceso?')">
                        <i class="fas fa-trash-alt me-1"></i> Borrar
                    </a>
                    <?php endif; ?>
                </div>
            </div>
        </div>
        <?php endwhile; ?>
    </div>
</div>

<div class="modal fade" id="modalUsuario" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
        <form action="controlador/car_UsuariosControlador.php?accion=guardar" method="POST" class="modal-content border-0 shadow">
            <div class="modal-header bg-dark text-white">
                <h5 class="modal-title" id="tituloModal">Configurar Usuario</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <input type="hidden" name="usu_id" id="form_id">
                <div class="row g-3">
                    <div class="col-12">
                        <label class="form-label small fw-bold">Nombre Completo</label>
                        <input type="text" name="usu_nombre" id="form_nombre" class="form-control" required>
                    </div>
                    <div class="col-md-6">
                        <label class="form-label small fw-bold">Usuario (Login)</label>
                        <input type="text" name="usu_usuario" id="form_usuario" class="form-control" required>
                    </div>
                    <div class="col-md-6">
                        <label class="form-label small fw-bold">Rol / Permisos</label>
                        <select name="usu_rol" id="form_rol" class="form-select" required>
                            <option value="Operario">Operario</option>
                            <option value="Administrador Local">Administrador Local</option>
                            <option value="Administrador General">Administrador General</option>
                        </select>
                    </div>
                    <div class="col-12">
                        <label class="form-label small fw-bold">Correo Electrónico</label>
                        <input type="email" name="usu_correo" id="form_correo" class="form-control">
                    </div>
                    <div class="col-12">
                        <label class="form-label small fw-bold text-primary">Contraseña</label>
                        <input type="password" name="usu_clave" id="form_clave" class="form-control" placeholder="Escriba la clave">
                        <small id="pass_help" class="text-muted" style="font-size: 0.7rem;">Si está editando, deje en blanco para mantener la actual.</small>
                    </div>
                </div>
            </div>
            <div class="modal-footer bg-light border-0">
                <button type="button" class="btn btn-secondary btn-sm" data-bs-dismiss="modal">Cancelar</button>
                <button type="submit" class="btn btn-primary btn-sm px-4">Guardar Usuario</button>
            </div>
        </form>
    </div>
</div>

<script>
function nuevoUsuario() {
    document.getElementById('tituloModal').innerText = "Nuevo Usuario";
    document.getElementById('form_id').value = "";
    document.getElementById('form_nombre').value = "";
    document.getElementById('form_usuario').value = "";
    document.getElementById('form_correo').value = "";
    document.getElementById('form_rol').value = "Operario";
    document.getElementById('form_clave').required = true;
    document.getElementById('pass_help').style.display = "none";
}

function abrirEditar(u) {
    document.getElementById('tituloModal').innerText = "Editar Usuario";
    document.getElementById('form_id').value = u.usu_id;
    document.getElementById('form_nombre').value = u.usu_nombre;
    document.getElementById('form_usuario').value = u.usu_usuario;
    document.getElementById('form_correo').value = u.usu_correo;
    document.getElementById('form_rol').value = u.usu_rol;
    document.getElementById('form_clave').value = ""; // No mostrar clave actual por seguridad
    document.getElementById('form_clave').required = false; 
    document.getElementById('pass_help').style.display = "block";
    
    var myModal = new bootstrap.Modal(document.getElementById('modalUsuario'));
    myModal.show();
}
</script>