<?php
class VYC_Altcha {

    private static function key(): string {
        return getenv('ALTCHA_HMAC_KEY') ?: '';
    }

    public static function is_enabled(): bool {
        return !empty(self::key());
    }

    public static function create_challenge(int $maxnumber = 100000): array {
        $salt      = bin2hex(random_bytes(12));
        $number    = random_int(0, $maxnumber);
        $challenge = hash('sha256', $salt . $number);
        $signature = hash_hmac('sha256', $challenge, self::key());
        return [
            'algorithm' => 'SHA-256',
            'challenge' => $challenge,
            'maxnumber' => $maxnumber,
            'salt'      => $salt,
            'signature' => $signature,
        ];
    }

    public static function verify(string $payload): bool {
        if (!self::is_enabled()) return true;
        if (empty($payload)) return false;

        $data = json_decode(base64_decode($payload, true), true);
        if (!is_array($data)) return false;

        foreach (['algorithm', 'challenge', 'number', 'salt', 'signature'] as $key) {
            if (!isset($data[$key])) return false;
        }

        if ($data['algorithm'] !== 'SHA-256') return false;

        $expected_sig = hash_hmac('sha256', $data['challenge'], self::key());
        if (!hash_equals($expected_sig, $data['signature'])) return false;

        $expected_challenge = hash('sha256', $data['salt'] . $data['number']);
        return hash_equals($expected_challenge, $data['challenge']);
    }
}
