<?php
/**
 * Steam Guard code generator (time-based, 30s steps)
 * Based on shared_secret (base64 string from Steam).
 * Note: strict_types declared in main file
 */

function steam_guard_code(string $shared_secret_b64): string {
    $secret = base64_decode($shared_secret_b64, true);
    if ($secret === false) return 'ERROR';
    $time = floor(time() / 30);
    $b = pack('N*', 0) . pack('N*', $time);
    $hmac = hash_hmac('sha1', $b, $secret, true);
    $offset = ord(substr($hmac, -1)) & 0x0F;
    $otp = (ord($hmac[$offset]) & 0x7F) << 24 |
           (ord($hmac[$offset+1]) & 0xFF) << 16 |
           (ord($hmac[$offset+2]) & 0xFF) << 8  |
           (ord($hmac[$offset+3]) & 0xFF);
    $chars = '23456789BCDFGHJKMNPQRTVWXY';
    $code = '';
    for ($i = 0; $i < 5; $i++) {
        $code .= $chars[$otp % strlen($chars)];
        $otp = intdiv($otp, strlen($chars));
    }
    return $code;
}
