<?php
session_start();
require_once '../../database/connection.php';

// Simular usuario logueado para pruebas
if (!isset($_SESSION['user_id'])) {
    $_SESSION['user_id'] = 1;
    $_SESSION['username'] = 'admin';
    $_SESSION['role'] = 'admin';
}

echo "<h1>Diagnóstico Completo - Status Update</h1>";
echo "<style>
    body { font-family: Arial, sans-serif; margin: 20px; }
    .section { margin: 20px 0; padding: 15px; border: 1px solid #ddd; border-radius: 5px; }
    .success { background-color: #d4edda; border-color: #c3e6cb; }
    .error { background-color: #f8d7da; border-color: #f5c6cb; }
    .warning { background-color: #fff3cd; border-color: #ffeaa7; }
    .info { background-color: #d1ecf1; border-color: #bee5eb; }
    pre { background: #f8f9fa; padding: 10px; border-radius: 3px; overflow-x: auto; }
    .test-button { padding: 10px 15px; margin: 5px; background: #007bff; color: white; border: none; border-radius: 3px; cursor: pointer; }
    .test-button:hover { background: #0056b3; }
</style>";

// 1. Verificar archivos críticos
echo "<div class='section info'>";
echo "<h2>1. Verificación de Archivos Críticos</h2>";

$files_to_check = [
    'view_scripts.js' => 'view_scripts.js',
    'update_status.php' => 'update_status.php',
    'view_content.php' => 'view_content.php'
];

foreach ($files_to_check as $file => $path) {
    if (file_exists($path)) {
        $size = filesize($path);
        echo "<p class='success'>✓ $file existe ($size bytes)</p>";
        
        if ($file === 'view_scripts.js') {
            $content = file_get_contents($path);
            if (strpos($content, 'lead-status-select') !== false) {
                echo "<p class='success'>✓ view_scripts.js contiene código para lead-status-select</p>";
            } else {
                echo "<p class='error'>✗ view_scripts.js NO contiene código para lead-status-select</p>";
            }
            
            if (strpos($content, 'updateLeadStatus') !== false) {
                echo "<p class='success'>✓ view_scripts.js contiene función updateLeadStatus</p>";
            } else {
                echo "<p class='error'>✗ view_scripts.js NO contiene función updateLeadStatus</p>";
            }
        }
    } else {
        echo "<p class='error'>✗ $file NO existe</p>";
    }
}
echo "</div>";

// 2. Verificar estructura de base de datos
echo "<div class='section info'>";
echo "<h2>2. Verificación de Base de Datos</h2>";

try {
    // Verificar tabla leads
    $stmt = $pdo->query("DESCRIBE leads");
    $columns = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    $has_status = false;
    foreach ($columns as $column) {
        if ($column['Field'] === 'status') {
            $has_status = true;
            echo "<p class='success'>✓ Columna 'status' existe en tabla leads</p>";
            echo "<p>Tipo: {$column['Type']}, Null: {$column['Null']}, Default: {$column['Default']}</p>";
            break;
        }
    }
    
    if (!$has_status) {
        echo "<p class='error'>✗ Columna 'status' NO existe en tabla leads</p>";
    }
    
    // Verificar lead de prueba
    $stmt = $pdo->prepare("SELECT id, status, first_name, last_name FROM leads WHERE id = 10292");
    $stmt->execute();
    $lead = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if ($lead) {
        echo "<p class='success'>✓ Lead 10292 existe</p>";
        echo "<pre>" . print_r($lead, true) . "</pre>";
    } else {
        echo "<p class='warning'>⚠ Lead 10292 no existe, usando el primer lead disponible</p>";
        $stmt = $pdo->query("SELECT id, status, first_name, last_name FROM leads LIMIT 1");
        $lead = $stmt->fetch(PDO::FETCH_ASSOC);
        if ($lead) {
            echo "<pre>" . print_r($lead, true) . "</pre>";
        }
    }
    
} catch (Exception $e) {
    echo "<p class='error'>✗ Error de base de datos: " . $e->getMessage() . "</p>";
}
echo "</div>";

// 3. Generar HTML de prueba con selector
if ($lead) {
    echo "<div class='section warning'>";
    echo "<h2>3. Prueba del Selector de Status</h2>";
    echo "<p>Selector de status para Lead ID: {$lead['id']}</p>";
    
    $statuses = ['new', 'contacted', 'qualified', 'proposal', 'negotiation', 'closed_won', 'closed_lost'];
    
    echo "<select id='lead-status-select' data-lead-id='{$lead['id']}' data-original-status='{$lead['status']}'>";
    foreach ($statuses as $status) {
        $selected = ($status === $lead['status']) ? 'selected' : '';
        $display_name = ucfirst(str_replace('_', ' ', $status));
        echo "<option value='$status' $selected>$display_name</option>";
    }
    echo "</select>";
    
    echo "<div id='status-feedback' style='margin-top: 10px; padding: 10px; border-radius: 3px; display: none;'></div>";
    echo "</div>";
}

// 4. JavaScript de diagnóstico
echo "<div class='section info'>";
echo "<h2>4. Diagnóstico JavaScript</h2>";
echo "<button class='test-button' onclick='testJavaScriptLoading()'>Probar Carga de JavaScript</button>";
echo "<button class='test-button' onclick='testEventListener()'>Probar Event Listener</button>";
echo "<button class='test-button' onclick='testAjaxEndpoint()'>Probar Endpoint AJAX</button>";
echo "<div id='js-results' style='margin-top: 15px;'></div>";
echo "</div>";

// 5. Incluir view_scripts.js si existe
if (file_exists('view_scripts.js')) {
    echo "<script src='view_scripts.js'></script>";
    echo "<div class='section success'>";
    echo "<h2>5. JavaScript Cargado</h2>";
    echo "<p>✓ view_scripts.js ha sido incluido en esta página</p>";
    echo "</div>";
} else {
    echo "<div class='section error'>";
    echo "<h2>5. JavaScript NO Cargado</h2>";
    echo "<p>✗ view_scripts.js no se pudo cargar</p>";
    echo "</div>";
}
?>

<script>
function testJavaScriptLoading() {
    const results = document.getElementById('js-results');
    let html = '<h3>Resultados de Carga JavaScript:</h3>';
    
    // Verificar si las funciones existen
    if (typeof updateLeadStatus === 'function') {
        html += '<p class="success">✓ Función updateLeadStatus está disponible</p>';
    } else {
        html += '<p class="error">✗ Función updateLeadStatus NO está disponible</p>';
    }
    
    if (typeof showStatusUpdateSuccess === 'function') {
        html += '<p class="success">✓ Función showStatusUpdateSuccess está disponible</p>';
    } else {
        html += '<p class="error">✗ Función showStatusUpdateSuccess NO está disponible</p>';
    }
    
    if (typeof showStatusUpdateError === 'function') {
        html += '<p class="success">✓ Función showStatusUpdateError está disponible</p>';
    } else {
        html += '<p class="error">✗ Función showStatusUpdateError NO está disponible</p>';
    }
    
    results.innerHTML = html;
}

function testEventListener() {
    const results = document.getElementById('js-results');
    const select = document.getElementById('lead-status-select');
    
    let html = '<h3>Resultados de Event Listener:</h3>';
    
    if (select) {
        html += '<p class="success">✓ Elemento select encontrado</p>';
        html += `<p>ID: ${select.id}</p>`;
        html += `<p>data-lead-id: ${select.getAttribute('data-lead-id')}</p>`;
        html += `<p>data-original-status: ${select.getAttribute('data-original-status')}</p>`;
        
        // Verificar si tiene event listeners
        const events = getEventListeners ? getEventListeners(select) : 'No disponible en este navegador';
        html += `<p>Event Listeners: ${JSON.stringify(events)}</p>`;
        
        // Probar cambio manual
        html += '<p><button onclick="triggerManualChange()" class="test-button">Disparar Cambio Manual</button></p>';
    } else {
        html += '<p class="error">✗ Elemento select NO encontrado</p>';
    }
    
    results.innerHTML = html;
}

function triggerManualChange() {
    const select = document.getElementById('lead-status-select');
    if (select) {
        const event = new Event('change', { bubbles: true });
        select.dispatchEvent(event);
        
        const feedback = document.getElementById('status-feedback');
        feedback.style.display = 'block';
        feedback.style.backgroundColor = '#d1ecf1';
        feedback.innerHTML = 'Evento change disparado manualmente';
    }
}

function testAjaxEndpoint() {
    const results = document.getElementById('js-results');
    const select = document.getElementById('lead-status-select');
    
    if (!select) {
        results.innerHTML = '<p class="error">✗ No se puede probar sin el elemento select</p>';
        return;
    }
    
    const leadId = select.getAttribute('data-lead-id');
    const newStatus = 'contacted'; // Status de prueba
    
    let html = '<h3>Probando Endpoint AJAX:</h3>';
    html += `<p>Enviando: Lead ID ${leadId}, Status: ${newStatus}</p>`;
    
    fetch('update_status.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: `lead_id=${leadId}&status=${newStatus}`
    })
    .then(response => response.json())
    .then(data => {
        html += `<p class="success">✓ Respuesta recibida:</p>`;
        html += `<pre>${JSON.stringify(data, null, 2)}</pre>`;
        results.innerHTML = html;
    })
    .catch(error => {
        html += `<p class="error">✗ Error en AJAX: ${error.message}</p>`;
        results.innerHTML = html;
    });
    
    results.innerHTML = html;
}

// Verificar cuando el DOM esté listo
document.addEventListener('DOMContentLoaded', function() {
    console.log('DOM loaded - Diagnóstico iniciado');
    
    const select = document.getElementById('lead-status-select');
    if (select) {
        console.log('Select encontrado:', select);
        console.log('data-lead-id:', select.getAttribute('data-lead-id'));
        console.log('data-original-status:', select.getAttribute('data-original-status'));
        
        // Agregar listener de prueba
        select.addEventListener('change', function() {
            console.log('¡Cambio detectado en select!');
            console.log('Nuevo valor:', this.value);
            
            const feedback = document.getElementById('status-feedback');
            feedback.style.display = 'block';
            feedback.style.backgroundColor = '#fff3cd';
            feedback.innerHTML = `Cambio detectado: ${this.value}`;
        });
    } else {
        console.error('Select NO encontrado');
    }
});
</script>