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

echo "<h2>Test Lead Production - Sin Redirecciones</h2>";

// Incluir configuración
require_once 'database/config.php';
require_once 'database/connection.php';

// Obtener ID del lead
$lead_id = isset($_GET['id']) ? intval($_GET['id']) : null;

if (!$lead_id) {
    echo "<p><strong>Proporcione un ID de lead: ?id=NUMERO</strong></p>";
    
    // Mostrar leads disponibles
    try {
        $db = getDB();
        $pdo = $db->getConnection();
        
        $stmt = $pdo->query("SELECT id, first_name, last_name, email, phone FROM leads ORDER BY id DESC LIMIT 20");
        $leads = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        echo "<h3>Leads disponibles (últimos 20):</h3>";
        echo "<table border='1' style='border-collapse: collapse; width: 100%;'>";
        echo "<tr><th>ID</th><th>Nombre</th><th>Email</th><th>Teléfono</th><th>Acción</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['phone']}</td>";
            echo "<td><a href='?id={$lead['id']}' target='_blank'>Probar</a></td>";
            echo "</tr>";
        }
        echo "</table>";
        
    } catch (Exception $e) {
        echo "<p>Error: " . $e->getMessage() . "</p>";
    }
    
    exit;
}

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

try {
    $db = getDB();
    $pdo = $db->getConnection();
    
    echo "<h4>1. Consulta básica</h4>";
    $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</p>";
        echo "<pre>" . print_r($basic_lead, true) . "</pre>";
    } else {
        echo "<p>❌ Lead NO encontrado</p>";
        exit;
    }
    
    echo "<h4>2. Consulta con JOINs (como view.php)</h4>";
    $stmt = $pdo->prepare(
        "SELECT l.*, 
                l.job_title AS position,
                u.username AS assigned_user,
                CONCAT(u.first_name, ' ', u.last_name) AS assigned_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_with_joins = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if ($lead_with_joins) {
        echo "<p>✅ Consulta con JOINs exitosa</p>";
        echo "<pre>" . print_r($lead_with_joins, true) . "</pre>";
    } else {
        echo "<p>❌ Consulta con JOINs falló</p>";
    }
    
    echo "<h4>3. Simulación exacta de view.php</h4>";
    
    $lead = null;
    
    // Intentar consulta principal
    try {
        $stmt = $pdo->prepare(
            "SELECT l.*, 
                    l.job_title AS position,
                    u.username AS assigned_user,
                    CONCAT(u.first_name, ' ', u.last_name) AS assigned_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 no devolvió resultados, probando fallback...</p>";
            
            // Fallback
            $stmt = $pdo->prepare("SELECT * FROM leads WHERE id = ? LIMIT 1");
            $stmt->execute([$lead_id]);
            $basic_lead = $stmt->fetch(PDO::FETCH_ASSOC);
            
            if ($basic_lead) {
                echo "<p>✅ Fallback exitoso</p>";
                $lead = $basic_lead;
                
                // Agregar datos de usuario
                if ($lead['assigned_to']) {
                    try {
                        $user_stmt = $pdo->prepare("SELECT username, CONCAT(first_name, ' ', last_name) AS full_name FROM users WHERE id = ?");
                        $user_stmt->execute([$lead['assigned_to']]);
                        $user = $user_stmt->fetch(PDO::FETCH_ASSOC);
                        if ($user) {
                            $lead['assigned_user'] = $user['username'];
                            $lead['assigned_name'] = $user['full_name'];
                        }
                    } catch (Exception $e) {
                        echo "<p>⚠️ Error obteniendo usuario: " . $e->getMessage() . "</p>";
                    }
                }
                
                // Agregar datos de desk
                if ($lead['desk_id']) {
                    try {
                        $desk_stmt = $pdo->prepare("SELECT name, color FROM desks WHERE id = ?");
                        $desk_stmt->execute([$lead['desk_id']]);
                        $desk = $desk_stmt->fetch(PDO::FETCH_ASSOC);
                        if ($desk) {
                            $lead['desk_name'] = $desk['name'];
                            $lead['desk_color'] = $desk['color'];
                        }
                    } catch (Exception $e) {
                        echo "<p>⚠️ Error obteniendo desk: " . $e->getMessage() . "</p>";
                    }
                }
                
                if (!isset($lead['position'])) {
                    $lead['position'] = $lead['job_title'] ?? null;
                }
            } else {
                echo "<p>❌ Fallback también falló</p>";
            }
        } else {
            echo "<p>✅ Consulta principal exitosa</p>";
        }
        
    } catch (Throwable $e) {
        echo "<p>❌ Error en simulación: " . $e->getMessage() . "</p>";
        echo "<pre>" . $e->getTraceAsString() . "</pre>";
        $lead = false;
    }
    
    echo "<h4>4. Resultado Final</h4>";
    if ($lead) {
        echo "<p>✅ Lead procesado correctamente</p>";
        echo "<h5>Datos del lead:</h5>";
        echo "<ul>";
        echo "<li><strong>ID:</strong> " . ($lead['id'] ?? 'N/A') . "</li>";
        echo "<li><strong>Nombre:</strong> " . ($lead['first_name'] ?? '') . " " . ($lead['last_name'] ?? '') . "</li>";
        echo "<li><strong>Email:</strong> " . ($lead['email'] ?? 'N/A') . "</li>";
        echo "<li><strong>Teléfono:</strong> " . ($lead['phone'] ?? 'N/A') . "</li>";
        echo "<li><strong>Asignado a:</strong> " . ($lead['assigned_name'] ?? 'Sin asignar') . "</li>";
        echo "<li><strong>Desk:</strong> " . ($lead['desk_name'] ?? 'Sin desk') . "</li>";
        echo "<li><strong>Estado:</strong> " . ($lead['status'] ?? 'N/A') . "</li>";
        echo "</ul>";
        
        echo "<h5>¿Por qué view.php dice 'no encontrado'?</h5>";
        echo "<p>El lead SÍ existe y se puede obtener. El problema puede ser:</p>";
        echo "<ul>";
        echo "<li>Problema de sesión/autenticación</li>";
        echo "<li>Problema con la función getDB()</li>";
        echo "<li>Diferencia en la configuración de base de datos</li>";
        echo "<li>Error en el manejo de excepciones</li>";
        echo "</ul>";
        
        // Probar URL directa
        echo "<h5>Probar URL directa:</h5>";
        $direct_url = "https://spin2pay.com/test/simple_crm/index.php?module=leads&action=view&id=$lead_id";
        echo "<p><a href='$direct_url' target='_blank'>$direct_url</a></p>";
        
    } else {
        echo "<p>❌ No se pudo procesar el lead</p>";
    }
    
} catch (Exception $e) {
    echo "<p>❌ Error general: " . $e->getMessage() . "</p>";
    echo "<pre>" . $e->getTraceAsString() . "</pre>";
}

echo "<h4>5. Información del sistema</h4>";
echo "<ul>";
echo "<li><strong>Servidor:</strong> " . $_SERVER['SERVER_NAME'] . "</li>";
echo "<li><strong>PHP Version:</strong> " . PHP_VERSION . "</li>";
echo "<li><strong>Script:</strong> " . $_SERVER['SCRIPT_NAME'] . "</li>";
echo "</ul>";

?>