<?php
require __DIR__ . '/../bootstrap.php';

use Gestoreasy\Core\Tenant\ConnectionManager;
use Gestoreasy\Core\Security\Crypto;

$userId = isset($argv[1]) ? (int)$argv[1] : 1;
$period = isset($argv[2]) ? (int)$argv[2] : 30;
function hotp(string $key, int $counter, int $digits = 6): string {
    $binCounter = pack('N*', 0) . pack('N*', $counter);
    $hash = hash_hmac('sha1', $binCounter, $key, true);
    $offset = ord($hash[19]) & 0x0F;
    $truncated = ((ord($hash[$offset]) & 0x7F) << 24) |
        (ord($hash[$offset + 1]) << 16) |
        (ord($hash[$offset + 2]) << 8) |
        (ord($hash[$offset + 3]));
    $code = $truncated % 1000000;
    return str_pad((string)$code, 6, '0', STR_PAD_LEFT);
}

function totp(string $key, int $period = 30, int $digits = 6, ?int $now = null): array {
    $now = $now ?? time();
    $counter = (int)floor($now / $period);
    return [
        'counter' => $counter,
        't-1' => hotp($key, $counter-1, $digits),
        't0' => hotp($key, $counter, $digits),
        't+1' => hotp($key, $counter+1, $digits),
    ];
}

try {
    $pdo = ConnectionManager::forTenant('default');
    $stmt = $pdo->prepare('SELECT * FROM user_mfa WHERE user_id = ? LIMIT 1');
    $stmt->execute([$userId]);
    $row = $stmt->fetch();
    if (!$row) { echo json_encode(['error' => 'no-record']); exit(1); }
    $data = Crypto::decryptJson($row['secret_enc'], $row['secret_iv'], $row['secret_tag'], $row['kdf_salt']);
    $secretB64 = $data['secret'];
    $secretBin = base64_decode($secretB64, true);
    $codes = totp($secretBin, $period, 6);
    echo json_encode(['enabled' => (bool)$row['enabled'], 'codes' => $codes], JSON_UNESCAPED_UNICODE) . "\n";
} catch (Throwable $e) {
    echo json_encode(['error' => $e->getMessage()], JSON_UNESCAPED_UNICODE) . "\n";
}