<?php

declare(strict_types=1);

namespace HBank;

/**
 * HBank's callback: right before charging a customer, HBank POSTs the payment to its callback URL and charges only if
 * you answer 200 with {"resume": true} as application/json within 10 seconds.
 *
 * It's signed: check the HBank-Signature header with your business's signing secret (business settings → Callback URLs)
 * before you approve: fromRequest($secret) does, or verifySignature(). Also check that `id` and `amount` match an order
 * you created, and confirm with getPayment() before handing out goods.
 *
 *     // Plain PHP (refuses a callback without a valid signature)
 *     $cb = \HBank\Callback::fromRequest(getenv('HBANK_CALLBACK_SECRET'));
 *     \HBank\Callback::respond($orders->matches($cb->id, $cb->amount) ? \HBank\Callback::approve() : \HBank\Callback::refuse('Out of stock'));
 *
 *     // Laravel (exclude the route from CSRF protection)
 *     Route::post('/hbank/callback', function (Request $request) {
 *         abort_unless(\HBank\Callback::verifySignature($secret, $request->header('HBank-Signature'), $request->getContent()), 400);
 *         $cb = \HBank\Callback::parse($request->getContent());
 *         return response()->json(Order::matches($cb->id, $cb->amount) ? \HBank\Callback::approve() : \HBank\Callback::refuse('Out of stock'));
 *     });
 */
final class Callback
{
    /** $amount is the exact decimal text, e.g. "24.90"; compare it with bccomp() or your decimal type. */
    public function __construct(
        public readonly string $id,
        public readonly string $amount,
        public readonly string $currency,
        public readonly string $status,
        public readonly string $description,
    ) {
    }

    /** Reads a callback body. Throws HBankException("invalid_callback") if it isn't one. */
    public static function parse(string $body): self
    {
        // Quote bare numbers first so amounts keep their exact digits.
        $exact = preg_replace('/("amount"\s*:\s*)(-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?)/', '$1"$2"', $body);
        $d = json_decode((string) $exact, true, 16, JSON_BIGINT_AS_STRING);
        if (!is_array($d) || !isset($d['id'], $d['amount'], $d['currency']) || !(is_string($d['id']) || is_int($d['id'])) || $d['id'] === '' || !is_numeric($d['amount'])) {
            throw new HBankException('invalid_callback', 0, 'missing or invalid id, amount or currency');
        }
        return new self((string) $d['id'], (string) $d['amount'], (string) $d['currency'],
            (string) ($d['status'] ?? ''), (string) ($d['description'] ?? ''));
    }

    /**
     * Reads the current request's body (php://input). With $secret, its HBank-Signature must be valid first: otherwise
     * it throws HBankException("invalid_callback").
     */
    public static function fromRequest(?string $secret = null): self
    {
        $body = (string) file_get_contents('php://input');
        if ($secret !== null && !self::verifySignature($secret, $_SERVER['HTTP_HBANK_SIGNATURE'] ?? null, $body)) {
            throw new HBankException('invalid_callback', 0, 'bad or missing HBank-Signature');
        }
        return self::parse($body);
    }

    /**
     * Whether $header (the request's HBank-Signature: "t=<unix time>,v1=<hex>") signs $body (the raw request body, exactly
     * as received) with $secret, and was made within $tolerance seconds of $now (default: now).
     */
    public static function verifySignature(string $secret, ?string $header, string $body, int $tolerance = 300, ?int $now = null): bool
    {
        if ($secret === '' || $header === null || $header === '') {
            return false;
        }
        $parts = [];
        foreach (explode(',', $header) as $part) {
            $kv = explode('=', $part, 2);
            if (count($kv) === 2) {
                $parts[$kv[0]] ??= $kv[1];
            }
        }
        $t = $parts['t'] ?? '';
        if (!preg_match('/^\d{1,18}$/', $t) || abs(($now ?? time()) - (int) $t) > $tolerance) {
            return false;
        }
        return hash_equals(hash_hmac('sha256', $t . '.' . $body, $secret), (string) ($parts['v1'] ?? ''));
    }

    /** Lets HBank charge the customer. */
    public static function approve(): array
    {
        return ['resume' => true];
    }

    /** Refuses the payment; the customer sees $error. */
    public static function refuse(?string $error = null): array
    {
        return $error === null ? ['resume' => false] : ['resume' => false, 'error' => $error];
    }

    /** Sends the answer (status 200, application/json) for plain PHP. */
    public static function respond(array $answer): void
    {
        http_response_code(200);
        header('Content-Type: application/json');
        echo json_encode($answer, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
    }
}
