<?php
/**
 * NEXUSLAB Payment Gateway — PHP SDK (API v1).
 *
 * Single-file SDK, no dependencies beyond cURL.
 *
 * Usage:
 *   require 'NexusLab.php';
 *   $nx = new NexusLab('আপনার_brand_key'); // sandbox: 'nx_test_...'
 *
 *   $pay = $nx->createPayment([
 *       'amount'      => 1250.00,
 *       'success_url' => 'https://yourshop.com/payment/success',
 *       'cancel_url'  => 'https://yourshop.com/payment/cancel',
 *       'cus_name'    => 'Karim Uddin',
 *       'cus_email'   => 'karim@example.com',
 *       'webhook_url' => 'https://yourshop.com/webhooks/nexuslab',
 *       'metadata'    => ['order_id' => '1001'],
 *   ]);
 *   header('Location: ' . $pay['payment_url']);
 *
 *   $check = $nx->verifyPayment($pay['transaction_id']);
 *   if ($check['status'] === 'COMPLETED' && (float) $check['amount'] === 1250.00) {
 *       // fulfil the order
 *   }
 *
 * Webhook signature check:
 *   $ok = NexusLab::verifyWebhookSignature(
 *       file_get_contents('php://input'),
 *       $_SERVER['HTTP_X_NEXUSLAB_SIGNATURE'] ?? '',
 *       'whsec_আপনার_webhook_secret'
 *   );
 */

class NexusLabException extends Exception
{
    public $errorCode;
    public $requestId;
    public $httpStatus;

    public function __construct($code, $message, $requestId = null, $httpStatus = null)
    {
        parent::__construct($code . ': ' . $message);
        $this->errorCode = $code;
        $this->requestId = $requestId;
        $this->httpStatus = $httpStatus;
    }
}

class NexusLab
{
    private $apiKey;
    private $baseUrl;
    private $timeout;

    public function __construct($apiKey, $baseUrl = 'https://payment.nexuslab.dev.cv', $timeout = 30)
    {
        $this->apiKey = $apiKey;
        $this->baseUrl = rtrim($baseUrl, '/');
        $this->timeout = $timeout;
    }

    /**
     * Create a payment. Required keys: amount, success_url, cancel_url.
     * Optional: cus_name, cus_email, webhook_url, metadata (array), return_type.
     * Returns ['payment_url' => ..., 'transaction_id' => ..., 'test' => bool]
     */
    public function createPayment(array $params, $idempotencyKey = null)
    {
        $headers = [];
        if ($idempotencyKey) {
            $headers[] = 'Idempotency-Key: ' . $idempotencyKey;
        }
        return $this->post('/api/v1/payment/create', $params, $headers);
    }

    /**
     * Verify a payment by transaction_id.
     * Returns the data array; 'status' is one of
     * PENDING / PROCESSING / COMPLETED / FAILED / CANCELLED / EXPIRED.
     */
    public function verifyPayment($transactionId)
    {
        return $this->post('/api/v1/payment/verify', ['transaction_id' => $transactionId]);
    }

    /**
     * Verify an X-Nexuslab-Signature header ('t=<ts>,v1=<hmac>').
     * $rawBody must be the exact request body. Returns bool.
     */
    public static function verifyWebhookSignature($rawBody, $signatureHeader, $secret, $tolerance = 300)
    {
        $parts = [];
        foreach (explode(',', (string) $signatureHeader) as $piece) {
            $kv = explode('=', trim($piece), 2);
            if (count($kv) === 2) {
                $parts[$kv[0]] = $kv[1];
            }
        }
        if (empty($parts['t']) || empty($parts['v1'])) {
            return false;
        }
        if (abs(time() - (int) $parts['t']) > $tolerance) {
            return false;
        }
        $expected = hash_hmac('sha256', $parts['t'] . '.' . $rawBody, (string) $secret);
        return hash_equals($expected, $parts['v1']);
    }

    private function post($path, array $payload, array $extraHeaders = [])
    {
        $headers = array_merge(
            ['API-KEY: ' . $this->apiKey, 'Content-Type: application/json'],
            $extraHeaders
        );
        $ch = curl_init($this->baseUrl . $path);
        curl_setopt_array($ch, [
            CURLOPT_POST           => true,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT        => $this->timeout,
            CURLOPT_HTTPHEADER     => $headers,
            CURLOPT_POSTFIELDS     => json_encode($payload),
        ]);
        $out = curl_exec($ch);
        $code = (int) curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
        $err = curl_error($ch);
        curl_close($ch);
        if ($out === false) {
            throw new NexusLabException('INTERNAL_SERVER_ERROR', 'Network error: ' . $err, null, $code);
        }
        $body = json_decode($out, true);
        if (!is_array($body)) {
            throw new NexusLabException('INTERNAL_SERVER_ERROR', 'Non-JSON response (HTTP ' . $code . ')', null, $code);
        }
        if (empty($body['status'])) {
            $e = $body['error'] ?? [];
            throw new NexusLabException(
                $e['code'] ?? 'INTERNAL_SERVER_ERROR',
                $e['message'] ?? 'Unknown error',
                $body['request_id'] ?? null,
                $code
            );
        }
        return $body['data'];
    }
}
