<?php
/**
 * Copyright © Simplyin. All rights reserved.
 */
declare(strict_types=1);

namespace Simplyin\Payment\Model\Auth;

/**
 * Inbound payment-webhook HMAC verifier (SIN-1477). Byte-for-byte identical to SIN.CORE and the
 * WooCommerce receiver:
 *
 *   signature = hex( HMAC-SHA256( "{timestamp}.{rawBody}", secret ) )
 *
 * carried in `x-simplyin-webhook-signature`, with the Unix-seconds `x-simplyin-webhook-timestamp`
 * that was signed into the payload. (This replaces the plugin's previous, non-matching
 * `sha256(body . secret)` scheme.)
 *
 * Pure and side-effect free so it can be unit-tested against the cross-repo golden vector.
 */
class WebhookSignatureVerifier
{
    /** Replay window in seconds (±) around the signed timestamp. */
    private const FRESHNESS_WINDOW_SECONDS = 900;

    /**
     * Verify a webhook signature.
     *
     * @param string $rawBody Exact request body bytes.
     * @param string $timestamp Value of the x-simplyin-webhook-timestamp header.
     * @param string $signature Value of the x-simplyin-webhook-signature header (hex).
     * @param string $secret Decrypted per-shop signing secret.
     * @return bool
     */
    public function verify(string $rawBody, string $timestamp, string $signature, string $secret): bool
    {
        if ($secret === '' || $signature === '' || $timestamp === '') {
            return false;
        }

        // Signature must be a 64-char SHA-256 hex digest. Normalize case before comparison:
        // hash_equals() is case-sensitive while hash_hmac() emits lowercase.
        if (strlen($signature) !== 64 || !ctype_xdigit($signature)) {
            return false;
        }
        $signature = strtolower($signature);

        // Timestamp must be a plain integer string — the exact bytes the HMAC was computed over.
        if (!ctype_digit($timestamp) || strlen($timestamp) > 20) {
            return false;
        }
        if (abs(time() - (int)$timestamp) > self::FRESHNESS_WINDOW_SECONDS) {
            return false;
        }

        $expected = hash_hmac('sha256', $timestamp . '.' . $rawBody, $secret);

        return hash_equals($expected, $signature);
    }
}
