<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

echo "<h2>Debug View.php en Producción</h2>";

// Incluir configuración de base de datos
require_once 'database/connection.php';

// Simular parámetros GET como lo haría view.php
$lead_id = isset($_GET['id']) ? (int)$_GET['id'] : null;

if (!$lead_id) {
    echo "<p><strong>No se proporcionó ID del lead. Agregue ?id=NUMERO_LEAD a la URL</strong></p>";
    
    // Mostrar algunos leads disponibles
    try {
        $stmt = $pdo->query("SELECT id, first_name, last_name FROM leads ORDER BY id DESC LIMIT 10");
        $leads = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        echo "<h3>Leads disponibles para probar:</h3>";
        echo "<ul>";
        foreach ($leads as $lead) {
            echo "<li><a href='?id={$lead['id']}'>Lead {$lead['id']}: {$lead['first_name']} {$lead['last_name']}</a></li>";
        }
        echo "</ul>";
    } catch (Exception $e) {
        echo "<p>Error obteniendo leads: " . $e->getMessage() . "</p>";
    }
    
    exit;
}

echo "<h3>Debuggeando Lead ID: $lead_id</h3>";

// 1. Verificar si el lead existe con consulta simple
echo "<h4>1. Verificación básica del lead</h4>";
try {
    $stmt = $pdo->prepare("SELECT * FROM leads WHERE id = ?");
    $stmt->execute([$lead_id]);
    $basic_lead = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if ($basic_lead) {
        echo "<p>✅ Lead encontrado con consulta básica</p>";
        echo "<pre>" . print_r($basic_lead, true) . "</pre>";
    } else {
        echo "<p>❌ Lead NO encontrado con consulta básica</p>";
        exit;
    }
} catch (Exception $e) {
    echo "<p>❌ Error en consulta básica: " . $e->getMessage() . "</p>";
    exit;
}

// 2. Probar la consulta exacta de view.php (con LEFT JOINs)
echo "<h4>2. Consulta con LEFT JOINs (como en view.php)</h4>";
try {
    $query = "SELECT l.*, 
                     u.username as assigned_name, 
                     u.first_name as assigned_first_name, 
                     u.last_name as assigned_last_name,
                     d.name as desk_name, 
                     d.color as desk_color
              FROM leads l 
              LEFT JOIN users u ON l.assigned_to = u.id 
              LEFT JOIN desks d ON l.desk_id = d.id 
              WHERE l.id = ?";
    
    echo "<p><strong>Consulta SQL:</strong></p>";
    echo "<pre>$query</pre>";
    
    $stmt = $pdo->prepare($query);
    $stmt->execute([$lead_id]);
    $lead_with_joins = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if ($lead_with_joins) {
        echo "<p>✅ Lead encontrado con LEFT JOINs</p>";
        echo "<pre>" . print_r($lead_with_joins, true) . "</pre>";
    } else {
        echo "<p>❌ Lead NO encontrado con LEFT JOINs</p>";
        
        // Verificar si hay problema con las tablas relacionadas
        echo "<h5>Verificando tablas relacionadas:</h5>";
        
        // Verificar tabla users
        if ($basic_lead['assigned_to']) {
            $stmt = $pdo->prepare("SELECT * FROM users WHERE id = ?");
            $stmt->execute([$basic_lead['assigned_to']]);
            $user = $stmt->fetch(PDO::FETCH_ASSOC);
            echo "<p>Usuario asignado (ID {$basic_lead['assigned_to']}): " . ($user ? "✅ Encontrado" : "❌ No encontrado") . "</p>";
        }
        
        // Verificar tabla desks
        if ($basic_lead['desk_id']) {
            $stmt = $pdo->prepare("SELECT * FROM desks WHERE id = ?");
            $stmt->execute([$basic_lead['desk_id']]);
            $desk = $stmt->fetch(PDO::FETCH_ASSOC);
            echo "<p>Desk asignado (ID {$basic_lead['desk_id']}): " . ($desk ? "✅ Encontrado" : "❌ No encontrado") . "</p>";
        }
    }
} catch (Exception $e) {
    echo "<p>❌ Error en consulta con JOINs: " . $e->getMessage() . "</p>";
    echo "<p><strong>Detalles del error:</strong></p>";
    echo "<pre>" . print_r($e, true) . "</pre>";
}

