<?php
/**
 * Sign Officially API client for PHP 8.1+ (curl extension).
 *
 *   require 'SignOfficially.php';
 *   $so = new SignOfficially\Client('so_live_...');
 *   $env = $so->sendPdf('contract.pdf', ['signers' => [['name' => 'Emily Carter', 'email' => 'emily@example.com']]]);
 *
 * Docs: https://signofficially.com/developers
 */
declare(strict_types=1);

namespace SignOfficially;

final class ApiError extends \RuntimeException
{
    public function __construct(public readonly int $status, public readonly string $errorCode, string $message)
    {
        parent::__construct($status . ' ' . $errorCode . ': ' . $message);
    }
}

final class Client
{
    public const VERSION = '1.0.0';
    private string $base;

    public function __construct(private string $apiKey, string $baseUrl = 'https://signofficially.com', private int $timeout = 60)
    {
        if (!str_starts_with($apiKey, 'so_live_') && !str_starts_with($apiKey, 'so_test_')) {
            throw new \InvalidArgumentException('API keys start with so_live_ (or so_test_ for the sandbox)');
        }
        $this->base = rtrim($baseUrl, '/');
    }

    /** @param array|string|null $body array = JSON, string = raw (with $contentType) */
    public function request(string $method, string $path, array|null $body = null, bool $raw = false, ?array $multipart = null): mixed
    {
        $ch = curl_init($this->base . $path);
        $headers = ['Authorization: Bearer ' . $this->apiKey, 'Accept: application/json', 'User-Agent: signofficially-php/' . self::VERSION];
        curl_setopt_array($ch, [CURLOPT_CUSTOMREQUEST => $method, CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => $this->timeout]);
        if ($multipart !== null) {
            curl_setopt($ch, CURLOPT_POSTFIELDS, $multipart);
        } elseif ($body !== null) {
            $headers[] = 'Content-Type: application/json';
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($body ?: new \stdClass()));
        }
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        $out = curl_exec($ch);
        $status = (int)curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
        $err = curl_error($ch);
        curl_close($ch);
        if ($out === false) {
            throw new ApiError(0, 'network', $err);
        }
        if ($status < 200 || $status >= 300) {
            $d = json_decode((string)$out, true) ?: [];
            throw new ApiError($status, (string)($d['error'] ?? 'http_error'), (string)($d['message'] ?? 'HTTP ' . $status));
        }
        return $raw ? $out : (json_decode((string)$out, true) ?? []);
    }

    private static function file(string $pdf): \CURLFile|\CURLStringFile
    {
        return is_file($pdf) ? new \CURLFile($pdf, 'application/pdf', basename($pdf)) : new \CURLStringFile($pdf, 'document.pdf', 'application/pdf');
    }

    public function me(): array { return $this->request('GET', '/v1/me'); }
    public function templates(): array { return $this->request('GET', '/v1/templates')['data']; }
    public function listEnvelopes(?string $status = null): array { return $this->request('GET', '/v1/envelopes' . ($status ? '?status=' . rawurlencode($status) : ''))['data']; }
    public function getEnvelope(string $id): array { return $this->request('GET', '/v1/envelopes/' . rawurlencode($id)); }

    /** $recipients: ['roleRef' => ['name' => ..., 'email' => ...]]; $options: title, message, variables, send_at, ... */
    public function sendTemplate(string $template, array $recipients, array $options = []): array
    {
        return $this->request('POST', '/v1/envelopes', ['template' => $template, 'recipients' => $recipients] + $options);
    }

    /** $pdf: a file path or the PDF bytes. $meta: signers [[name, email]] or recipients + fields, plus title, message, ... */
    public function sendPdf(string $pdf, array $meta): array
    {
        if (!isset($meta['recipients'])) {
            $meta['recipients'] = array_map(fn($s, $i) => ['ref' => 's' . ($i + 1), 'name' => $s['name'], 'email' => $s['email'], 'role' => 'signer', 'order' => $i + 1], $meta['signers'] ?? [], array_keys($meta['signers'] ?? []));
        }
        unset($meta['signers']);
        return $this->request('POST', '/v1/envelopes', null, false, ['meta' => json_encode($meta), 'file' => self::file($pdf)]);
    }

    public function remind(string $id): array { return $this->request('POST', '/v1/envelopes/' . rawurlencode($id) . '/remind', []); }
    public function void(string $id, string $reason = 'Cancelled'): array { return $this->request('POST', '/v1/envelopes/' . rawurlencode($id) . '/void', ['reason' => $reason]); }
    /** The sealed signed PDF bytes. */
    public function signedPdf(string $id): string { return $this->request('GET', '/v1/envelopes/' . rawurlencode($id) . '/final.pdf', null, true); }
    public function audit(string $id): array { return $this->request('GET', '/v1/envelopes/' . rawurlencode($id) . '/audit'); }
    public function comments(string $id): array { return $this->request('GET', '/v1/envelopes/' . rawurlencode($id) . '/comments')['data']; }
    public function addComment(string $id, string $body): array { return $this->request('POST', '/v1/envelopes/' . rawurlencode($id) . '/comments', ['body' => $body])['data']; }

    /** Emails test documents would have sent, with their signing links (test keys only). */
    public function sandboxEmails(): array { return $this->request('GET', '/v1/sandbox/emails')['data']; }

    public function signingUrl(string $id, string $recipientId, int $expiresSeconds = 600, ?string $redirectUrl = null): array
    {
        return $this->request('POST', '/v1/envelopes/' . rawurlencode($id) . '/recipients/' . rawurlencode($recipientId) . '/signing-url', ['expires_seconds' => $expiresSeconds] + ($redirectUrl ? ['redirect_url' => $redirectUrl] : []));
    }

    /** One-time link to the sending screen. $options: pdf (path or bytes), template, recipients, title, message, expires_seconds. */
    public function senderView(string $returnUrl, array $options = []): array
    {
        $pdf = $options['pdf'] ?? null;
        unset($options['pdf']);
        $meta = ['return_url' => $returnUrl] + $options;
        return $pdf === null ? $this->request('POST', '/v1/sender-views', $meta)
            : $this->request('POST', '/v1/sender-views', null, false, ['meta' => json_encode($meta), 'file' => self::file($pdf)]);
    }

    public function contracts(string $filter = 'all', string $q = ''): array { return $this->request('GET', '/v1/contracts?' . http_build_query(['filter' => $filter, 'q' => $q]))['data']; }
    public function getContract(string $id): ?array { return $this->request('GET', '/v1/envelopes/' . rawurlencode($id) . '/contract')['data']; }
    public function setContract(string $id, array $terms): array { return $this->request('POST', '/v1/envelopes/' . rawurlencode($id) . '/contract', $terms)['data']; }

    /** True when an X-SignOfficially-Signature header matches the raw request body. */
    public static function verifyWebhook(string $rawBody, string $signatureHeader, string $secret, int $tolerance = 300): bool
    {
        $parts = [];
        foreach (explode(',', $signatureHeader) as $p) {
            [$k, $v] = array_pad(explode('=', $p, 2), 2, '');
            $parts[$k] = $v;
        }
        $ts = (int)($parts['t'] ?? 0);
        if (!$ts || abs(time() - $ts) > $tolerance || empty($parts['v1'])) {
            return false;
        }
        return hash_equals(hash_hmac('sha256', $ts . '.' . $rawBody, $secret), $parts['v1']);
    }
}
