<?php
/**
 * Módulo Leads - Listado Profesional para Forex/CFD CRM
 */

// Iniciar sesión si no está iniciada
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// Definir BASE_PATH si no está definido (ruta a simple_crm)
if (!defined('BASE_PATH')) {
    define('BASE_PATH', dirname(dirname(__DIR__)));
}

// Incluir configuración y conexión de base de datos
require_once BASE_PATH . '/database/config.php';
require_once BASE_PATH . '/database/connection.php';
require_once BASE_PATH . '/modules/shared/helpers.php';

// Helper de autenticaciÃ³n si no existe
if (!function_exists('isLoggedIn')) {
    function isLoggedIn() {
        return isset($_SESSION['user_id']) && !empty($_SESSION['user_id']);
    }
}

// Identificar módulo actual para el sidebar
$current_module = 'leads';

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

$db = getDB();
// Obtener conexiÃ³n PDO y usuario actual
$pdo = $db->getConnection();
$current_user_id = isset($_SESSION['user_id']) ? (int)$_SESSION['user_id'] : 0;
// Helper local para verificar permisos por nombre (p.name) - robusto con try/catch
if (!function_exists('userHasPermissionByName')) {
    function userHasPermissionByName($pdo, $permName, $userId) {
        if (empty($userId)) return false;
        try {
            $stmt = $pdo->prepare("SELECT 1 FROM role_permissions rp INNER JOIN permissions p ON rp.permission_id = p.id INNER JOIN user_roles ur ON rp.role_id = ur.role_id WHERE ur.user_id = ? AND p.name = ? LIMIT 1");
            $stmt->execute([$userId, $permName]);
            return (bool)$stmt->fetchColumn();
        } catch (Throwable $e) {
            // Si la tabla/permiso no existe o hay error, asumir sin permiso
            return false;
        }
    }
}
// Determinar si el usuario puede ver todos los leads
$can_view_all = userHasPermissionByName($pdo, 'leads.view_all', $current_user_id);

// Parámetros de búsqueda y filtros
$search = $_GET['search'] ?? '';
$status_filter = $_GET['status'] ?? '';
$priority_filter = $_GET['priority'] ?? '';
$desk_filter = $_GET['desk'] ?? '';
$assigned_filter = $_GET['assigned'] ?? '';
// Filtro por país (multi-selección)
$country_filters_raw = $_GET['country'] ?? [];
if (is_string($country_filters_raw)) {
    $country_filters = [$country_filters_raw];
} elseif (is_array($country_filters_raw)) {
    $country_filters = $country_filters_raw;
} else {
    $country_filters = [];
}
// Normalizar valores (trim y quitar vacíos)
$country_filters = array_values(array_filter(array_map('trim', $country_filters), function($c){ return $c !== ''; }));
$sort_by = $_GET['sort'] ?? 'created_at';
$sort_order = $_GET['order'] ?? 'DESC';
$page = max(1, intval($_GET['page'] ?? 1));
// Tamaños de página permitidos para UX profesional
$allowed_page_sizes = [10, 25, 100];
$per_page_param = isset($_GET['per_page']) ? intval($_GET['per_page']) : 25;
$per_page = in_array($per_page_param, $allowed_page_sizes, true) ? $per_page_param : 25;
$offset = ($page - 1) * $per_page;
// Filtro de conexión (online/offline)
$online_filter = $_GET['online'] ?? '';

// Validar campos de ordenamiento
$allowed_sort_fields = ['first_name', 'last_name', 'email', 'phone', 'country', 'company', 'position', 'source', 'status', 'priority', 'created_at', 'updated_at'];
if (!in_array($sort_by, $allowed_sort_fields)) {
    $sort_by = 'created_at';
}
$sort_order = strtoupper($sort_order) === 'ASC' ? 'ASC' : 'DESC';
// Mapear 'position' del UI a columna real 'job_title'
$sort_column = ($sort_by === 'position') ? 'job_title' : $sort_by;

// Construir consulta
$where_conditions = [];
$params = [];

if (!empty($search)) {
    $where_conditions[] = "(l.first_name LIKE ? OR l.last_name LIKE ? OR l.email LIKE ? OR l.phone LIKE ? OR l.company LIKE ?)";
    $search_param = "%$search%";
    $params = array_merge($params, [$search_param, $search_param, $search_param, $search_param, $search_param]);
}

if (!empty($status_filter)) {
    $where_conditions[] = "l.status = ?";
    $params[] = $status_filter;
}

// Excluir siempre los convertidos del listado de Leads
$where_conditions[] = "l.status <> 'converted'";

if (!empty($priority_filter)) {
    $where_conditions[] = "l.priority = ?";
    $params[] = $priority_filter;
}


if (!empty($desk_filter)) {
    $where_conditions[] = "l.desk_id = ?";
    $params[] = $desk_filter;
}

// Si el usuario puede ver todos, permitimos filtrar por empleado; de lo contrario, se ignora
if (!empty($assigned_filter) && $can_view_all) {
    $where_conditions[] = "l.assigned_to = ?";
    $params[] = $assigned_filter;
}

// Filtro por país (IN ...)
if (!empty($country_filters)) {
    $placeholders = implode(',', array_fill(0, count($country_filters), '?'));
    $where_conditions[] = "l.country IN ($placeholders)";
    $params = array_merge($params, $country_filters);
}

// Filtro Online/Offline basado en presencia del cliente vinculado
if (!empty($online_filter)) {
    if ($online_filter === 'online') {
        $where_conditions[] = "TIMESTAMPDIFF(MINUTE, COALESCE(c.last_seen, c.updated_at, c.created_at), NOW()) <= 5";
    } elseif ($online_filter === 'offline') {
        $where_conditions[] = "(c.id IS NULL OR COALESCE(c.last_seen, c.updated_at, c.created_at) IS NULL OR TIMESTAMPDIFF(MINUTE, COALESCE(c.last_seen, c.updated_at, c.created_at), NOW()) > 5)";
    }
}

// Restringir automÃ¡ticamente a leads asignados al usuario si NO tiene 'leads.view_all'
if (!$can_view_all) {
    $where_conditions[] = "l.assigned_to = ?";
    $params[] = $current_user_id;
}

$where_clause = !empty($where_conditions) ? 'WHERE ' . implode(' AND ', $where_conditions) : '';