// 3. Simular exactamente lo que hace view.php
echo "<h4>3. Simulación exacta de view.php</h4>";

$lead = null;

try {
    // Intentar la consulta principal (como en view.php)
    $stmt = $pdo->prepare("SELECT l.*, 
                                 u.username as assigned_name, 
                                 u.first_name as assigned_first_name, 
                                 u.last_name as assigned_last_name,
                                 d.name as desk_name, 
                                 d.color as desk_color
                          FROM leads l 
                          LEFT JOIN users u ON l.assigned_to = u.id 
                          LEFT JOIN desks d ON l.desk_id = d.id 
                          WHERE l.id = ?");
    $stmt->execute([$lead_id]);
    $lead = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$lead) {
        echo "<p>⚠️ Consulta principal falló, ejecutando fallback...</p>";
        
        // Fallback mejorado (como modificamos en view.php)
        $stmt = $pdo->prepare("SELECT * FROM leads WHERE id = ?");
        $stmt->execute([$lead_id]);
        $lead = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if ($lead) {
            echo "<p>✅ Lead encontrado con fallback</p>";
            
            // Obtener datos del usuario asignado
            if ($lead['assigned_to']) {
                $stmt = $pdo->prepare("SELECT username, first_name, last_name FROM users WHERE id = ?");
                $stmt->execute([$lead['assigned_to']]);
                $user = $stmt->fetch(PDO::FETCH_ASSOC);
                if ($user) {
                    $lead['assigned_name'] = $user['username'];
                    $lead['assigned_first_name'] = $user['first_name'];
                    $lead['assigned_last_name'] = $user['last_name'];
                }
            }
            
            // Obtener datos del desk
            if ($lead['desk_id']) {
                $stmt = $pdo->prepare("SELECT name, color FROM desks WHERE id = ?");
                $stmt->execute([$lead['desk_id']]);
                $desk = $stmt->fetch(PDO::FETCH_ASSOC);
                if ($desk) {
                    $lead['desk_name'] = $desk['name'];
                    $lead['desk_color'] = $desk['color'];
                }
            }
        } else {
            echo "<p>❌ Lead NO encontrado ni siquiera con fallback</p>";
        }
    } else {
        echo "<p>✅ Lead encontrado con consulta principal</p>";
    }
    
} catch (Exception $e) {
    echo "<p>❌ Error en simulación: " . $e->getMessage() . "</p>";
    echo "<p><strong>Stack trace:</strong></p>";
    echo "<pre>" . $e->getTraceAsString() . "</pre>";
}

// 4. Mostrar resultado final
if ($lead) {
    echo "<h4>4. Resultado Final</h4>";
    echo "<p>✅ Lead procesado correctamente</p>";
    echo "<pre>" . print_r($lead, true) . "</pre>";
    
    // Verificar campos críticos
    echo "<h5>Campos críticos:</h5>";
    echo "<ul>";
    echo "<li>ID: " . ($lead['id'] ?? 'No definido') . "</li>";
    echo "<li>Nombre: " . ($lead['first_name'] ?? 'No definido') . " " . ($lead['last_name'] ?? 'No definido') . "</li>";
    echo "<li>Asignado a: " . ($lead['assigned_name'] ?? 'Sin asignar') . "</li>";
    echo "<li>Desk: " . ($lead['desk_name'] ?? 'Sin desk') . "</li>";
    echo "</ul>";
} else {
    echo "<h4>4. Resultado Final</h4>";
    echo "<p>❌ No se pudo obtener el lead</p>";
}

// 5. Información de configuración
echo "<h4>5. Información de Configuración</h4>";
echo "<ul>";
echo "<li>Servidor: " . $_SERVER['SERVER_NAME'] . "</li>";
echo "<li>Script: " . $_SERVER['SCRIPT_NAME'] . "</li>";
echo "<li>Base de datos: " . (defined('DB_NAME') ? DB_NAME : 'No definida') . "</li>";
echo "<li>Host DB: " . (defined('DB_HOST') ? DB_HOST : 'No definido') . "</li>";
echo "</ul>";

?>