<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>🧪 Test Completo - Rutas AJAX Corregidas</title>
    <style>
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            margin: 20px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: #333;
            min-height: 100vh;
        }
        .container {
            max-width: 1200px;
            margin: 0 auto;
            background: white;
            border-radius: 15px;
            padding: 30px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.2);
        }
        h1 {
            text-align: center;
            color: #2c3e50;
            margin-bottom: 30px;
            font-size: 2.5em;
        }
        .module-section {
            margin: 30px 0;
            padding: 20px;
            border: 2px solid #e74c3c;
            border-radius: 10px;
            background: #fff5f5;
        }
        .module-section.success {
            border-color: #27ae60;
            background: #f0fff4;
        }
        .module-section.warning {
            border-color: #f39c12;
            background: #fffbf0;
        }
        .test-button {
            background: #3498db;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 5px;
            cursor: pointer;
            margin: 5px;
            font-size: 14px;
            transition: all 0.3s;
        }
        .test-button:hover {
            background: #2980b9;
            transform: translateY(-2px);
        }
        .test-button:disabled {
            background: #95a5a6;
            cursor: not-allowed;
            transform: none;
        }
        .result {
            margin: 10px 0;
            padding: 10px;
            border-radius: 5px;
            font-family: monospace;
            font-size: 12px;
        }
        .success {
            background: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        .error {
            background: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }
        .info {
            background: #d1ecf1;
            color: #0c5460;
            border: 1px solid #bee5eb;
        }
        .stats {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 20px;
            margin: 20px 0;
        }
        .stat-card {
            background: #f8f9fa;
            padding: 20px;
            border-radius: 10px;
            text-align: center;
            border-left: 4px solid #3498db;
        }
        .stat-number {
            font-size: 2em;
            font-weight: bold;
            color: #2c3e50;
        }
        .progress-bar {
            width: 100%;
            height: 20px;
            background: #ecf0f1;
            border-radius: 10px;
            overflow: hidden;
            margin: 10px 0;
        }
        .progress-fill {
            height: 100%;
            background: linear-gradient(90deg, #27ae60, #2ecc71);
            width: 0%;
            transition: width 0.5s ease;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>🧪 Test Completo - Rutas AJAX Corregidas</h1>
        
        <div class="stats">
            <div class="stat-card">
                <div class="stat-number" id="totalTests">0</div>
                <div>Tests Totales</div>
            </div>
            <div class="stat-card">
                <div class="stat-number" id="passedTests">0</div>
                <div>Tests Exitosos</div>
            </div>
            <div class="stat-card">
                <div class="stat-number" id="failedTests">0</div>
                <div>Tests Fallidos</div>
            </div>
            <div class="stat-card">
                <div class="stat-number" id="successRate">0%</div>
                <div>Tasa de Éxito</div>
            </div>
        </div>

        <div class="progress-bar">
            <div class="progress-fill" id="progressFill"></div>
        </div>

        <!-- Módulo Roles (ya corregido anteriormente) -->
        <div class="module-section" id="rolesModule">
            <h2>🔐 Módulo Roles</h2>
            <p><strong>Estado:</strong> ✅ Previamente corregido</p>
            <button class="test-button" onclick="testRolesModule()">Test Roles AJAX</button>
            <div id="rolesResults"></div>
        </div>

        <!-- Módulo Desks -->
        <div class="module-section" id="desksModule">
            <h2>🎫 Módulo Desks (Tickets)</h2>
            <p><strong>Correcciones aplicadas:</strong></p>
            <ul>
                <li><code>document_review.php</code> - update_document_status.php</li>
                <li><code>ticket.php</code> - reply_ticket_message.php</li>
            </ul>
            <button class="test-button" onclick="testDesksModule()">Test Desks AJAX</button>
            <div id="desksResults"></div>
        </div>

        <!-- Módulo Client Portal -->
        <div class="module-section" id="clientPortalModule">
            <h2>👥 Módulo Client Portal</h2>
            <p><strong>Correcciones aplicadas:</strong></p>
            <ul>
                <li><code>ticket.php</code> - add_ticket_message.php</li>
                <li><code>tickets.php</code> - create_ticket.php</li>
            </ul>
            <button class="test-button" onclick="testClientPortalModule()">Test Client Portal AJAX</button>
            <div id="clientPortalResults"></div>
        </div>

        <!-- Módulo Clients -->
        <div class="module-section" id="clientsModule">
            <h2>👤 Módulo Clients</h2>
            <p><strong>Correcciones aplicadas:</strong></p>
            <ul>
                <li><code>view.php</code> - integrations/actions.php (voiso_click_to_call)</li>
            </ul>
            <button class="test-button" onclick="testClientsModule()">Test Clients AJAX</button>
            <div id="clientsResults"></div>
        </div>

        <!-- Módulo Integrations -->
        <div class="module-section" id="integrationsModule">
            <h2>🔗 Módulo Integrations</h2>
            <p><strong>Correcciones aplicadas:</strong></p>
            <ul>
                <li><code>integrations_content.php</code> - 5 endpoints corregidos</li>
                <li>save_settings, test_voiso, test_big4pay, get_big4pay_password, test_big4pay_payment</li>
            </ul>
            <button class="test-button" onclick="testIntegrationsModule()">Test Integrations AJAX</button>
            <div id="integrationsResults"></div>
        </div>

        <!-- Dashboard Público -->
        <div class="module-section" id="dashboardModule">
            <h2>📊 Dashboard Público</h2>
            <p><strong>Correcciones aplicadas:</strong></p>
            <ul>
                <li><code>dashboard.js</code> - upload_document.php</li>
                <li><code>dashboard.js</code> - create_ticket.php</li>
            </ul>
            <button class="test-button" onclick="testDashboardModule()">Test Dashboard AJAX</button>
            <div id="dashboardResults"></div>
        </div>

        <div style="margin-top: 30px; text-align: center;">
            <button class="test-button" onclick="runAllTests()" style="background: #e74c3c; font-size: 16px; padding: 15px 30px;">
                🚀 Ejecutar Todos los Tests
            </button>
            <button class="test-button" onclick="location.reload()" style="background: #95a5a6;">
                🔄 Reiniciar Tests
            </button>
        </div>
    </div>

    <script>
        let testStats = {
            total: 0,
            passed: 0,
            failed: 0
        };

        function updateStats() {
            document.getElementById('totalTests').textContent = testStats.total;
            document.getElementById('passedTests').textContent = testStats.passed;
            document.getElementById('failedTests').textContent = testStats.failed;
            
            const successRate = testStats.total > 0 ? Math.round((testStats.passed / testStats.total) * 100) : 0;
            document.getElementById('successRate').textContent = successRate + '%';
            
            const progressPercent = testStats.total > 0 ? (testStats.passed / testStats.total) * 100 : 0;
            document.getElementById('progressFill').style.width = progressPercent + '%';
        }

        function addResult(containerId, message, type = 'info') {
            const container = document.getElementById(containerId);
            const result = document.createElement('div');
            result.className = `result ${type}`;
            result.innerHTML = `[${new Date().toLocaleTimeString()}] ${message}`;
            container.appendChild(result);
            
            testStats.total++;
            if (type === 'success') {
                testStats.passed++;
                document.getElementById(containerId.replace('Results', 'Module')).classList.add('success');
            } else if (type === 'error') {
                testStats.failed++;
            }
            updateStats();
        }

        async function testEndpoint(url, method = 'GET', data = null) {
            try {
                const options = {
                    method: method,
                    headers: {
                        'Content-Type': 'application/json',
                    }
                };
                
                if (data && method !== 'GET') {
                    options.body = JSON.stringify(data);
                }
                
                const response = await fetch(url, options);
                
                return {
                    success: response.ok,
                    status: response.status,
                    statusText: response.statusText,
                    url: url
                };
            } catch (error) {
                return {
                    success: false,
                    error: error.message,
                    url: url
                };
            }
        }

        async function testRolesModule() {
            addResult('rolesResults', '🔄 Iniciando tests del módulo Roles...', 'info');
            
            const endpoints = [
                'modules/roles/actions.php?action=get_role_details',
                'modules/roles/actions.php?action=get_users',
                'modules/roles/actions.php?action=update_permissions'
            ];
            
            for (const endpoint of endpoints) {
                const result = await testEndpoint(endpoint);
                if (result.success || result.status === 405) { // 405 = Method not allowed (esperado para POST endpoints)
                    addResult('rolesResults', `✅ ${endpoint} - Ruta accesible`, 'success');
                } else {
                    addResult('rolesResults', `❌ ${endpoint} - Error: ${result.error || result.statusText}`, 'error');
                }
            }
        }

        async function testDesksModule() {
            addResult('desksResults', '🔄 Iniciando tests del módulo Desks...', 'info');
            
            const endpoints = [
                'modules/desks/update_document_status.php',
                'modules/desks/reply_ticket_message.php'
            ];
            
            for (const endpoint of endpoints) {
                const result = await testEndpoint(endpoint);
                if (result.success || result.status === 405) {
                    addResult('desksResults', `✅ ${endpoint} - Ruta accesible`, 'success');
                } else {
                    addResult('desksResults', `❌ ${endpoint} - Error: ${result.error || result.statusText}`, 'error');
                }
            }
        }

        async function testClientPortalModule() {
            addResult('clientPortalResults', '🔄 Iniciando tests del módulo Client Portal...', 'info');
            
            const endpoints = [
                'modules/client_portal/add_ticket_message.php',
                'modules/client_portal/create_ticket.php'
            ];
            
            for (const endpoint of endpoints) {
                const result = await testEndpoint(endpoint);
                if (result.success || result.status === 405) {
                    addResult('clientPortalResults', `✅ ${endpoint} - Ruta accesible`, 'success');
                } else {
                    addResult('clientPortalResults', `❌ ${endpoint} - Error: ${result.error || result.statusText}`, 'error');
                }
            }
        }

        async function testClientsModule() {
            addResult('clientsResults', '🔄 Iniciando tests del módulo Clients...', 'info');
            
            const endpoints = [
                'modules/integrations/actions.php?action=voiso_click_to_call'
            ];
            
            for (const endpoint of endpoints) {
                const result = await testEndpoint(endpoint);
                if (result.success || result.status === 405) {
                    addResult('clientsResults', `✅ ${endpoint} - Ruta accesible`, 'success');
                } else {
                    addResult('clientsResults', `❌ ${endpoint} - Error: ${result.error || result.statusText}`, 'error');
                }
            }
        }

        async function testIntegrationsModule() {
            addResult('integrationsResults', '🔄 Iniciando tests del módulo Integrations...', 'info');
            
            const endpoints = [
                'modules/integrations/actions.php?action=save_settings',
                'modules/integrations/actions.php?action=test_voiso',
                'modules/integrations/actions.php?action=test_big4pay',
                'modules/integrations/actions.php?action=get_big4pay_password',
                'modules/integrations/actions.php?action=test_big4pay_payment'
            ];
            
            for (const endpoint of endpoints) {
                const result = await testEndpoint(endpoint);
                if (result.success || result.status === 405) {
                    addResult('integrationsResults', `✅ ${endpoint} - Ruta accesible`, 'success');
                } else {
                    addResult('integrationsResults', `❌ ${endpoint} - Error: ${result.error || result.statusText}`, 'error');
                }
            }
        }

        async function testDashboardModule() {
            addResult('dashboardResults', '🔄 Iniciando tests del Dashboard...', 'info');
            
            const endpoints = [
                'modules/client_portal/upload_document.php',
                'modules/client_portal/create_ticket.php'
            ];
            
            for (const endpoint of endpoints) {
                const result = await testEndpoint(endpoint);
                if (result.success || result.status === 405) {
                    addResult('dashboardResults', `✅ ${endpoint} - Ruta accesible`, 'success');
                } else {
                    addResult('dashboardResults', `❌ ${endpoint} - Error: ${result.error || result.statusText}`, 'error');
                }
            }
        }

        async function runAllTests() {
            // Limpiar resultados anteriores
            document.querySelectorAll('.result').forEach(el => el.remove());
            document.querySelectorAll('.module-section').forEach(el => {
                el.classList.remove('success', 'warning');
            });
            
            testStats = { total: 0, passed: 0, failed: 0 };
            updateStats();
            
            // Ejecutar todos los tests
            await testRolesModule();
            await new Promise(resolve => setTimeout(resolve, 500));
            
            await testDesksModule();
            await new Promise(resolve => setTimeout(resolve, 500));
            
            await testClientPortalModule();
            await new Promise(resolve => setTimeout(resolve, 500));
            
            await testClientsModule();
            await new Promise(resolve => setTimeout(resolve, 500));
            
            await testIntegrationsModule();
            await new Promise(resolve => setTimeout(resolve, 500));
            
            await testDashboardModule();
            
            // Mostrar resumen final
            setTimeout(() => {
                const successRate = Math.round((testStats.passed / testStats.total) * 100);
                alert(`🎉 Tests completados!\n\nTotal: ${testStats.total}\nExitosos: ${testStats.passed}\nFallidos: ${testStats.failed}\nTasa de éxito: ${successRate}%`);
            }, 1000);
        }

        // Inicializar estadísticas
        updateStats();
    </script>
</body>
</html>