<?php
/**
 * Fix de Sesiones - Limpia sesiones huérfanas y corrige problemas
 */
error_reporting(E_ALL);
ini_set('display_errors', '1');

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

use App\Services\Database;

$db = Database::getInstance();

echo "<!DOCTYPE html><html><head><title>Fix Sesiones</title>";
echo "<style>body{font-family:monospace;padding:20px;background:#1e1e1e;color:#d4d4d4;}";
echo ".success{color:#4ec9b0;} .error{color:#f48771;} .info{color:#4fc1ff;}</style></head><body>";

echo "<h1>🔧 Fix de Sesiones</h1>";

// 1. Eliminar sesiones expiradas
echo "<h2 class='info'>1. Eliminando sesiones expiradas...</h2>";
$deleted = $db->query("DELETE FROM sessions WHERE expires_at < UTC_TIMESTAMP()");
$rowCount = $db->query("SELECT ROW_COUNT() as count")[0]['count'] ?? 0;
echo "<p class='success'>✓ Eliminadas {$rowCount} sesiones expiradas</p>";

// 2. Mostrar sesiones activas
echo "<h2 class='info'>2. Sesiones activas:</h2>";
$activeSessions = $db->query("
    SELECT s.id, s.admin_id, a.nombre, a.email, s.expires_at, s.created_at
    FROM sessions s
    LEFT JOIN admins a ON s.admin_id = a.id
    WHERE s.expires_at > UTC_TIMESTAMP()
    ORDER BY s.created_at DESC
");

if (empty($activeSessions)) {
    echo "<p class='error'>❌ No hay sesiones activas</p>";
} else {
    echo "<table border='1' cellpadding='10' style='border-collapse:collapse;color:#d4d4d4;'>";
    echo "<tr><th>ID</th><th>Usuario</th><th>Email</th><th>Expira</th><th>Creado</th></tr>";
    foreach ($activeSessions as $s) {
        echo "<tr>";
        echo "<td>" . substr($s['id'], 0, 8) . "...</td>";
        echo "<td>" . htmlspecialchars($s['nombre'] ?? 'N/A') . "</td>";
        echo "<td>" . htmlspecialchars($s['email'] ?? 'N/A') . "</td>";
        echo "<td>" . $s['expires_at'] . "</td>";
        echo "<td>" . $s['created_at'] . "</td>";
        echo "</tr>";
    }
    echo "</table>";
}

// 3. Verificar timezone
echo "<h2 class='info'>3. Verificación de Timezone:</h2>";
$phpTime = gmdate('Y-m-d H:i:s');
$mysqlUtc = $db->fetchOne("SELECT UTC_TIMESTAMP() as utc")['utc'];
echo "<p>PHP gmdate(): <strong>{$phpTime}</strong></p>";
echo "<p>MySQL UTC_TIMESTAMP(): <strong>{$mysqlUtc}</strong></p>";

$diff = abs(strtotime($phpTime) - strtotime($mysqlUtc));
if ($diff > 60) {
    echo "<p class='error'>❌ Diferencia mayor a 60 segundos: {$diff}s</p>";
} else {
    echo "<p class='success'>✓ Tiempos sincronizados (diferencia: {$diff}s)</p>";
}

echo "<hr style='margin:30px 0;border-color:#3e3e42;'>";
echo "<h2>Siguiente paso:</h2>";
echo "<ol>";
echo "<li>Las sesiones expiradas han sido limpiadas</li>";
echo "<li><a href='public/admin/login.php' style='color:#4ec9b0;'>→ Ir al Login</a></li>";
echo "<li>Intenta iniciar sesión nuevamente</li>";
echo "<li>Si el problema persiste, <a href='debug-session.php' style='color:#4ec9b0;'>→ Ejecutar debug-session.php</a></li>";
echo "</ol>";

echo "</body></html>";
