<?php
require_once 'database/connection.php';

echo "<h2>Test Final - Lead 10292</h2>";

// Simular exactamente lo que hace view.php
$lead_id = 10292;
$pdo_local = $db->getConnection();
$lead = null;

try {
    $stmt = $pdo_local->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);
    
    echo "<h3>Resultado de la consulta principal:</h3>";
    if ($lead) {
        echo "✅ Consulta principal exitosa<br>";
        echo "<strong>assigned_name:</strong> " . ($lead['assigned_name'] ?? 'NULL') . "<br>";
        echo "<strong>assigned_user:</strong> " . ($lead['assigned_user'] ?? 'NULL') . "<br>";
        echo "<strong>desk_name:</strong> " . ($lead['desk_name'] ?? 'NULL') . "<br>";
        echo "<strong>desk_color:</strong> " . ($lead['desk_color'] ?? 'NULL') . "<br>";
    } else {
        echo "❌ Consulta principal no devolvió resultados, ejecutando fallback...<br>";
        
        // Ejecutar el fallback mejorado
        $stmt = $pdo_local->prepare("SELECT * FROM leads WHERE id = ? LIMIT 1");
        $stmt->execute([$lead_id]);
        $basic_lead = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if ($basic_lead) {
            echo "✅ Consulta básica exitosa<br>";
            $lead = $basic_lead;
            
            // Obtener datos del usuario asignado
            if ($lead['assigned_to']) {
                try {
                    $user_stmt = $pdo_local->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'];
                        echo "✅ Usuario asignado obtenido: " . $user['full_name'] . "<br>";
                    } else {
                        echo "❌ Usuario no encontrado para ID: " . $lead['assigned_to'] . "<br>";
                    }
                } catch (Exception $e) {
                    echo "❌ Error obteniendo usuario: " . $e->getMessage() . "<br>";
                    $lead['assigned_user'] = null;
                    $lead['assigned_name'] = null;
                }
            } else {
                echo "ℹ️ Lead no tiene assigned_to<br>";
            }
            
            // Obtener datos del desk
            if ($lead['desk_id']) {
                try {
                    $desk_stmt = $pdo_local->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'];
                        echo "✅ Desk obtenido: " . $desk['name'] . "<br>";
                    } else {
                        echo "❌ Desk no encontrado para ID: " . $lead['desk_id'] . "<br>";
                    }
                } catch (Exception $e) {
                    echo "❌ Error obteniendo desk: " . $e->getMessage() . "<br>";
                    $lead['desk_name'] = null;
                    $lead['desk_color'] = null;
                }
            } else {
                echo "ℹ️ Lead no tiene desk_id<br>";
            }
        } else {
            echo "❌ No se encontró el lead<br>";
        }
    }
    
} catch (Throwable $e) {
    echo "❌ Error en consulta: " . $e->getMessage() . "<br>";
    $lead = false;
}

echo "<h3>Datos finales del lead:</h3>";
if ($lead) {
    echo "<pre>";
    print_r([
        'id' => $lead['id'],
        'first_name' => $lead['first_name'],
        'last_name' => $lead['last_name'],
        'assigned_to' => $lead['assigned_to'],
        'assigned_name' => $lead['assigned_name'] ?? 'NULL',
        'assigned_user' => $lead['assigned_user'] ?? 'NULL',
        'desk_id' => $lead['desk_id'],
        'desk_name' => $lead['desk_name'] ?? 'NULL',
        'desk_color' => $lead['desk_color'] ?? 'NULL',
        'status' => $lead['status']
    ]);
    echo "</pre>";
    
    // Verificar qué se mostraría en view_content.php
    echo "<h3>Lo que se mostraría en el perfil:</h3>";
    echo "<strong>Asignado a:</strong> " . htmlspecialchars($lead['assigned_name'] ?? $lead['assigned_user'] ?? 'Sin asignar') . "<br>";
    echo "<strong>Desk:</strong> " . htmlspecialchars($lead['desk_name'] ?? 'Sin desk') . "<br>";
    
    // Verificar status según desk
    $desk_id = intval($lead['desk_id'] ?? 0);
    if ($desk_id > 0) {
        $allowed_statuses = $db->select("SELECT status FROM desk_allowed_statuses WHERE desk_id = ? ORDER BY position ASC, status ASC", [$desk_id]);
        if ($allowed_statuses) {
            echo "<strong>Status permitidos para este desk:</strong><br>";
            foreach ($allowed_statuses as $status) {
                echo "- " . $status['status'] . "<br>";
            }
        } else {
            echo "<strong>No hay status específicos para este desk, usando defaults</strong><br>";
        }
    } else {
        echo "<strong>Sin desk asignado, usando status defaults</strong><br>";
    }
} else {
    echo "❌ No se pudieron obtener los datos del lead<br>";
}
?>