<?php

/**
 * RFC 6238 TOTP, compatible with Microsoft Authenticator, Google Authenticator
 * and Authy. SHA1, 6 digits, 30 second steps.
 */
final class Totp
{
    private const ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567';
    public const PERIOD = 30;
    public const DIGITS = 6;

    /** A fresh base32 shared secret (160 bits). */
    public static function generateSecret(int $bytes = 20): string
    {
        return self::base32Encode(random_bytes($bytes));
    }

    /** The URI encoded into the enrollment QR code. */
    public static function provisioningUri(string $secret, string $account, string $issuer): string
    {
        $label = rawurlencode($issuer) . ':' . rawurlencode($account);
        $query = http_build_query([
            'secret'    => $secret,
            'issuer'    => $issuer,
            'algorithm' => 'SHA1',
            'digits'    => self::DIGITS,
            'period'    => self::PERIOD,
        ]);
        return "otpauth://totp/{$label}?{$query}";
    }

    public static function codeAt(string $secret, int $counter): string
    {
        $key    = self::base32Decode($secret);
        $binCtr = pack('N*', 0) . pack('N*', $counter);
        $hash   = hash_hmac('sha1', $binCtr, $key, true);
        $offset = ord($hash[19]) & 0x0f;
        $value  = ((ord($hash[$offset]) & 0x7f) << 24)
                | ((ord($hash[$offset + 1]) & 0xff) << 16)
                | ((ord($hash[$offset + 2]) & 0xff) << 8)
                | (ord($hash[$offset + 3]) & 0xff);
        return str_pad((string) ($value % (10 ** self::DIGITS)), self::DIGITS, '0', STR_PAD_LEFT);
    }

    /**
     * Verifies a code within +/- $window steps of now.
     * Returns the matched counter, or null. Compare the result against the
     * user's stored twofa_last_counter to block replay of the same code.
     */
    public static function verify(string $secret, string $code, int $window = 1): ?int
    {
        $code = preg_replace('/\D/', '', $code);
        if (strlen($code) !== self::DIGITS) {
            return null;
        }
        $now = (int) floor(time() / self::PERIOD);
        for ($i = -$window; $i <= $window; $i++) {
            if (hash_equals(self::codeAt($secret, $now + $i), $code)) {
                return $now + $i;
            }
        }
        return null;
    }

    public static function base32Encode(string $data): string
    {
        $bits = '';
        foreach (str_split($data) as $ch) {
            $bits .= str_pad(decbin(ord($ch)), 8, '0', STR_PAD_LEFT);
        }
        $out = '';
        foreach (str_split($bits, 5) as $chunk) {
            $out .= self::ALPHABET[bindec(str_pad($chunk, 5, '0', STR_PAD_RIGHT))];
        }
        return $out;
    }

    public static function base32Decode(string $b32): string
    {
        $b32  = strtoupper(rtrim($b32, '='));
        $bits = '';
        foreach (str_split($b32) as $ch) {
            $idx = strpos(self::ALPHABET, $ch);
            if ($idx === false) {
                throw new InvalidArgumentException('Invalid base32 secret');
            }
            $bits .= str_pad(decbin($idx), 5, '0', STR_PAD_LEFT);
        }
        $out = '';
        foreach (str_split($bits, 8) as $byte) {
            if (strlen($byte) === 8) {
                $out .= chr(bindec($byte));
            }
        }
        return $out;
    }
}
