<?php
session_start();
require_once 'config/database.php';
require_once 'includes/functions.php';

// Verificar sesión
if (!isset($_SESSION['user_id'])) {
    die('No hay sesión activa');
}

$current_user_id = $_SESSION['user_id'];
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Debug JavaScript - Leads</title>
    <style>
        body { font-family: Arial, sans-serif; margin: 20px; }
        .debug-section { margin: 20px 0; padding: 15px; border: 1px solid #ddd; border-radius: 5px; }
        .error { color: red; font-weight: bold; }
        .success { color: green; font-weight: bold; }
        .info { color: blue; }
        pre { background: #f5f5f5; padding: 10px; border-radius: 3px; overflow-x: auto; }
        .test-table { width: 100%; border-collapse: collapse; margin: 10px 0; }
        .test-table th, .test-table td { border: 1px solid #ddd; padding: 8px; text-align: left; }
        .test-table th { background-color: #f2f2f2; }
    </style>
</head>
<body>
    <h1>Debug JavaScript - Tabla de Leads</h1>
    
    <div class="debug-section">
        <h2>1. Verificación de Archivos JavaScript</h2>
        <?php
        $jsFiles = [
            'public/script.js',
            'public/dashboard.js'
        ];
        
        foreach ($jsFiles as $file) {
            if (file_exists($file)) {
                echo "<p class='success'>✓ $file existe</p>";
                $size = filesize($file);
                echo "<p class='info'>Tamaño: " . number_format($size) . " bytes</p>";
            } else {
                echo "<p class='error'>✗ $file NO existe</p>";
            }
        }
        ?>
    </div>
    
    <div class="debug-section">
        <h2>2. Test de Tabla HTML Básica</h2>
        <p>Esta tabla debería renderizarse correctamente:</p>
        <table class="test-table leads-table data-table">
            <thead>
                <tr>
                    <th>ID</th>
                    <th>Nombre</th>
                    <th>Email</th>
                    <th>Estado</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td>1</td>
                    <td>Juan Pérez</td>
                    <td>juan@example.com</td>
                    <td>new</td>
                </tr>
                <tr>
                    <td>2</td>
                    <td>María García</td>
                    <td>maria@example.com</td>
                    <td>contacted</td>
                </tr>
            </tbody>
        </table>
    </div>
    
    <div class="debug-section">
        <h2>3. Test de Leads Reales</h2>
        <?php
        try {
            // Obtener algunos leads reales
            $stmt = $pdo->prepare("SELECT id, first_name, last_name, email, status FROM leads LIMIT 5");
            $stmt->execute();
            $leads = $stmt->fetchAll(PDO::FETCH_ASSOC);
            
            if (count($leads) > 0) {
                echo "<p class='success'>Se encontraron " . count($leads) . " leads en la base de datos</p>";
                echo "<table class='test-table leads-table data-table'>";
                echo "<thead><tr><th>ID</th><th>Nombre</th><th>Email</th><th>Estado</th></tr></thead>";
                echo "<tbody>";
                foreach ($leads as $lead) {
                    echo "<tr>";
                    echo "<td>" . htmlspecialchars($lead['id']) . "</td>";
                    echo "<td>" . htmlspecialchars($lead['first_name'] . ' ' . $lead['last_name']) . "</td>";
                    echo "<td>" . htmlspecialchars($lead['email']) . "</td>";
                    echo "<td>" . htmlspecialchars($lead['status']) . "</td>";
                    echo "</tr>";
                }
                echo "</tbody></table>";
            } else {
                echo "<p class='error'>No se encontraron leads en la base de datos</p>";
            }
        } catch (Exception $e) {
            echo "<p class='error'>Error al obtener leads: " . $e->getMessage() . "</p>";
        }
        ?>
    </div>
    
    <div class="debug-section">
        <h2>4. Console Log de JavaScript</h2>
        <p>Abre las herramientas de desarrollador (F12) y revisa la consola para ver si hay errores JavaScript.</p>
        <button onclick="testJavaScript()">Probar JavaScript</button>
        <div id="js-test-result"></div>
    </div>
    
    <div class="debug-section">
        <h2>5. Verificación de CSS</h2>
        <p>Verificando si los estilos CSS están cargando correctamente:</p>
        <div style="background: red; color: white; padding: 10px; margin: 10px 0;">
            Este div debería tener fondo rojo
        </div>
        <div class="leads-container" style="border: 2px solid blue; padding: 10px;">
            Este div tiene la clase 'leads-container'
        </div>
    </div>
    
    <!-- Incluir los archivos JavaScript -->
    <script src="public/script.js"></script>
    <script>
        function testJavaScript() {
            const resultDiv = document.getElementById('js-test-result');
            
            try {
                // Test 1: Verificar si las funciones existen
                const tests = [
                    { name: 'initializeTables', func: window.initializeTables },
                    { name: 'setupTableUX', func: window.setupTableUX },
                    { name: 'goToLeadProfile', func: window.goToLeadProfile }
                ];
                
                let results = '<h3>Resultados de pruebas JavaScript:</h3>';
                
                tests.forEach(test => {
                    if (typeof test.func === 'function') {
                        results += `<p class="success">✓ ${test.name} está definida</p>`;
                    } else {
                        results += `<p class="error">✗ ${test.name} NO está definida</p>`;
                    }
                });
                
                // Test 2: Verificar si las tablas se inicializan
                const tables = document.querySelectorAll('table.leads-table, table.data-table');
                results += `<p class="info">Tablas encontradas: ${tables.length}</p>`;
                
                // Test 3: Intentar inicializar tablas
                if (typeof window.initializeTables === 'function') {
                    window.initializeTables();
                    results += '<p class="success">✓ initializeTables() ejecutada</p>';
                } else {
                    results += '<p class="error">✗ No se pudo ejecutar initializeTables()</p>';
                }
                
                resultDiv.innerHTML = results;
                
            } catch (error) {
                resultDiv.innerHTML = `<p class="error">Error en JavaScript: ${error.message}</p>`;
                console.error('Error en test JavaScript:', error);
            }
        }
        
        // Auto-ejecutar al cargar
        document.addEventListener('DOMContentLoaded', function() {
            console.log('Debug JavaScript cargado');
            testJavaScript();
        });
    </script>
</body>
</html>