<?php
session_start();
if (!defined('BASE_PATH')) { define('BASE_PATH', __DIR__); }
require_once BASE_PATH . '/database/config.php';
require_once BASE_PATH . '/database/connection.php';

$pdo = getDB()->getConnection();
$current_user_id = (int)($_SESSION['user_id'] ?? 0);

function userHasPermissionByName($pdo, $permName, $userId) {
    if (empty($userId)) return false;
    $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();
}

echo "<h2>Debug Detallado - Lista de Leads</h2>";
echo "<p>Usuario ID: " . $current_user_id . "</p>";

if ($current_user_id > 0) {
    // 1. Verificar permisos críticos
    echo "<h3>1. Permisos Críticos</h3>";
    $canViewAll = userHasPermissionByName($pdo, 'leads.view_all', $current_user_id);
    $canView = userHasPermissionByName($pdo, 'leads.view', $current_user_id);
    
    echo "<p>leads.view: " . ($canView ? '✅ SÍ' : '❌ NO') . "</p>";
    echo "<p>leads.view_all: " . ($canViewAll ? '✅ SÍ' : '❌ NO') . "</p>";
    
    // 2. Simular exactamente la lógica del index.php
    echo "<h3>2. Simulación Exacta del Index.php</h3>";
    
    // Parámetros de búsqueda y filtros (como en index.php)
    $search = $_GET['search'] ?? '';
    $priority_filter = $_GET['priority'] ?? '';
    $desk_filter = $_GET['desk'] ?? '';
    $assigned_filter = $_GET['assigned'] ?? '';
    $country_filter = $_GET['country'] ?? [];
    $online_filter = $_GET['online'] ?? '';
    $page = max(1, (int)($_GET['page'] ?? 1));
    $per_page = max(1, min(100, (int)($_GET['per_page'] ?? 25)));
    $offset = ($page - 1) * $per_page;
    
    echo "<p><strong>Parámetros de filtro:</strong></p>";
    echo "<ul>";
    echo "<li>Búsqueda: '" . htmlspecialchars($search) . "'</li>";
    echo "<li>Prioridad: '" . htmlspecialchars($priority_filter) . "'</li>";
    echo "<li>Desk: '" . htmlspecialchars($desk_filter) . "'</li>";
    echo "<li>Asignado: '" . htmlspecialchars($assigned_filter) . "'</li>";
    echo "<li>País: " . (is_array($country_filter) ? implode(', ', $country_filter) : $country_filter) . "</li>";
    echo "<li>Online: '" . htmlspecialchars($online_filter) . "'</li>";
    echo "<li>Página: $page</li>";
    echo "<li>Por página: $per_page</li>";
    echo "<li>Offset: $offset</li>";
    echo "</ul>";
    
    // Construir WHERE clause exactamente como en index.php
    $whereConditions = [];
    $params = [];
    
    // Restricción de permisos
    if (!$canViewAll) {
        $whereConditions[] = "(l.assigned_to = ? OR l.assigned_to IS NULL)";
        $params[] = $current_user_id;
        echo "<p style='color: orange;'>⚠️ Aplicando restricción: solo leads asignados al usuario o sin asignar</p>";
    } else {
        echo "<p style='color: green;'>✅ Sin restricción: puede ver todos los leads</p>";
    }
    
    // Filtro de búsqueda
    if (!empty($search)) {
        $whereConditions[] = "(l.first_name LIKE ? OR l.last_name LIKE ? OR l.email LIKE ? OR l.phone LIKE ?)";
        $searchParam = "%$search%";
        $params = array_merge($params, [$searchParam, $searchParam, $searchParam, $searchParam]);
    }
    
    // Filtro de prioridad
    if (!empty($priority_filter)) {
        $whereConditions[] = "l.priority = ?";
        $params[] = $priority_filter;
    }
    
    // Filtro de desk
    if (!empty($desk_filter)) {
        $whereConditions[] = "l.desk_id = ?";
        $params[] = $desk_filter;
    }
    
    // Filtro de asignado
    if (!empty($assigned_filter)) {
        if ($assigned_filter === 'unassigned') {
            $whereConditions[] = "l.assigned_to IS NULL";
        } else {
            $whereConditions[] = "l.assigned_to = ?";
            $params[] = $assigned_filter;
        }
    }
    
    // Filtro de país
    if (!empty($country_filter) && is_array($country_filter)) {
        $placeholders = str_repeat('?,', count($country_filter) - 1) . '?';
        $whereConditions[] = "l.country IN ($placeholders)";
        $params = array_merge($params, $country_filter);
    }
    
    // Filtro online/offline (alineado con index.php: usa COALESCE(updated_at, created_at))
    if (!empty($online_filter)) {
        if ($online_filter === 'online') {
            $whereConditions[] = "COALESCE(l.updated_at, l.created_at) >= DATE_SUB(NOW(), INTERVAL 5 MINUTE)";
        } else {
            $whereConditions[] = "(COALESCE(l.updated_at, l.created_at) < DATE_SUB(NOW(), INTERVAL 5 MINUTE))";
        }
    }
    
    $whereClause = !empty($whereConditions) ? 'WHERE ' . implode(' AND ', $whereConditions) : '';
    
    // Consulta principal
    $sql = "SELECT l.*, d.name as desk_name, u.first_name as assigned_first_name, u.last_name as assigned_last_name 
            FROM leads l 
            LEFT JOIN desks d ON l.desk_id = d.id 
            LEFT JOIN users u ON l.assigned_to = u.id 
            $whereClause 
            ORDER BY l.created_at DESC 
            LIMIT $per_page OFFSET $offset";
    
    echo "<h3>3. Consulta SQL Generada</h3>";
    echo "<pre style='background: #f5f5f5; padding: 10px; border-radius: 5px;'>$sql</pre>";
    echo "<p><strong>Parámetros:</strong> [" . implode(', ', array_map(function($p) { return "'$p'"; }, $params)) . "]</p>";
    
    // Ejecutar consulta
    try {
        $stmt = $pdo->prepare($sql);
        $stmt->execute($params);
        $leads = $stmt->fetchAll();
        
        echo "<h3>4. Resultados de la Consulta</h3>";
        echo "<p><strong>Leads encontrados:</strong> " . count($leads) . "</p>";
        
        if ($leads) {
            echo "<table border='1' style='border-collapse: collapse; width: 100%; margin-top: 10px;'>";
            echo "<tr style='background-color: #f0f0f0;'><th>ID</th><th>Nombre</th><th>Email</th><th>Estado</th><th>Prioridad</th><th>Asignado a</th><th>Desk</th><th>País</th></tr>";
            foreach ($leads as $lead) {
                echo "<tr>";
                echo "<td>{$lead['id']}</td>";
                echo "<td>{$lead['first_name']} {$lead['last_name']}</td>";
                echo "<td>{$lead['email']}</td>";
                echo "<td>{$lead['status']}</td>";
                echo "<td>{$lead['priority']}</td>";
                echo "<td>" . ($lead['assigned_first_name'] ? $lead['assigned_first_name'] . ' ' . $lead['assigned_last_name'] : 'Sin asignar') . "</td>";
                echo "<td>" . ($lead['desk_name'] ?? 'Sin desk') . "</td>";
                echo "<td>" . ($lead['country'] ?? 'Sin país') . "</td>";
                echo "</tr>";
            }
            echo "</table>";
        } else {
            echo "<p style='color: red; font-weight: bold;'>❌ No se encontraron leads con los filtros aplicados</p>";
        }
        
        // Consulta de conteo total
        $countSql = "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 $whereClause";
        $countStmt = $pdo->prepare($countSql);
        $countStmt->execute($params);
        $totalLeads = $countStmt->fetchColumn();
        
        echo "<h3>5. Información de Paginación</h3>";
        echo "<p>Total de leads que coinciden con los filtros: <strong>$totalLeads</strong></p>";
        echo "<p>Página actual: $page</p>";
        echo "<p>Leads por página: $per_page</p>";
        echo "<p>Offset: $offset</p>";
        
        // Verificar leads sin filtros
        echo "<h3>6. Verificación Sin Filtros</h3>";
        $allLeadsQuery = "SELECT COUNT(*) FROM leads";
        $allLeadsCount = $pdo->query($allLeadsQuery)->fetchColumn();
        echo "<p>Total de leads en la base de datos (sin filtros): <strong>$allLeadsCount</strong></p>";
        
        if ($canViewAll) {
            $visibleLeadsQuery = "SELECT COUNT(*) FROM leads";
            $visibleLeadsCount = $pdo->query($visibleLeadsQuery)->fetchColumn();
        } else {
            $visibleLeadsQuery = "SELECT COUNT(*) FROM leads WHERE assigned_to = ? OR assigned_to IS NULL";
            $visibleStmt = $pdo->prepare($visibleLeadsQuery);
            $visibleStmt->execute([$current_user_id]);
            $visibleLeadsCount = $visibleStmt->fetchColumn();
        }
        echo "<p>Leads visibles para el usuario: <strong>$visibleLeadsCount</strong></p>";
        
    } catch (Exception $e) {
        echo "<p style='color: red;'>Error en la consulta: " . $e->getMessage() . "</p>";
    }
    
} else {
    echo "<p style='color: red;'>No hay usuario logueado</p>";
}

echo "<hr>";
echo "<p><a href='modules/leads/index.php' style='background-color: #007cba; color: white; padding: 10px 20px; text-decoration: none; border-radius: 5px;'>Ir al Listado de Leads</a></p>";
?>