// Obtener leads
$hasClientLastSeen = false;
try {
    $col = $pdo->query("SHOW COLUMNS FROM `clients` LIKE 'last_seen'");
    $hasClientLastSeen = (bool)$col->fetch();
} catch (Exception $e) { $hasClientLastSeen = false; }
$presenceExprLead = $hasClientLastSeen
    ? "TIMESTAMPDIFF(MINUTE, COALESCE(c.last_seen, c.updated_at, c.created_at), NOW()) <= 5"
    : "TIMESTAMPDIFF(MINUTE, COALESCE(c.updated_at, c.created_at), NOW()) <= 5";

$leads = $db->select(
    "SELECT 
        l.*, 
        l.job_title AS position, 
        d.name AS desk_name, 
        u.username AS assigned_user, 
        CONCAT(u.first_name, ' ', u.last_name) AS assigned_user_name,
        CASE WHEN c.id IS NOT NULL AND $presenceExprLead THEN 1 ELSE 0 END AS is_online
     FROM leads l
     LEFT JOIN clients c ON c.lead_id = l.id
     LEFT JOIN desks d ON l.desk_id = d.id
     LEFT JOIN users u ON l.assigned_to = u.id
     $where_clause
     ORDER BY l.$sort_column $sort_order
     LIMIT $per_page OFFSET $offset",
    $params
);

// Contar total para paginaciÃ³n
$total_leads = $db->count(
    "SELECT COUNT(*) FROM leads l
     LEFT JOIN desks d ON l.desk_id = d.id
     LEFT JOIN users u ON l.assigned_to = u.id
     $where_clause",
    $params
);

$total_pages = max(1, (int)ceil($total_leads / $per_page));

// Obtener datos para filtros
if ($can_view_all) {
    $desks = $db->select("SELECT id, name FROM desks WHERE status = 'active' ORDER BY name");
    $users = $db->select("SELECT id, username, first_name, last_name FROM users WHERE status = 'active' ORDER BY first_name, last_name");
} else {
    // Solo mostrar escritorios vinculados al usuario actual
    $desks = $db->select(
        "SELECT d.id, d.name
         FROM desks d
         INNER JOIN desk_users du ON du.desk_id = d.id
         WHERE du.user_id = ? AND d.status = 'active'
         ORDER BY d.name",
        [$current_user_id]
    );
    // Solo mostrar al usuario logueado
    $users = $db->select(
        "SELECT id, username, first_name, last_name FROM users WHERE id = ? AND status = 'active'",
        [$current_user_id]
    );
}
// PaÃ­ses disponibles en leads (distintos)
$countries = $db->select("SELECT DISTINCT country FROM leads WHERE country IS NOT NULL AND country <> '' ORDER BY country");

// Estados disponibles para filtros (compatibles con desks creados y en el sistema)
try {
    if (!empty($desk_filter)) {
        // Si hay un desk filtrado, obtener solo sus estados permitidos
        $rows = $db->select("SELECT DISTINCT status FROM desk_allowed_statuses WHERE desk_id = ? ORDER BY status", [$desk_filter]);
    } else {
        // En general: estados de todos los desks activos
        $rows = $db->select("SELECT DISTINCT das.status FROM desk_allowed_statuses das INNER JOIN desks d ON das.desk_id = d.id WHERE d.status = 'active' ORDER BY das.status");
    }
    $leadStatusRows = $db->select("SELECT DISTINCT status FROM leads ORDER BY status");
    $statusesSet = [];
    foreach ($rows as $r) { if (!empty($r['status'])) $statusesSet[$r['status']] = true; }
    foreach ($leadStatusRows as $r) { if (!empty($r['status'])) $statusesSet[$r['status']] = true; }
    $statuses = array_keys($statusesSet);
    sort($statuses);
} catch (Exception $e) {
    // Fallback: lista vacÃ­a (el contenido manejarÃ¡ etiquetas por defecto)
    $statuses = [];
}

// EstadÃ­sticas rÃ¡pidas
// EstadÃ­sticas rÃ¡pidas filtradas por permisos
if (userHasPermissionByName($pdo, 'leads.view_all', $current_user_id)) {
    $stats = [
        'total' => $db->count("SELECT COUNT(*) FROM leads"),
        'new' => $db->count("SELECT COUNT(*) FROM leads WHERE status = 'new'"),
        'qualified' => $db->count("SELECT COUNT(*) FROM leads WHERE status = 'qualified'"),
        'deposited' => $db->count("SELECT COUNT(*) FROM leads WHERE status = 'deposited'"),
        'active_traders' => $db->count("SELECT COUNT(*) FROM leads WHERE status = 'active_trader'")
    ];
} else {
    $stats = [
        'total' => $db->count("SELECT COUNT(*) FROM leads WHERE assigned_to = ?", [$current_user_id]),
        'new' => $db->count("SELECT COUNT(*) FROM leads WHERE status = 'new' AND assigned_to = ?", [$current_user_id]),
        'qualified' => $db->count("SELECT COUNT(*) FROM leads WHERE status = 'qualified' AND assigned_to = ?", [$current_user_id]),
        'deposited' => $db->count("SELECT COUNT(*) FROM leads WHERE status = 'deposited' AND assigned_to = ?", [$current_user_id]),
        'active_traders' => $db->count("SELECT COUNT(*) FROM leads WHERE status = 'active_trader' AND assigned_to = ?", [$current_user_id])
    ];
}

// FunciÃ³n para obtener el color del estado
function getStatusColor($status) {
    $colors = [
        'new' => 'bg-blue-100 text-blue-800',
        'contacted' => 'bg-yellow-100 text-yellow-800',
        'qualified' => 'bg-green-100 text-green-800',
        'demo_scheduled' => 'bg-purple-100 text-purple-800',
        'demo_completed' => 'bg-indigo-100 text-indigo-800',
        'deposit_pending' => 'bg-orange-100 text-orange-800',
        'deposited' => 'bg-emerald-100 text-emerald-800',
        'active_trader' => 'bg-teal-100 text-teal-800',
        'inactive' => 'bg-gray-100 text-gray-800',
        'closed_lost' => 'bg-red-100 text-red-800'
    ];
    return $colors[$status] ?? 'bg-gray-100 text-gray-800';
}

// FunciÃ³n para obtener el color de la prioridad
function getPriorityColor($priority) {
    $colors = [
        'low' => 'bg-gray-100 text-gray-600',
        'medium' => 'bg-blue-100 text-blue-600',
        'high' => 'bg-orange-100 text-orange-600',
        'urgent' => 'bg-red-100 text-red-600'
    ];
    return $colors[$priority] ?? 'bg-gray-100 text-gray-600';
}

// FunciÃ³n para formatear la experiencia de trading
function formatTradingExperience($experience) {
    $labels = [
        'none' => 'Sin experiencia',
        'beginner' => 'Principiante',
        'intermediate' => 'Intermedio',
        'advanced' => 'Avanzado',
        'professional' => 'Profesional'
    ];
    return $labels[$experience] ?? 'No especificado';
}

