<?php
/**
 * Módulo Usuarios - Listado
 */

// Configuración inicial
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

if (!defined('BASE_PATH')) {
    define('BASE_PATH', dirname(dirname(__DIR__)));
}

require_once BASE_PATH . '/database/config.php';
require_once BASE_PATH . '/database/connection.php';

// Definir función isLoggedIn si no existe
if (!function_exists('isLoggedIn')) {
    function isLoggedIn() {
        return isset($_SESSION['user_id']) && !empty($_SESSION['user_id']);
    }
}

if (!isLoggedIn()) {
    header('Location: /index.php?module=auth&action=login');
    exit;
}

$db = getDB();

// Obtener usuarios con sus roles
$users = $db->select(
    "SELECT u.*, 
            GROUP_CONCAT(r.display_name SEPARATOR ', ') as roles,
            COUNT(l.id) as total_leads
     FROM users u
     LEFT JOIN user_roles ur ON u.id = ur.user_id
     LEFT JOIN roles r ON ur.role_id = r.id
     LEFT JOIN leads l ON u.id = l.assigned_to
     GROUP BY u.id
     ORDER BY u.created_at DESC"
);

// Obtener lista de roles para el asistente y edición
$roles = $db->select("SELECT id, display_name FROM roles ORDER BY display_name");

// Recalcular usuarios incluyendo desk actual y evitar duplicados de roles
$users = $db->select(
    "SELECT u.*, 
            GROUP_CONCAT(DISTINCT r.display_name SEPARATOR ', ') as roles,
            COUNT(l.id) as total_leads,
            (
              SELECT d.name 
              FROM desks d 
              INNER JOIN desk_users du ON d.id = du.desk_id 
              WHERE du.user_id = u.id 
              ORDER BY du.assigned_at DESC 
              LIMIT 1
            ) AS desk_name
     FROM users u
     LEFT JOIN user_roles ur ON u.id = ur.user_id
     LEFT JOIN roles r ON ur.role_id = r.id
     LEFT JOIN leads l ON u.id = l.assigned_to
     GROUP BY u.id
     ORDER BY u.created_at DESC"
);

// Permisos del usuario actual para acciones de Usuarios
$uid = (int)$_SESSION['user_id'];
$permSql = "SELECT 1 FROM permissions p
             INNER JOIN role_permissions rp ON p.id = rp.permission_id
             INNER JOIN user_roles ur ON rp.role_id = ur.role_id
             WHERE ur.user_id = ? AND CONCAT(p.module, '.', p.action) = ? LIMIT 1";
$canCreateUser = $db->selectOne($permSql, [$uid, 'users.create']) ? true : false;
$canEditUser   = $db->selectOne($permSql, [$uid, 'users.edit']) ? true : false;
$canDeleteUser = $db->selectOne($permSql, [$uid, 'users.delete']) ? true : false;

// Desks activos para asignación en asistente/edición
$desks = $db->select("SELECT id, name FROM desks WHERE status = 'active' ORDER BY name");

// Métricas para widgets del módulo Usuarios
$users_active_count = (int)$db->selectOne("SELECT COUNT(*) AS c FROM users WHERE status = 'active'")['c'];
$roles_count = (int)$db->selectOne("SELECT COUNT(*) AS c FROM roles")['c'];
$desks_active_count = (int)$db->selectOne("SELECT COUNT(*) AS c FROM desks WHERE status = 'active'")['c'];
$leads_assigned_count = (int)$db->selectOne("SELECT COUNT(*) AS c FROM leads WHERE assigned_to IS NOT NULL")['c'];

// Estado de configuración de Voiso para habilitar campo de extensión en UI
$voisoCfg = $db->select("SELECT setting_key, setting_value FROM integration_settings WHERE integration_name='voiso' AND setting_key IN ('api_base_url','api_token')");
$isVoisoConfigured = false;
if (!empty($voisoCfg)) {
    $vals = [];
    foreach ($voisoCfg as $r) { $vals[$r['setting_key']] = trim((string)$r['setting_value']); }
    $isVoisoConfigured = !empty($vals['api_base_url']) && !empty($vals['api_token']);
}
?>

