<?php
session_start();
require_once 'config/database.php';
require_once 'includes/functions.php';

// Verificar sesión
if (!isset($_SESSION['user_id'])) {
    die('No hay sesión activa');
}

$current_user_id = $_SESSION['user_id'];

echo "<h1>Debug de Filtros de Leads</h1>";

// Mostrar todos los parámetros GET
echo "<h2>Parámetros GET actuales:</h2>";
echo "<pre>";
print_r($_GET);
echo "</pre>";

// Mostrar todos los parámetros POST
echo "<h2>Parámetros POST actuales:</h2>";
echo "<pre>";
print_r($_POST);
echo "</pre>";

// Simular exactamente la lógica de filtros del 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'] ?? '';

echo "<h2>Filtros extraídos:</h2>";
echo "Search: '$search'<br>";
echo "Priority: '$priority_filter'<br>";
echo "Desk: '$desk_filter'<br>";
echo "Assigned: '$assigned_filter'<br>";
echo "Country: '$country_filter'<br>";
echo "Online: '$online_filter'<br>";

// Construir WHERE conditions exactamente como en index.php
$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 ?)";
    $search_param = '%' . $search . '%';
    $params[] = $search_param;
    $params[] = $search_param;
    $params[] = $search_param;
    $params[] = $search_param;
}

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

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

if (!empty($assigned_filter)) {
    if ($assigned_filter === 'unassigned') {
        $where_conditions[] = "l.assigned_to IS NULL";
    } else {
        $where_conditions[] = "l.assigned_to = ?";
        $params[] = $assigned_filter;
    }
}

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

if (!empty($online_filter)) {
    if ($online_filter === 'online') {
        $where_conditions[] = "l.is_online = 1";
    } elseif ($online_filter === 'offline') {
        $where_conditions[] = "(l.is_online = 0 OR l.is_online IS NULL)";
    }
}

// Verificar permisos
$hasViewAll = userHasPermissionByName($pdo, 'leads.view_all', $current_user_id);
echo "<h2>Permisos:</h2>";
echo "Usuario tiene 'leads.view_all': " . ($hasViewAll ? 'SÍ' : 'NO') . "<br>";

// Agregar restricción de permisos
if (!$hasViewAll) {
    $where_conditions[] = "(l.assigned_to = ? OR l.assigned_to IS NULL)";
    $params[] = $current_user_id;
    echo "Se agregó restricción de permisos para usuario ID: $current_user_id<br>";
}

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

echo "<h2>Consulta SQL construida:</h2>";
$query = "SELECT l.*, 
    CONCAT(u.first_name, ' ', u.last_name) as assigned_user_name,
    d.name as desk_name
FROM leads l
LEFT JOIN users u ON l.assigned_to = u.id
LEFT JOIN desks d ON l.desk_id = d.id
$where_clause
ORDER BY l.updated_at DESC";

echo "<pre>$query</pre>";

echo "<h2>Parámetros:</h2>";
echo "<pre>";
print_r($params);
echo "</pre>";

// Ejecutar la consulta
try {
    $stmt = $pdo->prepare($query);
    $stmt->execute($params);
    $leads = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    echo "<h2>Resultados encontrados: " . count($leads) . "</h2>";
    
    if (count($leads) > 0) {
        echo "<table border='1' style='border-collapse: collapse; width: 100%;'>";
        echo "<tr><th>ID</th><th>Nombre</th><th>Email</th><th>Asignado a</th><th>Desk</th><th>País</th><th>Online</th></tr>";
        foreach ($leads as $lead) {
            echo "<tr>";
            echo "<td>" . $lead['id'] . "</td>";
            echo "<td>" . htmlspecialchars($lead['first_name'] . ' ' . $lead['last_name']) . "</td>";
            echo "<td>" . htmlspecialchars($lead['email']) . "</td>";
            echo "<td>" . htmlspecialchars($lead['assigned_user_name'] ?? 'Sin asignar') . "</td>";
            echo "<td>" . htmlspecialchars($lead['desk_name'] ?? '') . "</td>";
            echo "<td>" . htmlspecialchars($lead['country'] ?? '') . "</td>";
            echo "<td>" . ($lead['is_online'] ? 'Online' : 'Offline') . "</td>";
            echo "</tr>";
        }
        echo "</table>";
    } else {
        echo "<p><strong>No se encontraron leads con los filtros actuales.</strong></p>";
    }
    
} catch (Exception $e) {
    echo "<h2>Error en la consulta:</h2>";
    echo "<pre>" . $e->getMessage() . "</pre>";
}

// Verificar leads sin filtros
echo "<h2>Verificación: Leads totales sin filtros</h2>";
try {
    $stmt = $pdo->prepare("SELECT COUNT(*) as total FROM leads");
    $stmt->execute();
    $total = $stmt->fetch(PDO::FETCH_ASSOC);
    echo "Total de leads en la base de datos: " . $total['total'] . "<br>";
    
    // Verificar leads que puede ver el usuario actual
    if (!$hasViewAll) {
        $stmt = $pdo->prepare("SELECT COUNT(*) as total FROM leads WHERE assigned_to = ? OR assigned_to IS NULL");
        $stmt->execute([$current_user_id]);
        $user_total = $stmt->fetch(PDO::FETCH_ASSOC);
        echo "Leads que puede ver el usuario actual (asignados + sin asignar): " . $user_total['total'] . "<br>";
    }
    
} catch (Exception $e) {
    echo "Error verificando totales: " . $e->getMessage();
}
?>