// Configurar layout corporativo
$page_title = 'Leads';
$module = 'leads';
$action = 'index';
$content_file = BASE_PATH . '/modules/leads/leads_content.php';

// Incluir layout unificado con sidebar y header corporativo
include BASE_PATH . '/modules/shared/layout.php';
return;
?>

<div class="leads-container">
    <!-- Header de Leads -->
    <div class="leads-header">
        <div class="header-left">
            <h1 class="page-title">
                <svg class="title-icon" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                    <path d="M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"/>
                    <circle cx="9" cy="7" r="4"/>
                    <path d="m22 2-5 10-5-5-5 10"/>
                </svg>
                Gestión de Leads
            </h1>
            <p class="page-subtitle">Administra y da seguimiento a tus prospectos de trading</p>
        </div>
        <div class="header-actions">
            <button class="btn-secondary" onclick="openImportModal()">
                <svg class="btn-icon" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                    <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/>
                    <polyline points="7,10 12,15 17,10"/>
                    <line x1="12" y1="15" x2="12" y2="3"/>
                </svg>
                <span class="btn-label">Importar leads</span>
            </button>
            <button class="btn-primary" onclick="openCreateModal()">
                <svg class="btn-icon" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                    <line x1="12" y1="5" x2="12" y2="19"/>
                    <line x1="5" y1="12" x2="19" y2="12"/>
                </svg>
                <span class="btn-label">Nuevo lead</span>
            </button>
            <a href="<?php echo route_url(['module'=>'clients']); ?>" class="btn-secondary">
                <svg class="btn-icon" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                    <path d="M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"/>
                    <circle cx="9" cy="7" r="4"/>
                </svg>
                <span class="btn-label">Ver Clientes</span>
            </a>
        </div>
    </div>

    <!-- EstadÃ­sticas RÃ¡pidas -->
    <div class="stats-grid">
        <div class="stat-card" data-stat-key="total">
            <div class="stat-icon bg-blue-500">
                <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                    <path d="M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"/>
                    <circle cx="9" cy="7" r="4"/>
                </svg>
            </div>
            <div class="stat-content">
                <div class="stat-number"><?php echo number_format($stats['total']); ?></div>
                <div class="stat-label">Total Leads</div>
            </div>
        </div>
        
        <div class="stat-card" data-stat-key="new">
            <div class="stat-icon bg-yellow-500">
                <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                    <circle cx="12" cy="12" r="10"/>
                    <path d="M12 6v6l4 2"/>
                </svg>
            </div>
            <div class="stat-content">
                <div class="stat-number"><?php echo number_format($stats['new']); ?></div>
                <div class="stat-label">Nuevos</div>
            </div>
        </div>
        
        <div class="stat-card" data-stat-key="qualified">
            <div class="stat-icon bg-green-500">
                <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                    <path d="M9 12l2 2 4-4"/>
                    <circle cx="12" cy="12" r="10"/>
                </svg>
            </div>
            <div class="stat-content">
                <div class="stat-number"><?php echo number_format($stats['qualified']); ?></div>
                <div class="stat-label">Calificados</div>
            </div>
        </div>
        
        <div class="stat-card" data-stat-key="deposited">
            <div class="stat-icon bg-emerald-500">
                <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                    <line x1="12" y1="1" x2="12" y2="23"/>
                    <path d="M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6"/>
                </svg>
            </div>
            <div class="stat-content">
                <div class="stat-number"><?php echo number_format($stats['deposited']); ?></div>
                <div class="stat-label">Con Depósito</div>
            </div>
        </div>
        
        <div class="stat-card" data-stat-key="active_traders">
            <div class="stat-icon bg-teal-500">
                <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                    <polyline points="22,12 18,12 15,21 9,3 6,12 2,12"/>
                </svg>
            </div>
            <div class="stat-content">
                <div class="stat-number"><?php echo number_format($stats['active_traders']); ?></div>
                <div class="stat-label">Traders Activos</div>
            </div>
        </div>
    </div>

    <!-- Filtros y Búsqueda -->
    <div class="filters-section">
        <form method="GET" class="filters-form">
            <input type="hidden" name="module" value="leads">
            
            <div class="search-box">
                <svg class="search-icon" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                    <circle cx="11" cy="11" r="8"/>
                    <path d="m21 21-4.35-4.35"/>
                </svg>
                <input type="text" name="search" value="<?php echo htmlspecialchars($search); ?>" 
                       placeholder="Buscar por nombre, email, teléfono o empresa..." class="search-input">
            </div>
            
            <div class="filter-group">
                <select name="status" class="filter-select">
                    <option value="">Todos los estados</option>
                    <option value="new" <?php echo $status_filter === 'new' ? 'selected' : ''; ?>>Nuevo</option>
                    <option value="contacted" <?php echo $status_filter === 'contacted' ? 'selected' : ''; ?>>Contactado</option>
                    <option value="qualified" <?php echo $status_filter === 'qualified' ? 'selected' : ''; ?>>Calificado</option>
                    <option value="demo_scheduled" <?php echo $status_filter === 'demo_scheduled' ? 'selected' : ''; ?>>Demo Programado</option>
                    <option value="demo_completed" <?php echo $status_filter === 'demo_completed' ? 'selected' : ''; ?>>Demo Completado</option>
                    <option value="deposit_pending" <?php echo $status_filter === 'deposit_pending' ? 'selected' : ''; ?>>Depósito Pendiente</option>
                    <option value="deposited" <?php echo $status_filter === 'deposited' ? 'selected' : ''; ?>>Con DepÃ³sito</option>
                    <option value="active_trader" <?php echo $status_filter === 'active_trader' ? 'selected' : ''; ?>>Trader Activo</option>
                    <option value="inactive" <?php echo $status_filter === 'inactive' ? 'selected' : ''; ?>>Inactivo</option>
                    <option value="closed_lost" <?php echo $status_filter === 'closed_lost' ? 'selected' : ''; ?>>Perdido</option>
                </select>
                
                <select name="priority" class="filter-select">
                    <option value="">Todas las prioridades</option>
                    <option value="low" <?php echo $priority_filter === 'low' ? 'selected' : ''; ?>>Baja</option>
                    <option value="medium" <?php echo $priority_filter === 'medium' ? 'selected' : ''; ?>>Media</option>
                    <option value="high" <?php echo $priority_filter === 'high' ? 'selected' : ''; ?>>Alta</option>
                    <option value="urgent" <?php echo $priority_filter === 'urgent' ? 'selected' : ''; ?>>Urgente</option>
                </select>
                
                <select name="experience" class="filter-select">
                    <option value="">Toda experiencia</option>
                    <option value="none" <?php echo $experience_filter === 'none' ? 'selected' : ''; ?>>Sin experiencia</option>
                    <option value="beginner" <?php echo $experience_filter === 'beginner' ? 'selected' : ''; ?>>Principiante</option>
                    <option value="intermediate" <?php echo $experience_filter === 'intermediate' ? 'selected' : ''; ?>>Intermedio</option>
                    <option value="advanced" <?php echo $experience_filter === 'advanced' ? 'selected' : ''; ?>>Avanzado</option>
                    <option value="professional" <?php echo $experience_filter === 'professional' ? 'selected' : ''; ?>>Profesional</option>
                </select>
                
                <?php if (!empty($desks)): ?>
                <select name="desk" class="filter-select">
                    <option value="">Todos los escritorios</option>
                    <?php foreach ($desks as $desk): ?>
                        <option value="<?php echo $desk['id']; ?>" <?php echo $desk_filter == $desk['id'] ? 'selected' : ''; ?>>
                            <?php echo htmlspecialchars($desk['name']); ?>
                        </option>
                    <?php endforeach; ?>
                </select>
                <?php endif; ?>
                
                <?php if (!empty($users)): ?>
                <select name="assigned" class="filter-select">
                    <option value="">Todos los agentes</option>
                    <?php foreach ($users as $user): ?>
                        <option value="<?php echo $user['id']; ?>" <?php echo $assigned_filter == $user['id'] ? 'selected' : ''; ?>>
                            <?php echo htmlspecialchars($user['first_name'] . ' ' . $user['last_name']); ?>
                        </option>
                    <?php endforeach; ?>
                </select>
                <?php endif; ?>
            </div>
            
            <div class="filter-actions">
                <button type="submit" class="btn-primary">
                    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                        <polygon points="22,3 2,3 10,12.46 10,19 14,21 14,12.46"/>
                    </svg>
                    Filtrar
                </button>
                <a href="?module=leads" class="btn-secondary">Limpiar</a>
            </div>
        </form>
    </div>

    <!-- Tabla de Leads -->
    <div class="table-container">
        <div class="table-header">
            <div class="table-title">
                <h3>Lista de Leads (<?php echo number_format($total_leads); ?> resultados)</h3>
            </div>
            <div class="table-actions">
                <button class="btn-ghost" onclick="exportLeads()">
                    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                        <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-15"/>
                        <polyline points="17,10 12,5 7,10"/>
                        <line x1="12" y1="16" x2="12" y2="5"/>
                    </svg>
                    Exportar
                </button>
            </div>
        </div>
        
        <?php if (empty($leads)): ?>
            <div class="empty-state">
                <div class="empty-icon">
                    <svg width="64" height="64" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1">
                        <path d="M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"/>
                        <circle cx="9" cy="7" r="4"/>
                        <path d="m22 2-5 10-5-5-5 10"/>
                    </svg>
                </div>
                <h3>No se encontraron leads</h3>
                <p>No hay leads que coincidan con los filtros seleccionados.</p>
                <button class="btn-primary" onclick="openCreateModal()">Crear primer lead</button>
            </div>
        <?php else: ?>
            <div class="table-responsive">
                <table class="leads-table data-table">
                    <thead>
                        <tr>
                            <th>
                                <input type="checkbox" id="selectAll" onchange="toggleSelectAll()">
                            </th>
                            <th class="sortable <?php echo $sort_by === 'first_name' ? 'sorted-' . strtolower($sort_order) : ''; ?>" 
                                onclick="sortTable('first_name')">
                                Nombre
                                <svg class="sort-icon" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                    <path d="M8 9l4-4 4 4"/>
                                    <path d="M16 15l-4 4-4-4"/>
                                </svg>
                            </th>
                            <th class="sortable <?php echo $sort_by === 'email' ? 'sorted-' . strtolower($sort_order) : ''; ?>" 
                                onclick="sortTable('email')">
                                Email
                                <svg class="sort-icon" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                    <path d="M8 9l4-4 4 4"/>
                                    <path d="M16 15l-4 4-4-4"/>
                                </svg>
                            </th>
                            <th>Teléfono</th>
                            <th>País</th>
                            <th class="sortable <?php echo $sort_by === 'status' ? 'sorted-' . strtolower($sort_order) : ''; ?>" 
                                onclick="sortTable('status')">
                                Estado
                                <svg class="sort-icon" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                    <path d="M8 9l4-4 4 4"/>
                                    <path d="M16 15l-4 4-4-4"/>
                                </svg>
                            </th>
                            <th class="sortable <?php echo $sort_by === 'priority' ? 'sorted-' . strtolower($sort_order) : ''; ?>" 
                                onclick="sortTable('priority')">
                                Prioridad
                                <svg class="sort-icon" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                    <path d="M8 9l4-4 4 4"/>
                                    <path d="M16 15l-4 4-4-4"/>
                                </svg>
                            </th>
                            <th class="sortable <?php echo $sort_by === 'trading_experience' ? 'sorted-' . strtolower($sort_order) : ''; ?>" 
                                onclick="sortTable('trading_experience')">
                                Experiencia
                                <svg class="sort-icon" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                    <path d="M8 9l4-4 4 4"/>
                                    <path d="M16 15l-4 4-4-4"/>
                                </svg>
                            </th>
                            <th class="sortable <?php echo $sort_by === 'investment_amount' ? 'sorted-' . strtolower($sort_order) : ''; ?>" 
                                onclick="sortTable('investment_amount')">
                                Inversión
                                <svg class="sort-icon" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                    <path d="M8 9l4-4 4 4"/>
                                    <path d="M16 15l-4 4-4-4"/>
                                </svg>
                            </th>
                            <th class="sortable <?php echo $sort_by === 'lead_score' ? 'sorted-' . strtolower($sort_order) : ''; ?>" 
                                onclick="sortTable('lead_score')">
                                Score
                                <svg class="sort-icon" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                    <path d="M8 9l4-4 4 4"/>
                                    <path d="M16 15l-4 4-4-4"/>
                                </svg>
                            </th>
                            <th>Asignado</th>
                            <th class="sortable <?php echo $sort_by === 'updated_at' ? 'sorted-' . strtolower($sort_order) : ''; ?>" 
                                onclick="sortTable('updated_at')">
                                Última actualización
                                <svg class="sort-icon" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                    <path d="M8 9l4-4 4 4"/>
                                    <path d="M16 15l-4 4-4-4"/>
                                </svg>
                            </th>
                            <th>Acciones</th>
                            
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($leads as $lead): ?>
                            <tr class="lead-row" data-lead-id="<?php echo $lead['id']; ?>">
                                <td>
                                    <input type="checkbox" class="lead-checkbox" value="<?php echo $lead['id']; ?>">
                                </td>
                                <td class="lead-name">
                                    <div class="name-cell" onclick="viewLead(<?php echo $lead['id']; ?>)" style="cursor:pointer">
                                        <div class="avatar">
                                            <?php echo strtoupper(substr($lead['first_name'], 0, 1) . substr($lead['last_name'], 0, 1)); ?>
                                        </div>
                                        <div class="name-info">
