<?php
declare(strict_types=1);

/**
 * DerashPay PHP SDK — single-file, zero-dependency API client.
 *
 * Requirements: PHP 7.4+, OpenSSL extension (for HTTPS + webhook HMAC).
 *
 * Quick start:
 *   require 'DerashPay.php';
 *   $dp  = new DerashPay('dp_secret_test_...');
 *   $tx  = $dp->createCharge(245000, 'ETB', 'telebirr', ['idempotency_key' => 'order_123']);
 *   $ses = $dp->createCheckoutSession(245000, 'ETB', 'https://you.com/success');
 *   header('Location: ' . $ses['url']);
 */

class DerashPayException extends \RuntimeException
{
    /** Machine-readable error code from the API (e.g. "auth_invalid"). */
    public string $apiCode;

    public function __construct(string $apiCode, string $message, int $httpStatus = 0)
    {
        $this->apiCode = $apiCode;
        parent::__construct($message, $httpStatus);
    }
}

class DerashPay
{
    private string $secretKey;
    private string $baseUrl;

    /**
     * @param string $secretKey Your test or live secret key (dp_secret_test_… / dp_secret_live_…).
     * @param string $baseUrl   Override only when self-hosting DerashPay.
     */
    public function __construct(string $secretKey, string $baseUrl = 'https://derashpay.co/api/v1')
    {
        $this->secretKey = $secretKey;
        $this->baseUrl   = rtrim($baseUrl, '/');
    }

    /**
     * Verify authentication and return the merchant / project context for this key.
     *
     * Use this as a connectivity check during integration.
     *
     * @throws DerashPayException
     */
    public function ping(): array
    {
        return $this->request('GET', '/ping');
    }

    /**
     * Create a direct server-to-server charge.
     *
     * Amounts are integers in MINOR units — ETB 1.00 = 100, ETB 2 450.00 = 245000.
     * Never pass floats; multiply on your side before calling this method.
     *
     * @param int    $amount  Minor units (no floats).
     * @param string $currency 3-letter ISO code: ETB, USD, EUR …
     * @param string $psp     Provider code: telebirr | cbe | cbebirr | awash | awashbirr |
     *                        dashen | boa | boa_card | zamzam | commercial |
     *                        m_pesa | stripe | paypal | card_generic | local_banks | pss_cards
     * @param array  $opts    Optional keys:
     *                          idempotency_key string — unique per logical charge; replay returns same tx
     *                          description     string — up to 255 chars
     *                          customer_email  string
     *                          customer_name   string
     *                          customer_phone  string
     *                          metadata        array  — stored as JSON; returned in webhooks
     *
     * @return array Transaction object: id, status, amount, fee, net, currency, psp, created, …
     * @throws DerashPayException
     */
    public function createCharge(int $amount, string $currency, string $psp, array $opts = []): array
    {
        $body = ['amount' => $amount, 'currency' => strtoupper($currency), 'psp' => $psp];

        foreach (['description', 'customer_email', 'customer_name', 'customer_phone'] as $k) {
            if (isset($opts[$k]) && $opts[$k] !== '') {
                $body[$k] = $opts[$k];
            }
        }
        if (isset($opts['metadata']) && is_array($opts['metadata'])) {
            $body['metadata'] = $opts['metadata'];
        }

        $extra = [];
        if (!empty($opts['idempotency_key'])) {
            $extra[] = 'Idempotency-Key: ' . $opts['idempotency_key'];
        }

        return $this->request('POST', '/charges', $body, $extra);
    }

    /**
     * Create a hosted checkout session and return its URL.
     *
     * Redirect (or open) session['url'] in the customer's browser.
     * After payment DerashPay sends the customer to:
     *   return_url?cs=cs_…&tx=tx_…&status=succeeded|pending
     * After cancel:
     *   cancel_url?cs=cs_…&status=cancelled
     *
     * @param int    $amount    Minor units.
     * @param string $currency  3-letter ISO code.
     * @param string $returnUrl Where the browser goes after a successful payment.
     * @param array  $opts      Optional keys:
     *                            cancel_url       string — browser lands here on cancel
     *                            allowed_psps     array  — limit which banks the customer sees
     *                            description      string
     *                            customer_email   string
     *                            customer_name    string
     *                            customer_phone   string
     *                            metadata         array
     *                            idempotency_key  string
     *
     * @return array Checkout session: id, url, status, expires_at, …
     * @throws DerashPayException
     */
    public function createCheckoutSession(int $amount, string $currency, string $returnUrl, array $opts = []): array
    {
        $body = [
            'amount'     => $amount,
            'currency'   => strtoupper($currency),
            'return_url' => $returnUrl,
        ];

        foreach (['cancel_url', 'description', 'customer_email', 'customer_name', 'customer_phone'] as $k) {
            if (isset($opts[$k]) && $opts[$k] !== '') {
                $body[$k] = $opts[$k];
            }
        }
        if (isset($opts['allowed_psps']) && is_array($opts['allowed_psps'])) {
            $body['allowed_psps'] = array_values($opts['allowed_psps']);
        }
        if (isset($opts['metadata']) && is_array($opts['metadata'])) {
            $body['metadata'] = $opts['metadata'];
        }

        $extra = [];
        if (!empty($opts['idempotency_key'])) {
            $extra[] = 'Idempotency-Key: ' . $opts['idempotency_key'];
        }

        return $this->request('POST', '/checkout_sessions', $body, $extra);
    }

