<?php
/**
 * Stard API SDK for PHP 7.4+ (ext-curl, ext-json) — v1.0.0
 * https://stard-market.ir/docs/sdks · MIT
 * Server-side only: never expose your API key.
 *
 *   require 'Stard.php';
 *   $s = new Stard\Client('sk_test_...');
 *   $order = $s->buyStars(500, '@username');
 */
namespace Stard;

class StardException extends \Exception
{
    public $status; public $type; public $errorCode; public $param; public $requestId;

    public function __construct(int $status, array $body)
    {
        $e = $body['error'] ?? [];
        parent::__construct(($e['code'] ?? 'http_' . $status) . ': ' . ($e['message'] ?? 'request failed'));
        $this->status = $status;
        $this->type = $e['type'] ?? null;
        $this->errorCode = $e['code'] ?? null;
        $this->param = $e['param'] ?? null;
        $this->requestId = $e['request_id'] ?? null;
    }
}

class Client
{
    const VERSION = '1.0.0';
    private $apiKey; private $baseUrl; private $timeout; private $maxRetries;

    public function __construct(string $apiKey, string $baseUrl = 'https://stard-market.ir/api/v1', int $timeout = 20, int $maxRetries = 2)
    {
        if (!preg_match('/^sk_(test|live)_/', $apiKey)) {
            throw new \InvalidArgumentException('Stard: a valid API key (sk_test_/sk_live_) is required');
        }
        $this->apiKey = $apiKey;
        $this->baseUrl = rtrim($baseUrl, '/');
        $this->timeout = $timeout;
        $this->maxRetries = $maxRetries;
    }

    public function request(string $method, string $path, array $query = [], ?array $body = null, ?string $idempotencyKey = null): array
    {
        $url = $this->baseUrl . $path;
        $query = array_filter($query, function ($v) { return $v !== null; });
        if ($query) { $url .= '?' . http_build_query($query); }
        $headers = ['Authorization: Bearer ' . $this->apiKey, 'Accept: application/json', 'User-Agent: stard-php/' . self::VERSION];
        $payload = null;
        if ($body !== null) {
            $payload = json_encode(array_filter($body, function ($v) { return $v !== null; }), JSON_UNESCAPED_UNICODE);
            $headers[] = 'Content-Type: application/json';
        }
        if ($method === 'POST') {
            $headers[] = 'Idempotency-Key: ' . ($idempotencyKey ?: bin2hex(random_bytes(16)));
        }
        for ($attempt = 0; ; $attempt++) {
            $ch = curl_init($url);
            curl_setopt_array($ch, [
                CURLOPT_CUSTOMREQUEST => $method, CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => $headers,
                CURLOPT_TIMEOUT => $this->timeout, CURLOPT_FOLLOWLOCATION => false,
            ]);
            if ($payload !== null) { curl_setopt($ch, CURLOPT_POSTFIELDS, $payload); }
            $raw = curl_exec($ch);
            $status = (int) curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
            $err = curl_error($ch);
            curl_close($ch);
            if ($raw === false) {
                if ($attempt < $this->maxRetries) { usleep((int) (500000 * (2 ** $attempt))); continue; }
                throw new \RuntimeException('Stard: network error: ' . $err);
            }
            $data = json_decode($raw, true) ?: [];
            if ($status >= 200 && $status < 300) { return $data; }
            if (($status === 429 || $status >= 500) && $attempt < $this->maxRetries) { usleep((int) (500000 * (2 ** $attempt))); continue; }
            throw new StardException($status, $data);
        }
    }

    public function ping(): array { return $this->request('GET', '/ping'); }
    public function prices(): array { return $this->request('GET', '/prices'); }
    public function starsPrice(int $quantity): array { return $this->request('GET', '/stars/price', ['quantity' => $quantity]); }
    public function premiumPrices(): array { return $this->request('GET', '/premium/prices'); }
    public function categories(): array { return $this->request('GET', '/categories'); }
    public function products(array $query = []): array { return $this->request('GET', '/products', $query); }
    public function product($ref): array { return $this->request('GET', '/products/' . rawurlencode((string) $ref)); }
    public function wallet(): array { return $this->request('GET', '/wallet'); }
    public function transactions(array $query = []): array { return $this->request('GET', '/transactions', $query); }

    /** $payCurrency: 'TON' | 'IRT' | null (null = the source chosen in your dashboard) */
    public function buyStars(int $quantity, string $recipient, ?string $payCurrency = null, ?array $metadata = null, ?string $idempotencyKey = null): array
    {
        return $this->request('POST', '/orders', [], ['type' => 'stars', 'quantity' => $quantity, 'recipient' => $recipient,
            'pay_currency' => $payCurrency, 'metadata' => $metadata], $idempotencyKey);
    }

    public function buyProduct(int $productId, ?string $recipient = null, ?string $giftMessage = null, ?string $payCurrency = null, ?array $metadata = null, ?string $idempotencyKey = null): array
    {
        return $this->request('POST', '/orders', [], ['type' => 'product', 'product_id' => $productId, 'recipient' => $recipient,
            'gift_message' => $giftMessage, 'pay_currency' => $payCurrency, 'metadata' => $metadata], $idempotencyKey);
    }

    public function order(string $id): array { return $this->request('GET', '/orders/' . rawurlencode($id)); }
    public function orders(array $query = []): array { return $this->request('GET', '/orders', $query); }
    public function cancelOrder(string $id): array { return $this->request('POST', '/orders/' . rawurlencode($id) . '/cancel'); }
}

/** Verify a Stard webhook. $rawBody = file_get_contents('php://input'). Returns the decoded event or throws. */
function verify_webhook(string $rawBody, string $signatureHeader, string $secret, int $tolerance = 300): array
{
    $parts = [];
    foreach (explode(',', $signatureHeader) as $p) {
        $kv = explode('=', $p, 2);
        if (count($kv) === 2) { $parts[$kv[0]] = $kv[1]; }
    }
    if (empty($parts['t']) || empty($parts['v1'])) { throw new \UnexpectedValueException('Stard webhook: malformed signature header'); }
    if (abs(time() - (int) $parts['t']) > $tolerance) { throw new \UnexpectedValueException('Stard webhook: timestamp outside tolerance'); }
    $expected = hash_hmac('sha256', $parts['t'] . '.' . $rawBody, $secret);
    if (!hash_equals($expected, $parts['v1'])) { throw new \UnexpectedValueException('Stard webhook: invalid signature'); }
    return json_decode($rawBody, true);
}