<div class="full-name"><a href="<?php echo route_url(['module' => 'leads', 'action' => 'view', 'id' => (int)$lead['id']]); ?>" class="lead-name-link"><?php echo htmlspecialchars($lead['first_name'] . ' ' . $lead['last_name']); ?></a></div>
                                            <?php if (!empty($lead['company'])): ?>
                                                <div class="company"><?php echo htmlspecialchars($lead['company']); ?></div>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                </td>
                                <td class="lead-email">
                                    <a href="mailto:<?php echo htmlspecialchars($lead['email']); ?>" class="email-link">
                                        <?php echo htmlspecialchars($lead['email']); ?>
                                    </a>
                                </td>
                                <td class="lead-phone">
                                    <?php if (!empty($lead['phone'])): ?>
                                        <a href="tel:<?php echo htmlspecialchars($lead['phone']); ?>" class="phone-link">
                                            <?php echo htmlspecialchars($lead['phone']); ?>
                                        </a>
                                    <?php else: ?>
                                        <span class="text-muted">-</span>
                                    <?php endif; ?>
                                </td>
                                <td class="lead-country">
                                    <?php echo !empty($lead['country']) ? htmlspecialchars($lead['country']) : '-'; ?>
                                </td>
                                <td class="lead-status">
                                    <span class="status-badge <?php echo getStatusColor($lead['status']); ?>">
                                        <?php echo ucfirst(str_replace('_', ' ', $lead['status'])); ?>
                                    </span>
                                </td>
                                <td class="lead-priority">
                                    <span class="priority-badge <?php echo getPriorityColor($lead['priority']); ?>">
                                        <?php echo ucfirst($lead['priority']); ?>
                                    </span>
                                </td>
                                <td class="lead-experience">
                                    <?php echo formatTradingExperience($lead['trading_experience']); ?>
                                </td>
                                <td class="lead-investment">
                                    <?php if ($lead['investment_amount'] > 0): ?>
                                        <span class="investment-amount">
                                            $<?php echo number_format($lead['investment_amount'], 0); ?>
                                        </span>
                                    <?php else: ?>
                                        <span class="text-muted">-</span>
                                    <?php endif; ?>
                                </td>
                                <td class="lead-score">
                                    <div class="score-container">
                                        <div class="score-bar">
                                            <div class="score-fill" style="width: <?php echo ($lead['lead_score'] / 1000) * 100; ?>%"></div>
                                        </div>
                                        <span class="score-text"><?php echo $lead['lead_score']; ?></span>
                                    </div>
                                </td>
                                <td class="lead-assigned">
                                    <?php if (!empty($lead['assigned_user_name'])): ?>
                                        <div class="assigned-user">
                                            <span><?php echo htmlspecialchars($lead['assigned_user_name']); ?></span>
                                        </div>
                                    <?php else: ?>
                                        <span class="text-muted">Sin asignar</span>
                                    <?php endif; ?>
                                </td>
                                <td class="lead-created">
                                    <div class="date-info">
                                        <div class="date"><?php echo date('d/m/Y', strtotime($lead['updated_at'] ?? $lead['created_at'])); ?></div>
                                        <div class="time"><?php echo date('H:i', strtotime($lead['updated_at'] ?? $lead['created_at'])); ?></div>
                                    </div>
                                </td>
                                <td class="lead-actions">
                                    <?php if (($lead['status'] ?? '') !== 'converted'): ?>
                                        <a href="/modules/leads/convert_to_client.php?lead_id=<?php echo (int)$lead['id']; ?>" class="btn btn-primary btn-size-sm">Convertir</a>
                                    <?php else: ?>
                                        <span class="status-badge bg-teal-100 text-teal-800">Convertido</span>
                                    <?php endif; ?>
                                </td>
                                
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        <?php endif; ?>
    </div>

    <!-- PaginaciÃ³n -->
    <?php if ($total_pages > 1): ?>
        <div class="pagination-container">
            <div class="pagination-info">
                Mostrando <?php echo (($page - 1) * $per_page) + 1; ?> - <?php echo min($page * $per_page, $total_leads); ?> 
                de <?php echo number_format($total_leads); ?> leads
            </div>
            <div class="pagination">
                <?php if ($page > 1): ?>
                    <a href="<?php echo route_url(array_merge($_GET, ['module'=>'leads','page'=>$page - 1])); ?>" 
                       class="pagination-btn">
                        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                            <polyline points="15,18 9,12 15,6"/>
                        </svg>
                        Anterior
                    </a>
                <?php endif; ?>
                
                <?php
                $start_page = max(1, $page - 2);
                $end_page = min($total_pages, $page + 2);
                
                for ($i = $start_page; $i <= $end_page; $i++):
                ?>
                    <a href="<?php echo route_url(array_merge($_GET, ['module'=>'leads','page'=>$i])); ?>" 
                       class="pagination-btn <?php echo $i === $page ? 'active' : ''; ?>">
                        <?php echo $i; ?>
                    </a>
                <?php endfor; ?>
                
                <?php if ($page < $total_pages): ?>
                    <a href="<?php echo route_url(array_merge($_GET, ['module'=>'leads','page'=>$page + 1])); ?>" 
                       class="pagination-btn">
                        Siguiente
                        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                            <polyline points="9,18 15,12 9,6"/>
                        </svg>
                    </a>
                <?php endif; ?>
            </div>
        </div>
    <?php endif; ?>
