<?php
/**
 * TEST COMPLETO DEL SISTEMA
 * Verifica configuración, BD, autenticación, servicios, seguridad y funcionalidad
 */

error_reporting(E_ALL);
ini_set('display_errors', '1');

// HTML Setup
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Test Completo del Sistema</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            padding: 20px;
            color: #333;
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
            background: white;
            border-radius: 12px;
            box-shadow: 0 20px 60px rgba(0,0,0,0.3);
            overflow: hidden;
        }

        .header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 30px;
            text-align: center;
        }

        .header h1 {
            font-size: 2.5em;
            margin-bottom: 10px;
        }

        .header .subtitle {
            font-size: 1.1em;
            opacity: 0.9;
        }

        .stats {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 20px;
            padding: 30px;
            background: #f8f9fa;
            border-bottom: 2px solid #e9ecef;
        }

        .stat-card {
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
            text-align: center;
        }

        .stat-card .number {
            font-size: 2.5em;
            font-weight: bold;
            margin-bottom: 5px;
        }

        .stat-card.success .number { color: #10b981; }
        .stat-card.error .number { color: #ef4444; }
        .stat-card.warning .number { color: #f59e0b; }
        .stat-card.info .number { color: #3b82f6; }

        .stat-card .label {
            color: #6b7280;
            font-size: 0.9em;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }

        .content {
            padding: 30px;
        }

        .section {
            margin-bottom: 30px;
            border: 1px solid #e5e7eb;
            border-radius: 8px;
            overflow: hidden;
        }

        .section-header {
            background: #f3f4f6;
            padding: 15px 20px;
            font-size: 1.3em;
            font-weight: 600;
            color: #1f2937;
            display: flex;
            align-items: center;
            gap: 10px;
            cursor: pointer;
            user-select: none;
        }

        .section-header:hover {
            background: #e5e7eb;
        }

        .section-header .icon {
            font-size: 1.2em;
        }

        .section-header .badge {
            margin-left: auto;
            padding: 4px 12px;
            border-radius: 12px;
            font-size: 0.75em;
            font-weight: 600;
        }

        .badge.success { background: #d1fae5; color: #065f46; }
        .badge.error { background: #fee2e2; color: #991b1b; }
        .badge.warning { background: #fef3c7; color: #92400e; }
        .badge.info { background: #dbeafe; color: #1e40af; }

        .section-content {
            padding: 20px;
        }

        .test-item {
            display: flex;
            align-items: flex-start;
            padding: 12px;
            margin-bottom: 8px;
            border-radius: 6px;
            background: #f9fafb;
            border-left: 4px solid transparent;
        }

        .test-item.success {
            border-left-color: #10b981;
            background: #ecfdf5;
        }

        .test-item.error {
            border-left-color: #ef4444;
            background: #fef2f2;
        }

        .test-item.warning {
            border-left-color: #f59e0b;
            background: #fffbeb;
        }

        .test-item.info {
            border-left-color: #3b82f6;
            background: #eff6ff;
        }

        .test-item .icon {
            font-size: 1.5em;
            margin-right: 12px;
            min-width: 24px;
        }

        .test-item .content {
            flex: 1;
        }

        .test-item .title {
            font-weight: 600;
            margin-bottom: 4px;
        }

        .test-item .details {
            font-size: 0.9em;
            color: #6b7280;
            margin-top: 4px;
        }

        .code-block {
            background: #1f2937;
            color: #f3f4f6;
            padding: 15px;
            border-radius: 6px;
            font-family: 'Courier New', monospace;
            font-size: 0.9em;
            overflow-x: auto;
            margin-top: 10px;
        }

        .code-block .key {
            color: #60a5fa;
        }

        .code-block .value {
            color: #34d399;
        }

        .progress-bar {
            height: 8px;
            background: #e5e7eb;
            border-radius: 4px;
            overflow: hidden;
            margin: 10px 0;
        }

        .progress-fill {
            height: 100%;
            background: linear-gradient(90deg, #10b981, #059669);
            transition: width 0.3s;
        }

        table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 10px;
        }

        th, td {
            text-align: left;
            padding: 10px;
            border-bottom: 1px solid #e5e7eb;
        }

        th {
            background: #f9fafb;
            font-weight: 600;
            color: #374151;
        }

        tr:hover {
            background: #f9fafb;
        }

        .collapse-toggle {
            transition: transform 0.3s;
        }

        .collapsed .collapse-toggle {
            transform: rotate(-90deg);
        }

        .collapsed .section-content {
            display: none;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>🔍 Test Completo del Sistema</h1>
            <div class="subtitle">Verificación exhaustiva de configuración, seguridad y funcionalidad</div>
        </div>

<?php

// ============================================================================
// VARIABLES DE SEGUIMIENTO
// ============================================================================
$totalTests = 0;
$passedTests = 0;
$failedTests = 0;
$warningTests = 0;

function testResult($passed, $title, $details = '', $type = 'success') {
    global $totalTests, $passedTests, $failedTests, $warningTests;
    $totalTests++;

    if ($type === 'warning') {
        $warningTests++;
        $icon = '⚠️';
        $class = 'warning';
    } elseif (!$passed) {
        $failedTests++;
        $icon = '❌';
        $class = 'error';
    } else {
        $passedTests++;
        $icon = '✅';
        $class = 'success';
    }

    echo "<div class='test-item {$class}'>";
    echo "<div class='icon'>{$icon}</div>";
    echo "<div class='content'>";
    echo "<div class='title'>{$title}</div>";
    if ($details) {
        echo "<div class='details'>{$details}</div>";
    }
    echo "</div>";
    echo "</div>";

    return $passed;
}

// ============================================================================
// 1. CONFIGURACIÓN Y ARCHIVOS
// ============================================================================
echo "<div class='section'>";
echo "<div class='section-header' onclick='toggleSection(this)'>";
echo "<span class='collapse-toggle'>▼</span>";
echo "<span class='icon'>⚙️</span>";
echo "<span>Configuración del Sistema</span>";
echo "<span class='badge info' id='badge-config'>Verificando...</span>";
echo "</div>";
echo "<div class='section-content'>";

$configPassed = 0;
$configTotal = 0;

// PHP Version
$configTotal++;
$phpVersion = phpversion();
$phpOk = version_compare($phpVersion, '7.4.0', '>=');
testResult($phpOk, "PHP Version: {$phpVersion}", $phpOk ? 'Versión compatible' : 'Requiere PHP 7.4+');
if ($phpOk) $configPassed++;

// Archivos críticos
$criticalFiles = [
    'config/bootstrap.php' => 'Bootstrap principal',
    'src/Services/AuthService.php' => 'Servicio de autenticación',
    'src/Services/ContractService.php' => 'Servicio de contratos',
    'src/Services/Database.php' => 'Conexión a base de datos',
    'includes/require-auth.php' => 'Helper de autenticación segura',
    '.env' => 'Variables de entorno',
];

foreach ($criticalFiles as $file => $desc) {
    $configTotal++;
    $exists = file_exists(__DIR__ . '/' . $file);
    testResult($exists, $desc, $exists ? "Archivo: {$file}" : "❌ No encontrado: {$file}");
    if ($exists) $configPassed++;
}

// Directorios críticos
$criticalDirs = [
    'storage/contracts' => 'Almacenamiento de contratos',
    'storage/signatures' => 'Almacenamiento de firmas',
    'storage/logos' => 'Almacenamiento de logos',
    'storage/pdfs' => 'Almacenamiento de PDFs',
];

foreach ($criticalDirs as $dir => $desc) {
    $configTotal++;
    $path = __DIR__ . '/' . $dir;
    $exists = is_dir($path);
    $writable = $exists && is_writable($path);

    if ($writable) {
        testResult(true, $desc, "✓ Existe y tiene permisos de escritura");
        $configPassed++;
    } elseif ($exists) {
        testResult(false, $desc, "⚠️ Existe pero NO tiene permisos de escritura", 'warning');
    } else {
        testResult(false, $desc, "❌ No existe el directorio: {$dir}");
    }
}

echo "<script>document.getElementById('badge-config').textContent = '{$configPassed}/{$configTotal}'; document.getElementById('badge-config').className = 'badge " . ($configPassed === $configTotal ? 'success' : 'error') . "';</script>";
echo "</div></div>";

// ============================================================================
// 2. VARIABLES DE ENTORNO
// ============================================================================
echo "<div class='section'>";
echo "<div class='section-header' onclick='toggleSection(this)'>";
echo "<span class='collapse-toggle'>▼</span>";
echo "<span class='icon'>🔐</span>";
echo "<span>Variables de Entorno (.env)</span>";
echo "<span class='badge info' id='badge-env'>Verificando...</span>";
echo "</div>";
echo "<div class='section-content'>";

if (file_exists(__DIR__ . '/.env')) {
    require_once __DIR__ . '/config/bootstrap.php';

    $envPassed = 0;
    $envTotal = 0;

    $requiredEnv = [
        'DB_HOST' => 'Host de base de datos',
        'DB_NAME' => 'Nombre de base de datos',
        'DB_USER' => 'Usuario de base de datos',
        'DB_PASSWORD' => 'Contraseña de base de datos',
        'APP_URL' => 'URL de la aplicación',
        'APP_ENV' => 'Ambiente (production/development)',
    ];

    foreach ($requiredEnv as $key => $desc) {
        $envTotal++;
        $value = $_ENV[$key] ?? null;
        $exists = !empty($value);

        if ($key === 'APP_ENV') {
            $isProd = $value === 'production';
            testResult($exists, $desc, $exists ? "Valor: {$value} " . ($isProd ? '✓ Producción' : '⚠️ Development') : 'No configurado', $isProd ? 'success' : 'warning');
        } elseif ($key === 'DB_PASSWORD') {
            testResult($exists, $desc, $exists ? 'Configurado (oculto por seguridad)' : 'No configurado');
        } else {
            testResult($exists, $desc, $exists ? "Valor: {$value}" : 'No configurado');
        }

        if ($exists) $envPassed++;
    }

    echo "<script>document.getElementById('badge-env').textContent = '{$envPassed}/{$envTotal}'; document.getElementById('badge-env').className = 'badge " . ($envPassed === $envTotal ? 'success' : 'warning') . "';</script>";
} else {
    testResult(false, 'Archivo .env', '❌ No se encontró el archivo .env');
    echo "<script>document.getElementById('badge-env').textContent = '0/1'; document.getElementById('badge-env').className = 'badge error';</script>";
}

echo "</div></div>";

// ============================================================================
// 3. BASE DE DATOS
// ============================================================================
echo "<div class='section'>";
echo "<div class='section-header' onclick='toggleSection(this)'>";
echo "<span class='collapse-toggle'>▼</span>";
echo "<span class='icon'>🗄️</span>";
echo "<span>Base de Datos</span>";
echo "<span class='badge info' id='badge-db'>Verificando...</span>";
echo "</div>";
echo "<div class='section-content'>";

$dbPassed = 0;
$dbTotal = 0;

try {
    require_once __DIR__ . '/config/bootstrap.php';

    use App\Services\Database;

    $db = Database::getInstance();

    $dbTotal++;
    testResult(true, 'Conexión a base de datos', '✓ Conexión establecida correctamente');
    $dbPassed++;

    // Verificar tablas críticas
    $requiredTables = [
        'admins' => 'Tabla de administradores',
        'contracts' => 'Tabla de contratos',
        'signatures' => 'Tabla de firmas',
        'access_logs' => 'Tabla de logs de acceso',
        'sessions' => 'Tabla de sesiones',
        'password_resets' => 'Tabla de recuperación de contraseñas',
        'contract_templates' => 'Tabla de plantillas de contratos',
    ];

    foreach ($requiredTables as $table => $desc) {
        $dbTotal++;
        try {
            $result = $db->fetchOne("SHOW TABLES LIKE '{$table}'");
            $exists = !empty($result);

            if ($exists) {
                // Contar registros
                $count = $db->fetchOne("SELECT COUNT(*) as total FROM {$table}");
                testResult(true, $desc, "✓ Tabla existe - {$count['total']} registros");
                $dbPassed++;
            } else {
                testResult(false, $desc, "❌ Tabla no existe: {$table}");
            }
        } catch (Exception $e) {
            testResult(false, $desc, "❌ Error: " . $e->getMessage());
        }
    }

    // Verificar columna rol en admins
    $dbTotal++;
    try {
        $columns = $db->query("SHOW COLUMNS FROM admins LIKE 'rol'");
        $hasRol = !empty($columns);
        testResult($hasRol, 'Columna rol en admins', $hasRol ? '✓ Sistema de roles implementado' : '❌ Falta migración 003_add_roles.sql');
        if ($hasRol) $dbPassed++;
    } catch (Exception $e) {
        testResult(false, 'Columna rol en admins', "❌ Error: " . $e->getMessage());
    }

    echo "<script>document.getElementById('badge-db').textContent = '{$dbPassed}/{$dbTotal}'; document.getElementById('badge-db').className = 'badge " . ($dbPassed === $dbTotal ? 'success' : 'error') . "';</script>";

} catch (Exception $e) {
    testResult(false, 'Conexión a base de datos', "❌ Error: " . $e->getMessage());
    echo "<script>document.getElementById('badge-db').textContent = '0/1'; document.getElementById('badge-db').className = 'badge error';</script>";
}

echo "</div></div>";

// ============================================================================
// 4. SERVICIOS PRINCIPALES
// ============================================================================
echo "<div class='section'>";
echo "<div class='section-header' onclick='toggleSection(this)'>";
echo "<span class='collapse-toggle'>▼</span>";
echo "<span class='icon'>🔧</span>";
echo "<span>Servicios del Sistema</span>";
echo "<span class='badge info' id='badge-services'>Verificando...</span>";
echo "</div>";
echo "<div class='section-content'>";

$servicesPassed = 0;
$servicesTotal = 0;

$services = [
    'AuthService' => 'Servicio de autenticación',
    'ContractService' => 'Servicio de contratos',
    'SignatureService' => 'Servicio de firmas',
    'SecurityService' => 'Servicio de seguridad',
    'EmailService' => 'Servicio de email',
    'TemplateService' => 'Servicio de plantillas',
    'Logger' => 'Servicio de logging',
];

foreach ($services as $serviceClass => $desc) {
    $servicesTotal++;
    try {
        $fullClass = "App\\Services\\{$serviceClass}";

        if (class_exists($fullClass)) {
            $service = new $fullClass();
            testResult(true, $desc, "✓ Clase: {$fullClass}");
            $servicesPassed++;
        } else {
            testResult(false, $desc, "❌ Clase no encontrada: {$fullClass}");
        }
    } catch (Exception $e) {
        testResult(false, $desc, "❌ Error al instanciar: " . $e->getMessage());
    }
}

echo "<script>document.getElementById('badge-services').textContent = '{$servicesPassed}/{$servicesTotal}'; document.getElementById('badge-services').className = 'badge " . ($servicesPassed === $servicesTotal ? 'success' : 'error') . "';</script>";
echo "</div></div>";

// ============================================================================
// 5. SISTEMA DE AUTENTICACIÓN Y ROLES
// ============================================================================
echo "<div class='section'>";
echo "<div class='section-header' onclick='toggleSection(this)'>";
echo "<span class='collapse-toggle'>▼</span>";
echo "<span class='icon'>🔑</span>";
echo "<span>Sistema de Autenticación y Roles</span>";
echo "<span class='badge info' id='badge-auth'>Verificando...</span>";
echo "</div>";
echo "<div class='section-content'>";

$authPassed = 0;
$authTotal = 0;

try {
    use App\Services\AuthService;

    $auth = new AuthService();

    // Verificar métodos críticos
    $authTotal++;
    $hasRequireAuth = method_exists($auth, 'requireAuth');
    testResult($hasRequireAuth, 'Método requireAuth()', $hasRequireAuth ? '✓ Método de autenticación segura disponible' : '❌ Falta implementación');
    if ($hasRequireAuth) $authPassed++;

    $authTotal++;
    $hasUser = method_exists($auth, 'user');
    testResult($hasUser, 'Método user()', $hasUser ? '✓ Método para obtener usuario disponible' : '❌ Falta implementación');
    if ($hasUser) $authPassed++;

    $authTotal++;
    $hasCheck = method_exists($auth, 'check');
    testResult($hasCheck, 'Método check()', $hasCheck ? '✓ Método de verificación de sesión disponible' : '❌ Falta implementación');
    if ($hasCheck) $authPassed++;

    // Verificar helper require-auth.php
    $authTotal++;
    $requireAuthExists = file_exists(__DIR__ . '/includes/require-auth.php');
    testResult($requireAuthExists, 'Helper require-auth.php', $requireAuthExists ? '✓ Helper de autenticación segura disponible' : '❌ Falta archivo');
    if ($requireAuthExists) $authPassed++;

    // Verificar que getFallbackUser esté bloqueado en producción
    $authTotal++;
    $fallbackFile = file_exists(__DIR__ . '/includes/get-fallback-user.php');
    if ($fallbackFile && ($_ENV['APP_ENV'] ?? 'production') === 'production') {
        require_once __DIR__ . '/includes/get-fallback-user.php';
        try {
            $testFallback = getFallbackUser();
            testResult(false, 'getFallbackUser() bloqueado en producción', '❌ CRÍTICO: getFallbackUser NO está bloqueado en producción', 'error');
        } catch (Exception $e) {
            testResult(true, 'getFallbackUser() bloqueado en producción', '✓ Correctamente bloqueado - lanza excepción');
            $authPassed++;
        }
    } else {
        testResult(true, 'getFallbackUser() bloqueado en producción', '⚠️ Modo development - getFallbackUser disponible', 'warning');
        $authPassed++;
    }

    // Contar usuarios por rol
    if (isset($db)) {
        $roles = $db->query("SELECT rol, COUNT(*) as total FROM admins WHERE activo = 1 GROUP BY rol");

        echo "<div class='test-item info'>";
        echo "<div class='icon'>👥</div>";
        echo "<div class='content'>";
        echo "<div class='title'>Distribución de Usuarios por Rol</div>";
        echo "<table>";
        echo "<tr><th>Rol</th><th>Total</th></tr>";

        $totalAdmins = 0;
        foreach ($roles as $role) {
            echo "<tr><td>" . ucfirst($role['rol']) . "</td><td>{$role['total']}</td></tr>";
            $totalAdmins += $role['total'];
        }

        echo "<tr style='font-weight:bold'><td>Total Activos</td><td>{$totalAdmins}</td></tr>";
        echo "</table>";
        echo "</div></div>";
    }

    echo "<script>document.getElementById('badge-auth').textContent = '{$authPassed}/{$authTotal}'; document.getElementById('badge-auth').className = 'badge " . ($authPassed === $authTotal ? 'success' : 'error') . "';</script>";

} catch (Exception $e) {
    testResult(false, 'Sistema de autenticación', "❌ Error crítico: " . $e->getMessage());
    echo "<script>document.getElementById('badge-auth').textContent = '0/1'; document.getElementById('badge-auth').className = 'badge error';</script>";
}

echo "</div></div>";

// ============================================================================
// 6. SEGURIDAD
// ============================================================================
echo "<div class='section'>";
echo "<div class='section-header' onclick='toggleSection(this)'>";
echo "<span class='collapse-toggle'>▼</span>";
echo "<span class='icon'>🛡️</span>";
echo "<span>Seguridad</span>";
echo "<span class='badge info' id='badge-security'>Verificando...</span>";
echo "</div>";
echo "<div class='section-content'>";

$securityPassed = 0;
$securityTotal = 0;

try {
    use App\Services\SecurityService;

    $security = new SecurityService();

    // CSRF Token
    $securityTotal++;
    $csrfToken = $security->generateCSRFToken();
    $hasCsrf = !empty($csrfToken);
    testResult($hasCsrf, 'Sistema CSRF Token', $hasCsrf ? '✓ Generación de tokens CSRF funcionando' : '❌ Error generando token');
    if ($hasCsrf) $securityPassed++;

    // Verificar CSRF
    $securityTotal++;
    $validCsrf = $security->verifyCSRFToken($csrfToken);
    testResult($validCsrf, 'Verificación CSRF Token', $validCsrf ? '✓ Verificación de tokens CSRF funcionando' : '❌ Fallo en verificación');
    if ($validCsrf) $securityPassed++;

    // Password Hashing
    $securityTotal++;
    $testPassword = 'Test123!@#';
    $hashedPassword = $security->hashPassword($testPassword);
    $hashWorks = !empty($hashedPassword) && strlen($hashedPassword) > 50;
    testResult($hashWorks, 'Hash de contraseñas', $hashWorks ? '✓ Bcrypt funcionando correctamente' : '❌ Error en hashing');
    if ($hashWorks) $securityPassed++;

    // Password Verify
    $securityTotal++;
    $verifyWorks = $security->verifyPassword($testPassword, $hashedPassword);
    testResult($verifyWorks, 'Verificación de contraseñas', $verifyWorks ? '✓ Verificación funcionando correctamente' : '❌ Error en verificación');
    if ($verifyWorks) $securityPassed++;

    // Sanitización
    $securityTotal++;
    $hasSanitize = method_exists($security, 'sanitizeString');
    testResult($hasSanitize, 'Sanitización de strings', $hasSanitize ? '✓ Métodos de sanitización disponibles' : '❌ Falta implementación');
    if ($hasSanitize) $securityPassed++;

    // Rate Limiting
    $securityTotal++;
    $hasRateLimit = method_exists($security, 'checkRateLimit');
    testResult($hasRateLimit, 'Rate Limiting', $hasRateLimit ? '✓ Sistema de rate limiting disponible' : '❌ Falta implementación');
    if ($hasRateLimit) $securityPassed++;

    // Headers de seguridad
    $securityTotal++;
    $headers = headers_list();
    $hasSecurityHeaders = !empty($headers);
    testResult($hasSecurityHeaders, 'Headers HTTP', $hasSecurityHeaders ? '✓ Headers configurados' : '⚠️ Sin headers de seguridad', $hasSecurityHeaders ? 'success' : 'warning');
    if ($hasSecurityHeaders) $securityPassed++;

    echo "<script>document.getElementById('badge-security').textContent = '{$securityPassed}/{$securityTotal}'; document.getElementById('badge-security').className = 'badge " . ($securityPassed === $securityTotal ? 'success' : 'error') . "';</script>";

} catch (Exception $e) {
    testResult(false, 'Sistema de seguridad', "❌ Error crítico: " . $e->getMessage());
    echo "<script>document.getElementById('badge-security').textContent = '0/1'; document.getElementById('badge-security').className = 'badge error';</script>";
}

echo "</div></div>";

// ============================================================================
// 7. SISTEMA DE CONTRATOS
// ============================================================================
echo "<div class='section'>";
echo "<div class='section-header' onclick='toggleSection(this)'>";
echo "<span class='collapse-toggle'>▼</span>";
echo "<span class='icon'>📄</span>";
echo "<span>Sistema de Contratos</span>";
echo "<span class='badge info' id='badge-contracts'>Verificando...</span>";
echo "</div>";
echo "<div class='section-content'>";

$contractsPassed = 0;
$contractsTotal = 0;

try {
    use App\Services\ContractService;

    $contractService = new ContractService();

    // Verificar métodos críticos
    $contractMethods = [
        'create' => 'Crear contrato',
        'getById' => 'Obtener contrato por ID',
        'listByAdmin' => 'Listar contratos por admin',
        'getStats' => 'Obtener estadísticas',
        'cancel' => 'Cancelar contrato',
        'delete' => 'Eliminar contrato',
    ];

    foreach ($contractMethods as $method => $desc) {
        $contractsTotal++;
        $exists = method_exists($contractService, $method);
        testResult($exists, $desc, $exists ? "✓ Método {$method}() disponible" : "❌ Falta método {$method}()");
        if ($exists) $contractsPassed++;
    }

    // Estadísticas de contratos
    if (isset($db)) {
        $stats = $db->fetchOne("
            SELECT
                COUNT(*) as total,
                SUM(CASE WHEN estado = 'pendiente' THEN 1 ELSE 0 END) as pendientes,
                SUM(CASE WHEN estado = 'firmado' THEN 1 ELSE 0 END) as firmados,
                SUM(CASE WHEN estado = 'expirado' THEN 1 ELSE 0 END) as expirados,
                SUM(CASE WHEN estado = 'cancelado' THEN 1 ELSE 0 END) as cancelados
            FROM contracts
        ");

        echo "<div class='test-item info'>";
        echo "<div class='icon'>📊</div>";
        echo "<div class='content'>";
        echo "<div class='title'>Estadísticas de Contratos</div>";
        echo "<table>";
        echo "<tr><th>Estado</th><th>Cantidad</th></tr>";
        echo "<tr><td>Pendientes</td><td>{$stats['pendientes']}</td></tr>";
        echo "<tr><td>Firmados</td><td>{$stats['firmados']}</td></tr>";
        echo "<tr><td>Expirados</td><td>{$stats['expirados']}</td></tr>";
        echo "<tr><td>Cancelados</td><td>{$stats['cancelados']}</td></tr>";
        echo "<tr style='font-weight:bold'><td>Total</td><td>{$stats['total']}</td></tr>";
        echo "</table>";
        echo "</div></div>";
    }

    echo "<script>document.getElementById('badge-contracts').textContent = '{$contractsPassed}/{$contractsTotal}'; document.getElementById('badge-contracts').className = 'badge " . ($contractsPassed === $contractsTotal ? 'success' : 'error') . "';</script>";

} catch (Exception $e) {
    testResult(false, 'Sistema de contratos', "❌ Error crítico: " . $e->getMessage());
    echo "<script>document.getElementById('badge-contracts').textContent = '0/1'; document.getElementById('badge-contracts').className = 'badge error';</script>";
}

echo "</div></div>";

// ============================================================================
// 8. SISTEMA DE FIRMAS
// ============================================================================
echo "<div class='section'>";
echo "<div class='section-header' onclick='toggleSection(this)'>";
echo "<span class='collapse-toggle'>▼</span>";
echo "<span class='icon'>✍️</span>";
echo "<span>Sistema de Firmas Digitales</span>";
echo "<span class='badge info' id='badge-signatures'>Verificando...</span>";
echo "</div>";
echo "<div class='section-content'>";

$signaturesPassed = 0;
$signaturesTotal = 0;

try {
    use App\Services\SignatureService;

    $signatureService = new SignatureService();

    // Verificar métodos críticos
    $signatureMethods = [
        'createSignature' => 'Crear firma',
        'getByContract' => 'Obtener firma por contrato',
        'validateFiles' => 'Validar archivos de firma',
    ];

    foreach ($signatureMethods as $method => $desc) {
        $signaturesTotal++;
        $exists = method_exists($signatureService, $method);
        testResult($exists, $desc, $exists ? "✓ Método {$method}() disponible" : "❌ Falta método {$method}()");
        if ($exists) $signaturesPassed++;
    }

    // Estadísticas de firmas
    if (isset($db)) {
        $sigStats = $db->fetchOne("SELECT COUNT(*) as total FROM signatures");
        $docTypes = $db->query("SELECT tipo_documento, COUNT(*) as total FROM signatures GROUP BY tipo_documento ORDER BY total DESC");

        echo "<div class='test-item info'>";
        echo "<div class='icon'>📊</div>";
        echo "<div class='content'>";
        echo "<div class='title'>Estadísticas de Firmas - Total: {$sigStats['total']}</div>";

        if (!empty($docTypes)) {
            echo "<table>";
            echo "<tr><th>Tipo Documento</th><th>Cantidad</th></tr>";
            foreach ($docTypes as $type) {
                echo "<tr><td>{$type['tipo_documento']}</td><td>{$type['total']}</td></tr>";
            }
            echo "</table>";
        }

        echo "</div></div>";
    }

    echo "<script>document.getElementById('badge-signatures').textContent = '{$signaturesPassed}/{$signaturesTotal}'; document.getElementById('badge-signatures').className = 'badge " . ($signaturesPassed === $signaturesTotal ? 'success' : 'error') . "';</script>";

} catch (Exception $e) {
    testResult(false, 'Sistema de firmas', "❌ Error crítico: " . $e->getMessage());
    echo "<script>document.getElementById('badge-signatures').textContent = '0/1'; document.getElementById('badge-signatures').className = 'badge error';</script>";
}

echo "</div></div>";

// ============================================================================
// 9. SISTEMA DE LOGS Y AUDITORÍA
// ============================================================================
echo "<div class='section'>";
echo "<div class='section-header' onclick='toggleSection(this)'>";
echo "<span class='collapse-toggle'>▼</span>";
echo "<span class='icon'>📝</span>";
echo "<span>Sistema de Logs y Auditoría</span>";
echo "<span class='badge info' id='badge-logs'>Verificando...</span>";
echo "</div>";
echo "<div class='section-content'>";

$logsPassed = 0;
$logsTotal = 0;

try {
    use App\Services\Logger;

    $logger = new Logger();

    // Verificar métodos de logging
    $logsTotal++;
    $hasLogMethod = method_exists($logger, 'log');
    testResult($hasLogMethod, 'Método de logging general', $hasLogMethod ? '✓ Sistema de logging disponible' : '❌ Falta implementación');
    if ($hasLogMethod) $logsPassed++;

    $logsTotal++;
    $hasLogSecurity = method_exists($logger, 'logSecurity');
    testResult($hasLogSecurity, 'Logging de seguridad', $hasLogSecurity ? '✓ Logging de eventos de seguridad disponible' : '❌ Falta implementación');
    if ($hasLogSecurity) $logsPassed++;

    $logsTotal++;
    $hasLogAdmin = method_exists($logger, 'logAdminAccess');
    testResult($hasLogAdmin, 'Logging de acceso admin', $hasLogAdmin ? '✓ Logging de accesos administrativos disponible' : '❌ Falta implementación');
    if ($hasLogAdmin) $logsPassed++;

    // Estadísticas de logs
    if (isset($db)) {
        $logStats = $db->query("
            SELECT
                tipo,
                COUNT(*) as total,
                MAX(created_at) as ultimo
            FROM access_logs
            GROUP BY tipo
            ORDER BY total DESC
        ");

        if (!empty($logStats)) {
            echo "<div class='test-item info'>";
            echo "<div class='icon'>📊</div>";
            echo "<div class='content'>";
            echo "<div class='title'>Estadísticas de Logs</div>";
            echo "<table>";
            echo "<tr><th>Tipo</th><th>Total</th><th>Último Registro</th></tr>";

            foreach ($logStats as $stat) {
                echo "<tr>";
                echo "<td>" . ucfirst($stat['tipo']) . "</td>";
                echo "<td>{$stat['total']}</td>";
                echo "<td>{$stat['ultimo']}</td>";
                echo "</tr>";
            }

            echo "</table>";
            echo "</div></div>";
        }

        // Últimos eventos de seguridad
        $securityLogs = $db->query("
            SELECT accion, descripcion, created_at, nivel
            FROM access_logs
            WHERE tipo = 'security'
            ORDER BY created_at DESC
            LIMIT 5
        ");

        if (!empty($securityLogs)) {
            echo "<div class='test-item warning'>";
            echo "<div class='icon'>🔍</div>";
            echo "<div class='content'>";
            echo "<div class='title'>Últimos Eventos de Seguridad (5)</div>";
            echo "<table>";
            echo "<tr><th>Acción</th><th>Descripción</th><th>Nivel</th><th>Fecha</th></tr>";

            foreach ($securityLogs as $log) {
                $nivelClass = $log['nivel'] === 'warning' ? 'warning' : ($log['nivel'] === 'error' ? 'error' : 'info');
                echo "<tr class='{$nivelClass}'>";
                echo "<td>{$log['accion']}</td>";
                echo "<td>" . htmlspecialchars($log['descripcion']) . "</td>";
                echo "<td>" . strtoupper($log['nivel']) . "</td>";
                echo "<td>{$log['created_at']}</td>";
                echo "</tr>";
            }

            echo "</table>";
            echo "</div></div>";
        }
    }

    echo "<script>document.getElementById('badge-logs').textContent = '{$logsPassed}/{$logsTotal}'; document.getElementById('badge-logs').className = 'badge " . ($logsPassed === $logsTotal ? 'success' : 'error') . "';</script>";

} catch (Exception $e) {
    testResult(false, 'Sistema de logs', "❌ Error crítico: " . $e->getMessage());
    echo "<script>document.getElementById('badge-logs').textContent = '0/1'; document.getElementById('badge-logs').className = 'badge error';</script>";
}

echo "</div></div>";

// ============================================================================
// RESUMEN FINAL
// ============================================================================
$successRate = $totalTests > 0 ? round(($passedTests / $totalTests) * 100, 1) : 0;

?>

        <div class="stats">
            <div class="stat-card success">
                <div class="number"><?= $passedTests ?></div>
                <div class="label">Tests Exitosos</div>
            </div>

            <div class="stat-card error">
                <div class="number"><?= $failedTests ?></div>
                <div class="label">Tests Fallidos</div>
            </div>

            <div class="stat-card warning">
                <div class="number"><?= $warningTests ?></div>
                <div class="label">Advertencias</div>
            </div>

            <div class="stat-card info">
                <div class="number"><?= $successRate ?>%</div>
                <div class="label">Tasa de Éxito</div>
            </div>
        </div>

        <div style="padding: 30px; text-align: center; background: #f9fafb; border-top: 2px solid #e5e7eb;">
            <h2 style="margin-bottom: 15px;">
                <?php if ($successRate >= 90): ?>
                    ✅ Sistema funcionando correctamente
                <?php elseif ($successRate >= 70): ?>
                    ⚠️ Sistema funcional con advertencias
                <?php else: ?>
                    ❌ Sistema requiere atención inmediata
                <?php endif; ?>
            </h2>

            <div class="progress-bar" style="max-width: 600px; margin: 20px auto;">
                <div class="progress-fill" style="width: <?= $successRate ?>%"></div>
            </div>

            <p style="color: #6b7280; margin-top: 15px;">
                Total de tests ejecutados: <strong><?= $totalTests ?></strong><br>
                Generado el: <strong><?= date('Y-m-d H:i:s') ?></strong>
            </p>

            <?php if ($failedTests > 0): ?>
            <div style="margin-top: 20px; padding: 15px; background: #fef2f2; border: 1px solid #fecaca; border-radius: 8px; max-width: 600px; margin: 20px auto;">
                <p style="color: #991b1b; font-weight: 600;">
                    ⚠️ Se encontraron <?= $failedTests ?> problema(s) que requieren atención
                </p>
            </div>
            <?php endif; ?>
        </div>
    </div>

    <script>
        function toggleSection(header) {
            const section = header.parentElement;
            section.classList.toggle('collapsed');
        }

        // Auto-scroll a la primera sección con errores
        window.addEventListener('load', function() {
            const errorSection = document.querySelector('.section-header .badge.error');
            if (errorSection) {
                errorSection.closest('.section').scrollIntoView({ behavior: 'smooth', block: 'center' });
            }
        });
    </script>
</body>
</html>
