<?php

declare(strict_types=1);

final class Paystack
{
    public static function initializeTransaction(array $paystackConfig, array $payload): array
    {
        $ch = curl_init('https://api.paystack.co/transaction/initialize');
        curl_setopt_array($ch, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_POST => true,
            CURLOPT_HTTPHEADER => [
                'Authorization: Bearer ' . $paystackConfig['secret_key'],
                'Content-Type: application/json',
            ],
            CURLOPT_POSTFIELDS => json_encode($payload, JSON_UNESCAPED_SLASHES),
            CURLOPT_TIMEOUT => 30,
        ]);

        $resp = curl_exec($ch);
        if ($resp === false) {
            $err = curl_error($ch);
            curl_close($ch);
            throw new RuntimeException('Paystack error: ' . $err);
        }

        $status = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

        $decoded = json_decode($resp, true);
        if (!is_array($decoded)) {
            throw new RuntimeException('Paystack invalid response');
        }
        if ($status < 200 || $status >= 300 || empty($decoded['status'])) {
            $msg = $decoded['message'] ?? 'Paystack request failed';
            throw new RuntimeException($msg);
        }

        return $decoded;
    }

    public static function verifyWebhookSignature(string $secret, string $rawBody, string $signature): bool
    {
        $hash = hash_hmac('sha512', $rawBody, $secret);
        return hash_equals($hash, $signature);
    }
}