</div>

<!-- Modales y Scripts -->
<script>
// Variables globales
let currentSort = '<?php echo $sort_by; ?>';
let currentOrder = '<?php echo $sort_order; ?>';

// FunciÃ³n para ordenar tabla
function sortTable(field) {
    let newOrder = 'ASC';
    if (currentSort === field && currentOrder === 'ASC') {
        newOrder = 'DESC';
    }
    
    const url = new URL(window.location);
    url.searchParams.set('sort', field);
    url.searchParams.set('order', newOrder);
    url.searchParams.set('page', '1'); // Reset a primera pÃ¡gina
    
    window.location.href = url.toString();
}

// FunciÃ³n para seleccionar todos los leads
function toggleSelectAll() {
    const selectAll = document.getElementById('selectAll');
    const checkboxes = document.querySelectorAll('.lead-checkbox');
    
    checkboxes.forEach(checkbox => {
        checkbox.checked = selectAll.checked;
    });
    
    updateBulkActions();
}

// FunciÃ³n para actualizar acciones masivas
function updateBulkActions() {
    const checkedBoxes = document.querySelectorAll('.lead-checkbox:checked');
    const bulkActions = document.querySelector('.bulk-actions');
    
    if (checkedBoxes.length > 0) {
        if (!bulkActions) {
            createBulkActionsBar();
        }
        document.querySelector('.bulk-count').textContent = checkedBoxes.length;
    } else if (bulkActions) {
        bulkActions.remove();
    }
}

