<?php
// Script de diagnóstico completo para el sistema de agregar notas

require_once 'database/config.php';
require_once 'database/connection.php';
// No requerir auth para este diagnóstico

// Iniciar sesión si no está activa
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// Simular usuario autenticado para pruebas
if (!isset($_SESSION['user_id'])) {
    $_SESSION['user_id'] = 1;
    $_SESSION['user_name'] = 'Admin User';
    $_SESSION['user_role'] = 'admin';
}

?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>🔍 Diagnóstico - Sistema de Notas</title>
    <style>
        body { font-family: Arial, sans-serif; margin: 20px; background: #f5f5f5; }
        .container { max-width: 1200px; margin: 0 auto; background: white; padding: 20px; border-radius: 10px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); }
        .section { margin: 20px 0; padding: 15px; border-left: 4px solid #007bff; background: #f8f9fa; }
        .success { border-left-color: #28a745; background: #d4edda; }
        .error { border-left-color: #dc3545; background: #f8d7da; }
        .warning { border-left-color: #ffc107; background: #fff3cd; }
        .test-result { margin: 10px 0; padding: 10px; border-radius: 5px; }
        .code { background: #f4f4f4; padding: 10px; border-radius: 5px; font-family: monospace; margin: 10px 0; }
        .btn { padding: 10px 20px; margin: 5px; border: none; border-radius: 5px; cursor: pointer; color: white; }
        .btn-primary { background: #007bff; }
        .btn-success { background: #28a745; }
        .btn-danger { background: #dc3545; }
        .iframe-container { margin: 20px 0; border: 1px solid #ddd; border-radius: 5px; overflow: hidden; }
        iframe { width: 100%; height: 400px; border: none; }
    </style>
</head>
<body>
    <div class="container">
        <h1>🔍 Diagnóstico del Sistema de Notas</h1>
        <p><strong>Fecha:</strong> <?php echo date('Y-m-d H:i:s'); ?></p>
        
        <?php
        
        // 1. Verificar conexión a base de datos
echo "<div class='section'>";
echo "<h2>1️⃣ Conexión a Base de Datos</h2>";
try {
    $db = Database::getInstance();
    $conn = $db->getConnection();
    echo "<div class='test-result success'>✅ Conexión exitosa</div>";
    
    // Verificar tabla lead_activities
    $result = $conn->query("SELECT COUNT(*) as total FROM lead_activities");
    $count = $result->fetch(PDO::FETCH_ASSOC);
    echo "<div class='test-result success'>✅ Tabla lead_activities tiene {$count['total']} registros</div>";
    
} catch (Exception $e) {
    echo "<div class='test-result error'>❌ Error: " . $e->getMessage() . "</div>";
}
echo "</div>";
        
        // 2. Verificar archivos necesarios
        echo "<div class='section'>";
        echo "<h2>2️⃣ Archivos del Sistema</h2>";
        
        $files = [
            'modules/leads/add_note.php',
            'modules/leads/view_scripts.js',
            'modules/leads/view_content.php',
            'error_logger.js'
        ];
        
        foreach ($files as $file) {
            if (file_exists($file)) {
                echo "<div class='test-result success'>✅ $file existe</div>";
            } else {
                echo "<div class='test-result error'>❌ $file no existe</div>";
            }
        }
        echo "</div>";
        
        // 3. Verificar JavaScript
        echo "<div class='section'>";
        echo "<h2>3️⃣ JavaScript Configuration</h2>";
        
        $jsContent = file_get_contents('modules/leads/view_scripts.js');
        $checks = [
            'saveComment function' => strpos($jsContent, 'function saveComment') !== false,
            'window.leadData usage' => strpos($jsContent, 'window.leadData.id') !== false,
            'Correct endpoint path' => strpos($jsContent, 'modules/leads/add_note.php') !== false,
            'JSON content type' => strpos($jsContent, 'application/json') !== false
        ];
        
        foreach ($checks as $check => $result) {
            if ($result) {
                echo "<div class='test-result success'>✅ $check encontrado</div>";
            } else {
                echo "<div class='test-result error'>❌ $check no encontrado</div>";
            }
        }
        echo "</div>";
        
        // 4. Verificar lead de prueba
        echo "<div class='section'>";
        echo "<h2>4️⃣ Lead de Prueba (ID: 3)</h2>";
        
        try {
            $lead = $db->selectOne("SELECT * FROM leads WHERE id = ?", [3]);
            if ($lead) {
                echo "<div class='test-result success'>✅ Lead ID 3 encontrado</div>";
                echo "<div class='code'>";
                echo "Nombre: " . ($lead['first_name'] . ' ' . $lead['last_name']) . "<br>";
                echo "Email: " . $lead['email'] . "<br>";
                echo "Estado: " . $lead['status'] . "<br>";
                echo "</div>";
            } else {
                echo "<div class='test-result warning'>⚠️ Lead ID 3 no encontrado</div>";
            }
        } catch (Exception $e) {
            echo "<div class='test-result error'>❌ Error: " . $e->getMessage() . "</div>";
        }
        echo "</div>";
        
        // 5. Verificar actividades recientes
        echo "<div class='section'>";
        echo "<h2>5️⃣ Actividades Recientes del Lead 3</h2>";
        
        try {
            $activities = $db->select("
                SELECT la.*, u.username 
                FROM lead_activities la 
                LEFT JOIN users u ON la.created_by = u.id 
                WHERE la.lead_id = ? 
                ORDER BY la.created_at DESC 
                LIMIT 5
            ", [3]);
            
            if ($activities) {
                echo "<div class='test-result success'>✅ Encontradas " . count($activities) . " actividades</div>";
                echo "<table border='1' style='width: 100%; border-collapse: collapse;'>";
                echo "<tr style='background: #f8f9fa;'><th>ID</th><th>Tipo</th><th>Asunto</th><th>Fecha</th><th>Usuario</th></tr>";
                foreach ($activities as $activity) {
                    echo "<tr>";
                    echo "<td>" . $activity['id'] . "</td>";
                    echo "<td>" . $activity['type'] . "</td>";
                    echo "<td>" . htmlspecialchars($activity['subject']) . "</td>";
                    echo "<td>" . date('Y-m-d H:i', strtotime($activity['created_at'])) . "</td>";
                    echo "<td>" . ($activity['username'] ?? 'N/A') . "</td>";
                    echo "</tr>";
                }
                echo "</table>";
            } else {
                echo "<div class='test-result warning'>⚠️ No hay actividades para este lead</div>";
            }
        } catch (Exception $e) {
            echo "<div class='test-result error'>❌ Error: " . $e->getMessage() . "</div>";
        }
        echo "</div>";
        
        ?>
        
        <!-- 6. Pruebas manuales -->
        <div class='section'>
            <h2>6️⃣ Pruebas Manuales</h2>
            
            <div style='display: flex; gap: 10px; margin: 20px 0;'>
                <button class='btn btn-primary' onclick="window.open('test_javascript_leadid.html', '_blank')">
                    🧪 Probar JavaScript
                </button>
                <button class='btn btn-success' onclick="window.open('test_add_note.php', '_blank')">
                    📝 Probar Backend
                </button>
                <button class='btn btn-primary' onclick="window.open('index.php?module=leads&action=view&id=3', '_blank')">
                    👁️ Ver Lead
                </button>
                <button class='btn btn-danger' onclick="window.open('debug_activities.php', '_blank')">
                    📊 Ver Actividades
                </button>
            </div>
        </div>
        
        <!-- 7. Instrucciones para probar -->
        <div class='section'>
            <h2>7️⃣ Cómo Probar el Sistema</h2>
            <ol>
                <li><strong>Abrir el Lead:</strong> Haz clic en "Ver Lead" arriba</li>
                <li><strong>Buscar el botón:</strong> Busca el botón "Agregar Notas" en la página del lead</li>
                <li><strong>Seleccionar tipo:</strong> Elige entre llamada, email, reunión o nota</li>
                <li><strong>Completar formulario:</strong> Llena el asunto y descripción</li>
                <li><strong>Guardar:</strong> Haz clic en "Guardar Comentario"</li>
                <li><strong>Verificar:</strong> La actividad debe aparecer en la tabla de actividades</li>
            </ol>
        </div>
        
        <!-- 8. Iframe para verificar -->
        <div class='section'>
            <h2>8️⃣ Vista Previa del Lead</h2>
            <div class='iframe-container'>
                <iframe src="index.php?module=leads&action=view&id=3"></iframe>
            </div>
        </div>
        
        <div style='text-align: center; margin-top: 30px; padding: 20px; background: #e8f5e8; border-radius: 10px;'>
            <h3>✅ Estado del Sistema</h3>
            <p><strong>Backend:</strong> Funcionando</p>
            <p><strong>JavaScript:</strong> Configurado</p>
            <p><strong>Base de datos:</strong> Conectada</p>
            <p><strong>Endpoint:</strong> Disponible</p>
        </div>
    </div>
</body>
</html>