<?php
/**
 * ShipPickup API: client in one file (PHP 7.4+, only the curl extension).
 *
 *   require __DIR__ . '/shippickup.php';
 *   $api = new ShipPickup();   // key: SHIPPICKUP_API_KEY environment variable
 *
 * Methods: rates(), create(), get(), cancel(), tracking(), balance(), buyCheapest(), verifyWebhook().
 * Every method returns the decoded JSON ("data" and "meta"); an error response throws ShipPickupException.
 * Documentation: https://api.shippickup.com/docs
 */
class ShipPickupException extends RuntimeException
{
    /** @var int HTTP status (0 when there was no response) */
    public $status;
    /** @var string error code from the API, for example rate_expired */
    public $errorCode;
    /** @var array details of the error (fields and reasons) */
    public $details;

    public function __construct(int $status, string $errorCode, string $message, array $details = [])
    {
        parent::__construct($message, $status);
        $this->status = $status;
        $this->errorCode = $errorCode;
        $this->details = $details;
    }
}

class ShipPickup
{
    /** @var string */
    private $key;
    /** @var string */
    private $base;

    public function __construct(?string $key = null, ?string $baseUrl = null)
    {
        $this->key = $key !== null && $key !== '' ? $key : (string) getenv('SHIPPICKUP_API_KEY');
        $envBase = (string) getenv('SHIPPICKUP_API_URL');
        $this->base = rtrim($baseUrl !== null && $baseUrl !== '' ? $baseUrl : ($envBase !== '' ? $envBase : 'https://api.shippickup.com/v1'), '/');
        if ($this->key === '') {
            throw new ShipPickupException(0, 'no_key', 'Set the SHIPPICKUP_API_KEY environment variable');
        }
    }

    /** Rates for a route and a parcel: ['from' => [...], 'to' => [...], 'parcel' => [...]]. */
    public function rates(array $request): array
    {
        return $this->call('POST', '/rates', $request);
    }

    /** Buy a label. $body: rate_id, from, to, parcel, items. $idempotencyKey: 16-64 characters, see idempotencyKey(). */
    public function create(array $body, string $idempotencyKey): array
    {
        return $this->call('POST', '/shipments', $body, ['Idempotency-Key: ' . $idempotencyKey]);
    }

    /** An order by its id or tracking number. */
    public function get(string $id): array
    {
        return $this->call('GET', '/shipments/' . rawurlencode($id));
    }

    /** Cancel an order; the money returns to the balance. */
    public function cancel(string $id, string $reason = ''): array
    {
        return $this->call('POST', '/shipments/' . rawurlencode($id) . '/cancel', $reason === '' ? new stdClass() : ['reason' => $reason]);
    }

    /** The order and its tracking events (newest first). */
    public function tracking(string $id): array
    {
        return $this->call('GET', '/shipments/' . rawurlencode($id) . '/tracking');
    }

    public function balance(): array
    {
        return $this->call('GET', '/balance');
    }

    /**
     * Rates, then the cheapest one is bought. $body: from, to, parcel, items (and declared_value_cents).
     * The same $idempotencyKey never buys twice. Returns the shipment response.
     */
    public function buyCheapest(array $body, string $idempotencyKey): array
    {
        $request = ['from' => $body['from'], 'to' => $body['to'], 'parcel' => $body['parcel']];
        if (isset($body['declared_value_cents'])) {
            $request['declared_value_cents'] = $body['declared_value_cents'];
        }
        $rates = $this->rates($request);
        if (empty($rates['data'])) {
            throw new ShipPickupException(422, 'no_rates', 'No rates for this route and parcel');
        }
        return $this->create(['rate_id' => $rates['data'][0]['rate_id']] + $body, $idempotencyKey);
    }

    /** Stable key from your own order number: one order never buys two labels. */
    public static function idempotencyKey(string $seed): string
    {
        return 'sp-' . substr(hash('sha256', $seed), 0, 40);
    }

    /**
     * Check the X-Shipto-Signature header of a webhook. $rawBody is the body exactly as received.
     */
    public static function verifyWebhook(string $rawBody, string $signatureHeader, string $secret, int $toleranceSeconds = 300): bool
    {
        $parts = [];
        foreach (explode(',', $signatureHeader) as $piece) {
            $pair = explode('=', trim($piece), 2);
            if (count($pair) === 2) {
                $parts[$pair[0]] = $pair[1];
            }
        }
        if (empty($parts['t']) || empty($parts['v1']) || $secret === '') {
            return false;
        }
        if (abs(time() - (int) $parts['t']) > $toleranceSeconds) {
            return false;
        }
        return hash_equals(hash_hmac('sha256', $parts['t'] . '.' . $rawBody, $secret), $parts['v1']);
    }

    /**
     * @param array|object|null $body
     * @param string[] $headers
     */
    private function call(string $method, string $path, $body = null, array $headers = []): array
    {
        $ch = curl_init($this->base . $path);
        $headers[] = 'Authorization: Bearer ' . $this->key;
        $headers[] = 'Accept: application/json';
        $options = [
            CURLOPT_CUSTOMREQUEST => $method,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT => 60,
        ];
        if ($body !== null) {
            $headers[] = 'Content-Type: application/json';
            $options[CURLOPT_POSTFIELDS] = json_encode($body);
        }
        $options[CURLOPT_HTTPHEADER] = $headers;
        curl_setopt_array($ch, $options);
        $raw = curl_exec($ch);
        $status = (int) curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
        $failure = curl_error($ch);
        curl_close($ch);
        if ($raw === false) {
            throw new ShipPickupException(0, 'network_error', $failure !== '' ? $failure : 'Request failed');
        }
        $json = json_decode((string) $raw, true);
        if (!is_array($json)) {
            throw new ShipPickupException($status, 'bad_response', 'The response is not JSON');
        }
        if ($status >= 400 || isset($json['error'])) {
            $e = isset($json['error']) && is_array($json['error']) ? $json['error'] : [];
            throw new ShipPickupException($status, (string) ($e['code'] ?? 'error'), (string) ($e['message'] ?? 'Error'), (array) ($e['details'] ?? []));
        }
        return $json;
    }
}