// Crear barra de acciones masivas
function createBulkActionsBar() {
    const container = document.querySelector('.leads-container');
    const bulkBar = document.createElement('div');
    bulkBar.className = 'bulk-actions';
    bulkBar.innerHTML = `
        <div class="bulk-info">
            <span class="bulk-count">0</span> leads seleccionados
        </div>
        <div class="bulk-buttons">
            <button class="btn-secondary" onclick="bulkAssign()">Asignar</button>
            <button class="btn-secondary" onclick="bulkChangeStatus()">Cambiar estado</button>
            <button class="btn-secondary" onclick="bulkExport()">Exportar</button>
            <button class="btn-danger" onclick="bulkDelete()">Eliminar</button>
        </div>
        <button class="bulk-close" onclick="clearSelection()">
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                <line x1="18" y1="6" x2="6" y2="18"/>
                <line x1="6" y1="6" x2="18" y2="18"/>
            </svg>
        </button>
    `;
    
    container.insertBefore(bulkBar, container.firstChild);
}

// Limpiar selecciÃ³n
function clearSelection() {
    document.getElementById('selectAll').checked = false;
    document.querySelectorAll('.lead-checkbox').forEach(cb => cb.checked = false);
    updateBulkActions();
}

// Event listeners
document.addEventListener('DOMContentLoaded', function() {
    // Agregar event listeners a checkboxes
    document.querySelectorAll('.lead-checkbox').forEach(checkbox => {
        checkbox.addEventListener('change', updateBulkActions);
    });
    
    // Cerrar dropdowns al hacer clic fuera
    document.addEventListener('click', function(e) {
        if (!e.target.closest('.dropdown')) {
            document.querySelectorAll('.dropdown-menu').forEach(menu => {
                menu.style.display = 'none';
            });
        }
    });
});

// Funciones de acciones
function openCreateModal() {
    window.location.href = '?module=leads&action=create';
}

function openImportModal() {
    // Implementar modal de importaciÃ³n
    alert('Funcionalidad de importaciÃ³n en desarrollo');
}

function viewLead(id) {
    window.location.href = `?module=leads&action=view&id=${id}`;
}

function editLead(id) {
    window.location.href = `?module=leads&action=edit&id=${id}`;
}

function contactLead(id) {
    // Implementar modal de contacto
    alert(`Contactar lead ${id}`);
}

function toggleDropdown(id) {
    const dropdown = document.getElementById(`dropdown-${id}`);
    const isVisible = dropdown.style.display === 'block';
    
    // Cerrar todos los dropdowns
    document.querySelectorAll('.dropdown-menu').forEach(menu => {
        menu.style.display = 'none';
    });
    
    // Mostrar/ocultar el dropdown actual
    dropdown.style.display = isVisible ? 'none' : 'block';
}

function assignLead(id) {
    // Implementar modal de asignaciÃ³n
    alert(`Asignar lead ${id}`);
}

function changeStatus(id) {
    // Implementar modal de cambio de estado
    alert(`Cambiar estado del lead ${id}`);
}

function addNote(id) {
    // Implementar modal de agregar nota
    alert(`Agregar nota al lead ${id}`);
}

function deleteLead(id) {
    if (confirm('Â¿EstÃ¡s seguro de que deseas eliminar este lead?')) {
        // Implementar eliminaciÃ³n
        alert(`Eliminar lead ${id}`);
    }
}

function exportLeads() {
    // Implementar exportaciÃ³n
    alert('Funcionalidad de exportaciÃ³n en desarrollo');
}

