<?php
/**
 * BymPay SDK для PHP 7.4+ (нужно расширение curl).
 *
 *   require 'BymPay.php';
 *   $bym = new BymPay(getenv('BYMPAY_KEY'));
 *   $invoice = $bym->createInvoice(1500, 'Заказ №42', ['order_id' => '42'], 'order-42');
 *   header('Location: ' . $invoice['url']);
 *
 *   // уведомление:
 *   $event = BymPay::parseWebhook(file_get_contents('php://input'), $_SERVER['HTTP_BYMPAY_SIGNATURE'] ?? '', getenv('BYMPAY_WEBHOOK_SECRET'));
 */
class BymPay
{
    private $apiKey;
    private $baseUrl;

    public function __construct(string $apiKey, string $baseUrl = 'https://bympay.com')
    {
        if ($apiKey === '') {
            throw new InvalidArgumentException('BymPay: нужен ключ API');
        }
        $this->apiKey = $apiKey;
        $this->baseUrl = rtrim($baseUrl, '/');
    }

    private function request(string $method, string $path, ?array $body = null, ?string $idempotencyKey = null): array
    {
        $ch = curl_init($this->baseUrl . $path);
        $headers = ['Authorization: Bearer ' . $this->apiKey, 'Content-Type: application/json'];
        if ($idempotencyKey) {
            $headers[] = 'Idempotency-Key: ' . $idempotencyKey;
        }
        curl_setopt_array($ch, [
            CURLOPT_CUSTOMREQUEST => $method,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_HTTPHEADER => $headers,
            CURLOPT_TIMEOUT => 20,
        ]);
        if ($body !== null) {
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($body, JSON_UNESCAPED_UNICODE));
        }
        $raw = curl_exec($ch);
        if ($raw === false) {
            throw new RuntimeException('BymPay недоступен: ' . curl_error($ch));
        }
        $status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        $data = json_decode($raw, true) ?: [];
        if ($status >= 400) {
            throw new RuntimeException('BymPay: ' . ($data['error']['message'] ?? ('ошибка ' . $status)), $status);
        }
        return $data;
    }

    public function createInvoice(float $amount, string $description, array $metadata = [], ?string $idempotencyKey = null, string $currency = 'RUB', ?string $partnerId = null): array
    {
        $body = ['amount' => $amount, 'currency' => $currency, 'description' => $description, 'metadata' => $metadata];
        if ($partnerId) $body['partner_id'] = $partnerId; // ID платформы-партнёра
        return $this->request('POST', '/api/v1/invoices', $body, $idempotencyKey);
    }

    public function getInvoice(string $id): array
    {
        return $this->request('GET', '/api/v1/invoices/' . rawurlencode($id));
    }

    public static function parseWebhook(string $rawBody, string $signatureHeader, string $secret, int $toleranceSec = 300): array
    {
        parse_str(str_replace(',', '&', $signatureHeader), $sig);
        $t = isset($sig['t']) ? (int) $sig['t'] : 0;
        if (!$t || empty($sig['v1']) || abs(time() - $t) > $toleranceSec) {
            throw new RuntimeException('BymPay: подпись устарела или отсутствует');
        }
        if (!hash_equals(hash_hmac('sha256', $t . '.' . $rawBody, $secret), $sig['v1'])) {
            throw new RuntimeException('BymPay: неверная подпись');
        }
        return json_decode($rawBody, true);
    }
}