    /**
     * Verify a DerashPay webhook signature.
     *
     * Call this BEFORE processing any webhook payload.
     * Returns true only when the HMAC is valid AND the timestamp is within
     * $toleranceSeconds of now (prevents replay attacks).
     *
     * Example (plain PHP):
     *   $payload = file_get_contents('php://input');
     *   $sig     = $_SERVER['HTTP_X_DERASHPAY_SIGNATURE'] ?? '';
     *   if (!DerashPay::verifyWebhook($payload, $sig, 'whsec_...')) {
     *       http_response_code(400);
     *       exit;
     *   }
     *
     * @param string $payload          Raw request body — read BEFORE json_decode.
     * @param string $signatureHeader  Value of the X-DerashPay-Signature header.
     * @param string $endpointSecret   The "secret" shown next to your URL in Settings → Webhooks.
     * @param int    $toleranceSeconds Reject events older than this (default 300 s = 5 min).
     */
    public static function verifyWebhook(
        string $payload,
        string $signatureHeader,
        string $endpointSecret,
        int $toleranceSeconds = 300
    ): bool {
        if (!preg_match('/^t=(\d+),v1=([a-f0-9]+)$/', $signatureHeader, $m)) {
            return false;
        }
        [, $ts, $given] = $m;

        $expected = hash_hmac('sha256', $ts . '.' . $payload, $endpointSecret);

        return hash_equals($expected, $given)
            && abs(time() - (int)$ts) < $toleranceSeconds;
    }

    // -----------------------------------------------------------------------
    // Internal
    // -----------------------------------------------------------------------

    /**
     * Make an HTTP request to the API and return the decoded JSON body.
     *
     * Uses file_get_contents + stream context (no cURL required).
     *
     * @throws DerashPayException on network failure, non-JSON response, or API error.
     */
    private function request(string $method, string $path, array $body = [], array $extraHeaders = []): array
    {
        $url  = $this->baseUrl . $path;
        $json = ($method !== 'GET' && $body !== [])
            ? json_encode($body, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE)
            : null;

        $headers = [
            'Authorization: Bearer ' . $this->secretKey,
            'Accept: application/json',
        ];
        if ($json !== null) {
            $headers[] = 'Content-Type: application/json';
            $headers[] = 'Content-Length: ' . strlen($json);
        }
        foreach ($extraHeaders as $h) {
            $headers[] = $h;
        }

        $ctx  = stream_context_create(['http' => [
            'method'        => $method,
            'header'        => implode("\r\n", $headers) . "\r\n",
            'content'       => $json,
            'timeout'       => 15,
            'ignore_errors' => true,
        ]]);
        $raw  = @file_get_contents($url, false, $ctx);

        if ($raw === false) {
            throw new DerashPayException(
                'network_error',
                'Could not connect to DerashPay API. Check network and base URL.'
            );
        }

        $httpCode = 0;
        foreach ($http_response_header ?? [] as $h) {
            if (preg_match('/^HTTP\/[\d.]+\s+(\d+)/', $h, $hm)) {
                $httpCode = (int)$hm[1];
                break;
            }
        }

        $data = json_decode($raw, true);
        if ($data === null) {
            throw new DerashPayException(
                'invalid_response',
                'DerashPay returned a non-JSON response (HTTP ' . $httpCode . ').'
            );
        }

        if ($httpCode < 200 || $httpCode >= 300) {
            throw new DerashPayException(
                $data['error']['code']    ?? 'unknown_error',
                $data['error']['message'] ?? 'Unknown API error (HTTP ' . $httpCode . ').',
                $httpCode
            );
        }

        return $data;
    }
}