// Funciones de acciones masivas
function bulkAssign() {
    const selected = getSelectedLeads();
    if (selected.length === 0) {
        alert('Selecciona al menos un lead');
        return;
    }

    // Construir modal dinÃ¡mico
    const backdrop = document.createElement('div');
    backdrop.className = 'modal-backdrop modal-premium';

    const modal = document.createElement('div');
    modal.className = 'modal';

    // Estados se cargarÃ¡n dinÃ¡micamente segÃºn el desk seleccionado
    const desksData = <?php echo json_encode($desks ?? []); ?>;

    modal.innerHTML = `
        <div class="modal-header">
            <div class="modal-title">
                <span class="modal-icon">ðŸ“¦</span>
                <h3>AsignaciÃ³n Masiva de Leads</h3>
            </div>
            <button class="btn-ghost" onclick="(function(el){ el.closest('.modal-backdrop')?.remove(); })(this)">&times;</button>
        </div>
        <div class="modal-body">
            <div class="modal-lead-context">
                <strong>${selected.length}</strong> leads seleccionados
            </div>
            <div class="form-group">
                <label class="form-label">Selecciona Desk</label>
                <select id="bulkDeskSelect" class="form-control">
                    <option value="">-- Selecciona un desk --</option>
                    ${desksData.map(d => `<option value="${d.id}">${d.name}</option>`).join('')}
                </select>
            </div>
            <div class="form-group">
                <label class="form-label">Empleados del Desk</label>
                <div id="bulkDeskUsers" class="permissions-by-module" style="border:1px solid var(--border-light); border-radius:10px; padding:8px; min-height:48px;">
                    <em style="color:#64748b">Selecciona un desk para cargar empleados...</em>
                </div>
            </div>
            <div class="form-group">
                <label class="form-label">Estado de asignaciÃ³n</label>
                <select id="bulkStatusSelect" class="form-control">
                    <option value="">-- Selecciona un desk primero --</option>
                </select>
            </div>
            <div id="bulkDistributionInfo" class="empty-state" style="margin-top:8px;">
                <div class="empty-icon">âš–ï¸</div>
                <div>DistribuciÃ³n: selecciona empleados para calcular reparto automÃ¡tico</div>
            </div>
        </div>
        <div class="modal-footer">
            <button class="btn-secondary" onclick="(function(el){ el.closest('.modal-backdrop')?.remove(); })(this)">Cancelar</button>
            <button class="btn-primary" id="bulkAssignConfirmBtn">Asignar Leads</button>
        </div>
    `;

    backdrop.appendChild(modal);
    document.body.appendChild(backdrop);

    const deskSelect = modal.querySelector('#bulkDeskSelect');
    const usersContainer = modal.querySelector('#bulkDeskUsers');
    const statusSelect = modal.querySelector('#bulkStatusSelect');
    const distInfo = modal.querySelector('#bulkDistributionInfo');
    const confirmBtn = modal.querySelector('#bulkAssignConfirmBtn');

    function updateDistribution() {
        const checked = usersContainer.querySelectorAll('input[type="checkbox"]:checked');
        const nUsers = checked.length;
        const nLeads = selected.length;
        if (nUsers === 0) {
            distInfo.innerHTML = `<div class=\"empty-icon\">âš–ï¸</div><div>DistribuciÃ³n: selecciona empleados para calcular reparto automÃ¡tico</div>`;
            return;
        }
        if (nUsers === 1) {
            const name = checked[0].getAttribute('data-name') || 'Empleado';
            distInfo.innerHTML = `<div class=\"empty-icon\">ðŸ‘¤</div><div>${nLeads} leads serÃ¡n asignados a <strong>${name}</strong></div>`;
            return;
        }
        const base = Math.floor(nLeads / nUsers);
        const rem = nLeads % nUsers;
        distInfo.innerHTML = `<div class=\"empty-icon\">âš–ï¸</div><div>${nLeads} leads, ${nUsers} empleados â†’ ${base} por empleado ${rem ? `y ${rem} adicionales distribuidos` : ''}</div>`;
    }

    async function loadDeskUsers(deskId) {
        usersContainer.innerHTML = '<em style="color:#64748b">Cargando empleados...</em>';
        try {
            const resp = await fetch(`/modules/leads/get_desk_users.php?desk_id=${encodeURIComponent(deskId)}`);
            const data = await resp.json();
            if (!data.success) {
                usersContainer.innerHTML = `<span style='color:#ef4444'>Error: ${(data.message||'No se pudo cargar')}</span>`;
                return;
            }
            if (!data.users || data.users.length === 0) {
                usersContainer.innerHTML = '<em style="color:#64748b">No hay empleados activos en este desk.</em>';
                updateDistribution();
                return;
            }
            usersContainer.innerHTML = '';
            data.users.forEach(u => {
                const row = document.createElement('label');
                row.className = 'permission-check';
                row.style.margin = '4px 0';
                row.innerHTML = `
                    <input type="checkbox" class="bulk-user" value="${u.id}" data-name="${u.full_name || u.username}">
                    <span class="permission-label" data-text="${u.full_name || u.username}">${u.full_name || u.username}</span>
                `;
                usersContainer.appendChild(row);
            });
            usersContainer.querySelectorAll('.bulk-user').forEach(cb => cb.addEventListener('change', updateDistribution));
            updateDistribution();
        } catch (e) {
            usersContainer.innerHTML = `<span style='color:#ef4444'>Error de red: ${e.message}</span>`;
        }
    }

    async function loadDeskStatuses(deskId) {
        statusSelect.innerHTML = '<option value="">-- Selecciona estado del desk --</option>';
        if (!deskId) return;
        try {
            const resp = await fetch(`/modules/leads/get_desk_statuses.php?desk_id=${encodeURIComponent(deskId)}`);
            const data = await resp.json();
            if (data.success && Array.isArray(data.statuses)) {
                statusSelect.innerHTML = '';
                data.statuses.forEach(s => {
                    const opt = document.createElement('option');
                    opt.value = s; opt.textContent = String(s).replace('_',' ');
                    statusSelect.appendChild(opt);
                });
                if (!data.statuses.length) {
                    statusSelect.innerHTML = '<option value="">-- Sin estados configurados en este desk --</option>';
                }
            }
        } catch (e) {}
    }

    deskSelect.addEventListener('change', function() {
        const val = deskSelect.value;
        if (!val) {
            usersContainer.innerHTML = '<em style="color:#64748b">Selecciona un desk para cargar empleados...</em>';
            statusSelect.innerHTML = '<option value="">-- Selecciona un desk primero --</option>';
            updateDistribution();
            return;
        }
        loadDeskUsers(val);
        loadDeskStatuses(val);
    });

    confirmBtn.addEventListener('click', async function() {
        const deskId = deskSelect.value;
        const statusSel = modal.querySelector('#bulkStatusSelect').value;
        const selectedUsers = Array.from(usersContainer.querySelectorAll('.bulk-user:checked')).map(cb => cb.value);
        if (!deskId) { alert('Selecciona un desk'); return; }
        if (!statusSel) { alert('Selecciona el estado de asignaciÃ³n'); return; }
        if (selectedUsers.length === 0) { alert('Selecciona al menos un empleado'); return; }

        const form = new FormData();
        selected.forEach(id => form.append('lead_ids[]', id));
        selectedUsers.forEach(uid => form.append('user_ids[]', uid));
        form.append('desk_id', deskId);
        form.append('status', statusSel);

        confirmBtn.disabled = true;
        confirmBtn.textContent = 'Asignando...';
        try {
            const resp = await fetch('/modules/leads/bulk_assign.php', { method: 'POST', body: form });
            const data = await resp.json();
            if (data.success) {
                // NotificaciÃ³n sin recarga
                alert('Leads asignados correctamente');
                // Cerrar modal y limpiar selecciÃ³n
                backdrop.remove();
                clearSelection();
                // Helper: clases para badge de estado
                const statusClasses = {
                    new: 'bg-blue-100 text-blue-800',
                    contacted: 'bg-yellow-100 text-yellow-800',
                    qualified: 'bg-green-100 text-green-800',
                    demo_scheduled: 'bg-purple-100 text-purple-800',
                    demo_completed: 'bg-indigo-100 text-indigo-800',
                    deposit_pending: 'bg-orange-100 text-orange-800',
                    deposited: 'bg-emerald-100 text-emerald-800',
                    active_trader: 'bg-teal-100 text-teal-800',
                    inactive: 'bg-gray-100 text-gray-800',
                    closed_lost: 'bg-red-100 text-red-800'
                };
                function setBadgeClass(el, key){
                    const cls = statusClasses[key] || 'bg-gray-100 text-gray-800';
                    el.className = 'status-badge ' + cls;
                }
                // Actualizar filas utilizando el mapeo lead_updates si estÃ¡ disponible
                const updates = (data.data && Array.isArray(data.data.lead_updates)) ? data.data.lead_updates : null;
                if (updates && updates.length) {
                    updates.forEach(up => {
                        const lid = up.lead_id;
                        const row = document.querySelector(`.lead-row[data-lead-id="${lid}"]`);
                        if (!row) return;
                        // Assigned user
                        const assignedCell = row.querySelector('.lead-assigned');
                        if (assignedCell) {
                            const name = String(up.assigned_user_name || '').trim();
                            if (name) {
                                const span = assignedCell.querySelector('.assigned-user span');
                                if (span) { span.textContent = name; }
                                else { assignedCell.innerHTML = `<div class="assigned-user"><span>${name}</span></div>`; }
                            } else {
                                assignedCell.innerHTML = '<span class="text-muted">Sin asignar</span>';
                            }
                        }
                        // Status badge
                        const badge = row.querySelector('.lead-status .status-badge');
                        if (badge) {
                            const key = String(up.status || '').trim();
                            badge.textContent = key.replace('_',' ');
                            setBadgeClass(badge, key);
                        }
                        // Si existe columna de desk en otras vistas, opcionalmente se podrÃ­a actualizar aquÃ­
                    });
                } else {
                    // Fallback: actualizar solo estado de las filas seleccionadas
                    selected.forEach(id => {
                        const row = document.querySelector(`.lead-row[data-lead-id="${id}"]`);
                        const badge = row?.querySelector('.lead-status .status-badge');
                        if (badge) { badge.textContent = String(statusSel || '').replace('_',' '); setBadgeClass(badge, String(statusSel || '')); }
                    });
                }
                // Refrescar widgets para garantizar consistencia
                refreshStatsWidgets();
            } else {
                alert('Error: ' + (data.message || 'No se pudo asignar'));
            }
        } catch (e) {
            alert('Error de red: ' + e.message);
        } finally {
            confirmBtn.disabled = false;
            confirmBtn.textContent = 'Asignar Leads';
        }
    });
}