<?php
// Integración con layout corporativo
$page_title = 'Usuarios';
$current_module = 'users';
$current_action = 'index';
$content_file = BASE_PATH . '/modules/users/users_content.php';
include BASE_PATH . '/modules/shared/layout.php';
return; // Evita render duplicado del HTML legacy
?>

<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Usuarios - <?php echo APP_NAME; ?></title>
    <link rel="stylesheet" href="/test/simple_crm/public/style.css">
</head>
<body>
    <?php include BASE_PATH . '/modules/shared/header.php'; ?>
    
    <div class="container">
        <div class="card">
            <div class="card-header d-flex justify-between align-center">
                <h1 class="card-title">Gestión de Usuarios</h1>
                <div class="header-actions">
                    <a href="?module=users&action=create" class="btn-primary btn-size-md">Nuevo Usuario</a>
                </div>
            </div>
            
            <?php if (empty($users)): ?>
                <div class="alert alert-info">
                    No hay usuarios registrados en el sistema.
                </div>
            <?php else: ?>
                <table class="table data-table">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>Usuario</th>
                            <th>Nombre Completo</th>
                            <th>Email</th>
                            <th>Roles</th>
                            <th>Leads Asignados</th>
                            <th>Estado</th>
                            <th>Último Login</th>
                            <th>Acciones</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($users as $user): ?>
                            <tr>
                                <td><?php echo $user['id']; ?></td>
                                <td>
                                    <strong><?php echo htmlspecialchars($user['username']); ?></strong>
                                </td>
                                <td>
                                    <?php echo htmlspecialchars($user['first_name'] . ' ' . $user['last_name']); ?>
                                </td>
                                <td><?php echo htmlspecialchars($user['email']); ?></td>
                                <td>
                                    <?php if ($user['roles']): ?>
                                        <small><?php echo htmlspecialchars($user['roles']); ?></small>
                                    <?php else: ?>
                                        <small class="text-muted">Sin roles</small>
                                    <?php endif; ?>
                                </td>
                                <td class="text-center">
                                    <?php echo number_format($user['total_leads']); ?>
                                </td>
                                <td>
                                    <span class="badge badge-<?php echo $user['status']; ?>">
                                        <?php echo ucfirst($user['status']); ?>
                                    </span>
                                </td>
                                <td>
                                    <?php if ($user['last_login']): ?>
                                        <?php echo date('d/m/Y H:i', strtotime($user['last_login'])); ?>
                                    <?php else: ?>
                                        <small class="text-muted">Nunca</small>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <a href="?module=users&action=view&id=<?php echo $user['id']; ?>" 
                                       class="btn-secondary btn-size-md">Ver</a>
                                    <a href="?module=users&action=edit&id=<?php echo $user['id']; ?>" 
                                       class="btn-secondary btn-size-md">Editar</a>
                                    <?php if ($user['id'] != $_SESSION['user_id']): ?>
                                        <a href="?module=users&action=delete&id=<?php echo $user['id']; ?>" 
                                           class="btn-danger btn-size-md btn-delete"
                                           onclick="return confirmDelete('¿Eliminar este usuario?')">Eliminar</a>
                                    <?php endif; ?>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            <?php endif; ?>
        </div>
    </div>
    
    <script src="/public/script.js"></script>
    <style>
        .badge {
            padding: 0.25rem 0.5rem;
            border-radius: 3px;
            font-size: 0.8rem;
            font-weight: 500;
        }
        .badge-active { background: #28a745; color: white; }
        .badge-inactive { background: #6c757d; color: white; }
        .badge-suspended { background: #dc3545; color: white; }
        .text-muted { color: #6c757d; }
    </style>
</body>
</html>