<?php
/**
 * Script de depuración para verificar leads en la base de datos
 */

session_start();
require_once 'database/config.php';
require_once 'database/connection.php';

echo "<h2>🔍 Depuración de Leads</h2>";

// Verificar sesión
echo "<h3>1. Información de Sesión</h3>";
echo "<pre>";
echo "Usuario ID: " . ($_SESSION['user_id'] ?? 'No definido') . "\n";
echo "Usuario: " . ($_SESSION['username'] ?? 'No definido') . "\n";
echo "Sesión activa: " . (isset($_SESSION['user_id']) ? 'Sí' : 'No') . "\n";
echo "</pre>";

try {
    $db = getDB();
    $pdo = $db->getConnection();
    
    // Verificar conexión a la base de datos
    echo "<h3>2. Conexión a Base de Datos</h3>";
    echo "<pre>✅ Conexión exitosa</pre>";
    
    // Contar total de leads
    echo "<h3>3. Total de Leads en la Base de Datos</h3>";
    $total_leads = $db->count("SELECT COUNT(*) FROM leads");
    echo "<pre>Total de leads: $total_leads</pre>";
    
    // Mostrar algunos leads de ejemplo
    echo "<h3>4. Primeros 5 Leads</h3>";
    $sample_leads = $db->select("SELECT id, first_name, last_name, email, status, assigned_to FROM leads LIMIT 5");
    echo "<pre>";
    foreach ($sample_leads as $lead) {
        echo "ID: {$lead['id']}, Nombre: {$lead['first_name']} {$lead['last_name']}, Email: {$lead['email']}, Estado: {$lead['status']}, Asignado a: {$lead['assigned_to']}\n";
    }
    echo "</pre>";
    
    // Verificar permisos del usuario actual
    echo "<h3>5. Verificación de Permisos</h3>";
    $current_user_id = $_SESSION['user_id'] ?? 0;
    
    if ($current_user_id > 0) {
        // Función de permisos
        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();
        }
        
        $can_view_all = userHasPermissionByName($pdo, 'leads.view_all', $current_user_id);
        echo "<pre>";
        echo "Usuario ID: $current_user_id\n";
        echo "Permiso 'leads.view_all': " . ($can_view_all ? 'Sí' : 'No') . "\n";
        echo "</pre>";
        
        // Leads asignados al usuario actual
        echo "<h3>6. Leads Asignados al Usuario Actual</h3>";
        $assigned_leads = $db->select("SELECT id, first_name, last_name, email, status FROM leads WHERE assigned_to = ?", [$current_user_id]);
        echo "<pre>";
        echo "Leads asignados: " . count($assigned_leads) . "\n";
        foreach ($assigned_leads as $lead) {
            echo "ID: {$lead['id']}, Nombre: {$lead['first_name']} {$lead['last_name']}, Email: {$lead['email']}, Estado: {$lead['status']}\n";
        }
        echo "</pre>";
        
        // Leads sin asignar
        echo "<h3>7. Leads Sin Asignar</h3>";
        $unassigned_leads = $db->select("SELECT id, first_name, last_name, email, status FROM leads WHERE assigned_to IS NULL LIMIT 5");
        echo "<pre>";
        echo "Leads sin asignar: " . count($unassigned_leads) . "\n";
        foreach ($unassigned_leads as $lead) {
            echo "ID: {$lead['id']}, Nombre: {$lead['first_name']} {$lead['last_name']}, Email: {$lead['email']}, Estado: {$lead['status']}\n";
        }
        echo "</pre>";
        
        // Simular la consulta del index.php
        echo "<h3>8. Simulación de Consulta del Index.php</h3>";
        
        $where_conditions = [];
        $params = [];
        
        // Aplicar restricción de permisos como en index.php
        if (!$can_view_all) {
            $where_conditions[] = "(l.assigned_to = ? OR l.assigned_to IS NULL)";
            $params[] = $current_user_id;
        }
        
        $where_clause = !empty($where_conditions) ? 'WHERE ' . implode(' AND ', $where_conditions) : '';
        
        $query = "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 l.last_seen IS NOT NULL AND TIMESTAMPDIFF(MINUTE, l.last_seen, NOW()) <= 5 THEN 1 
                ELSE 0 
            END AS is_online
         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
         ORDER BY l.created_at DESC
         LIMIT 10";
        
        echo "<pre>";
        echo "Consulta SQL:\n$query\n\n";
        echo "Parámetros: " . json_encode($params) . "\n\n";
        
        $filtered_leads = $db->select($query, $params);
        echo "Resultados encontrados: " . count($filtered_leads) . "\n";
        
        foreach ($filtered_leads as $lead) {
            echo "ID: {$lead['id']}, Nombre: {$lead['first_name']} {$lead['last_name']}, Email: {$lead['email']}, Estado: {$lead['status']}, Asignado: {$lead['assigned_to']}\n";
        }
        echo "</pre>";
        
    } else {
        echo "<pre>❌ No hay usuario logueado</pre>";
    }
    
} catch (Exception $e) {
    echo "<h3>❌ Error</h3>";
    echo "<pre>" . htmlspecialchars($e->getMessage()) . "</pre>";
}

echo "<hr>";
echo "<p><a href='modules/leads/index.php'>← Volver al listado de leads</a></p>";
?>