function bulkChangeStatus() {
    const selected = getSelectedLeads();
    alert(`Cambiar estado de ${selected.length} leads`);
}

function bulkExport() {
    const selected = getSelectedLeads();
    alert(`Exportar ${selected.length} leads`);
}

function bulkDelete() {
    const selected = getSelectedLeads();
    if (selected.length === 0) { alert('Selecciona al menos un lead'); return; }
    if (!confirm(`Â¿EstÃ¡s seguro de que deseas eliminar ${selected.length} leads?`)) { return; }

    // Capturar estados de las filas a eliminar para actualizar widgets
    const rows = selected.map(id => document.querySelector(`.lead-row[data-lead-id="${id}"]`)).filter(Boolean);
    const statusCounts = {};
    rows.forEach(row => {
        const badge = row.querySelector('.lead-status .status-badge');
        if (badge) {
            const label = (badge.textContent || '').trim().toLowerCase();
            const key = label.replace(/\s+/g, '_');
            statusCounts[key] = (statusCounts[key] || 0) + 1;
        }
    });

    const form = new FormData();
    selected.forEach(id => form.append('lead_ids[]', id));

    fetch('/modules/leads/bulk_delete.php', { method: 'POST', body: form })
        .then(resp => resp.json())
        .then(data => {
            if (!data.success) {
                alert('Error: ' + (data.message || 'No se pudo eliminar'));
                return;
            }
            const ids = (data.data && data.data.deleted_ids) ? data.data.deleted_ids : selected;
            // Actualizar widgets de estadÃ­sticas
            updateStatsWidgets(ids.length, statusCounts);
            ids.forEach(id => {
                const row = document.querySelector(`.lead-row[data-lead-id="${id}"]`);
                if (row) row.remove();
            });
            updateBulkActions();
            alert('Leads eliminados correctamente');
        })
        .catch(e => alert('Error de red: ' + e.message));
}

function updateStatsWidgets(deletedCount, statusCounts) {
    // Decremento rÃ¡pido local y luego sincronizaciÃ³n vÃ­a endpoint
    const parseNum = (txt) => {
        const m = (txt || '').match(/\d+/g);
        if (!m) return 0;
        return parseInt(m.join(''), 10) || 0;
    };
    const formatNum = (n) => new Intl.NumberFormat('es-ES').format(n);

    const cards = document.querySelectorAll('.stats-grid .stat-card');
    const decs = Object.assign({ total: deletedCount }, statusCounts || {});
    cards.forEach(card => {
        const key = card.getAttribute('data-stat-key');
        const numEl = card.querySelector('.stat-number');
        if (!key || !numEl) return;
        const current = parseNum(numEl.textContent);
        const dec = decs[key] || 0;
        if (dec > 0) numEl.textContent = formatNum(Math.max(0, current - dec));
    });

    // Actualizar conteo de resultados en el tÃ­tulo de la tabla
    updateTableResultsCount(deletedCount);

    // Sincronizar con el servidor para asegurar consistencia total
    refreshStatsWidgets();
}

function refreshStatsWidgets() {
    fetch('/modules/leads/stats.php')
        .then(r => r.json())
        .then(j => {
            if (!j.success || !j.data) return;
            const formatNum = (n) => new Intl.NumberFormat('es-ES').format(n);
            const map = j.data;
            document.querySelectorAll('.stats-grid .stat-card').forEach(card => {
                const key = card.getAttribute('data-stat-key');
                const numEl = card.querySelector('.stat-number');
                if (!key || !numEl) return;
                if (key in map) numEl.textContent = formatNum(map[key] || 0);
            });
        })
        .catch(() => {});
}

function updateTableResultsCount(deletedCount) {
    const titleEl = document.querySelector('.table-title h3');
    if (!titleEl) return;
    const m = titleEl.textContent.match(/\(([^\)]*)\)/);
    if (!m) return;
    const parseNum = (txt) => {
        const mm = (txt || '').match(/\d+/g);
        if (!mm) return 0;
        return parseInt(mm.join(''), 10) || 0;
    };
    const current = parseNum(m[1]);
    const next = Math.max(0, current - (deletedCount || 0));
    titleEl.textContent = titleEl.textContent.replace(m[1], new Intl.NumberFormat('es-ES').format(next) + ' resultados');
}

function getSelectedLeads() {
    return Array.from(document.querySelectorAll('.lead-checkbox:checked')).map(cb => cb.value);
}
</script>

<?php include BASE_PATH . '/modules/shared/footer.php'; ?>
