<?php
session_start();
error_reporting(E_ALL);
ini_set('display_errors', 1); // Esto nos dirá el error exacto si vuelve a fallar

// 1. Cargar configuración
$configPath = __DIR__ . '/../config/settings.php';
if (!file_exists($configPath)) {
    die("Error: No se encontró el archivo de configuración en: " . $configPath);
}
require_once($configPath);

// 2. Definición de la Clase (Para evitar el Error 500 por falta de archivo)
class GoogleAuthenticator {
    protected $_codeLength = 6;
    public function getCode($secret, $timeSlice = null) {
        if ($timeSlice === null) { $timeSlice = floor(time() / 30); }
        $secretkey = $this->_base32Decode($secret);
        $time = chr(0).chr(0).chr(0).chr(0).pack('N*', $timeSlice);
        $hm = hash_hmac('SHA1', $time, $secretkey, true);
        $offset = ord(substr($hm, -1)) & 0x0F;
        $hashpart = substr($hm, $offset, 4);
        $value = unpack('N', $hashpart);
        $value = $value[1] & 0x7FFFFFFF;
        return str_pad($value % pow(10, $this->_codeLength), $this->_codeLength, '0', STR_PAD_LEFT);
    }
    public function verifyCode($secret, $code, $discrepancy = 1440) {
        $currentTimeSlice = floor(time() / 30);
        for ($i = -$discrepancy; $i <= $discrepancy; $i++) {
            if ($this->getCode($secret, $currentTimeSlice + $i) == $code) { return true; }
        }
        return false;
    }
    protected function _base32Decode($secret) {
        if (empty($secret)) return '';
        $base32chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
        $base32charsFlipped = array_flip(str_split($base32chars));
        $secret = str_replace('=','', strtoupper($secret));
        $secret = str_split($secret);
        $binaryString = "";
        for ($i = 0; $i < count($secret); $i = $i+8) {
            $x = "";
            for ($j = 0; $j < 8; $j++) { $x .= str_pad(base_convert(@$base32charsFlipped[@$secret[$i+$j]], 10, 2), 5, '0', STR_PAD_LEFT); }
            $eightBits = str_split($x, 8);
            for ($z = 0; $z < count($eightBits); $z++) { $binaryString .= ( ($y = chr(base_convert($eightBits[$z], 2, 10))) || ord($y) == 48 ) ? $y : ""; }
        }
        return $binaryString;
    }
}

// 3. Lógica de Verificación
$error = null;
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        $code = str_replace(' ', '', $_POST['code']);
        $adminUser = $db_settings['admin_user'] ?? 'Admin';

        $dsn = "dblib:host={$db_settings['host']};dbname={$db_settings['name']};charset=UTF8";
        $pdo = new PDO($dsn, $db_settings['user'], $db_settings['pass']);
        $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

        $stmt = $pdo->prepare("SELECT google_2fa_secret FROM MEMB_INFO WHERE memb___id = ?");
        $stmt->execute([$adminUser]);
        $user = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($user && !empty($user['google_2fa_secret'])) {
            $ga = new GoogleAuthenticator();
            // Mantenemos la tolerancia de 12 horas (1440 intervalos)
            if ($ga->verifyCode($user['google_2fa_secret'], $code, 1440)) {
                $_SESSION['2fa_verified'] = true;
                header("Location: index.php");
                exit;
            } else {
                $error = "CRISTAL INCORRECTO: El código no coincide.";
            }
        } else {
            $error = "ERROR: No hay un secreto 2FA registrado para el admin.";
        }
    } catch (Exception $e) {
        $error = "Error de Conexión: " . $e->getMessage();
    }
}
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <title>Master Core - Blindaje 2FA</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://fonts.googleapis.com/css2?family=Cinzel:wght@700&display=swap" rel="stylesheet">
    <style>
        body { background: radial-gradient(circle, #1a0505 0%, #050505 100%); color: #e6d6c6; height: 100vh; display: flex; align-items: center; justify-content: center; overflow: hidden; }
        .carnelian-card { background: rgba(20, 5, 5, 0.9); border: 1px solid #d4af37; box-shadow: 0 0 40px rgba(212, 175, 55, 0.1); border-radius: 30px; }
        .gold-text { color: #d4af37; font-family: 'Cinzel', serif; text-shadow: 0 0 10px rgba(212, 175, 55, 0.3); }
        .red-gem { color: #ff0000; filter: drop-shadow(0 0 8px #ff0000); }
        .input-code { background: rgba(0,0,0,0.5); border: 1px solid rgba(212, 175, 55, 0.3); color: white; outline: none; transition: 0.3s; }
        .input-code:focus { border-color: #d4af37; box-shadow: 0 0 15px rgba(212, 175, 55, 0.2); }
    </style>
</head>
<body>
    <div class="carnelian-card p-10 max-w-sm w-full text-center">
        <div class="mb-6">
            <span class="red-gem text-3xl">♦</span>
            <h1 class="gold-text text-xl tracking-[0.2em] mt-2">AUTENTICACIÓN</h1>
        </div>

        <?php if($error): ?>
            <div class="mb-6 p-3 bg-red-600/10 border border-red-600/40 rounded-xl text-red-500 text-[10px] font-bold uppercase">
                <?php echo $error; ?>
            </div>
        <?php endif; ?>

        <form method="POST">
            <p class="text-[9px] uppercase tracking-widest text-gray-500 mb-6">Introduce el código sagrado</p>
            <input type="text" name="code" maxlength="6" autocomplete="off" autofocus
                   class="input-code w-full p-4 rounded-2xl text-center text-4xl font-bold tracking-[0.3em] mb-8">
            
            <button type="submit" class="w-full bg-gradient-to-r from-[#d4af37] to-[#a67c00] text-black font-black py-4 rounded-xl text-[10px] uppercase tracking-widest hover:brightness-125 transition">
                Validar Blindaje
            </button>
        </form>
    </div>
</body>
</html>