<?php
/**
 * PayQube PHP SDK — single file, needs PHP 7.4+ with the curl extension.
 *
 *   require 'PayQube.php';
 *   $pq = new PayQube(getenv('PQ_KEY_ID'), getenv('PQ_SECRET'), 'https://your-payqube-domain');
 *   $p  = $pq->createPayment([
 *     'amount' => 499, 'order_id' => 'ORD-1', 'return_url' => 'https://shop.in/thanks',
 *     'customer' => ['name' => 'Asha', 'email' => 'a@x.in', 'phone' => '9876543210'],
 *   ]);
 *   header('Location: ' . $p['payment_url']);
 *
 * Webhooks:  PayQube::verifyWebhook(file_get_contents('php://input'), $_SERVER['HTTP_X_PAYQUBE_SIGNATURE'] ?? '', $webhookSecret)
 * Keep the secret on your server only.
 */

class PayQubeException extends Exception
{
    public $status;
    public $errorCode;
    public function __construct($message, $status = 0, $errorCode = '')
    {
        parent::__construct($message);
        $this->status = $status;
        $this->errorCode = $errorCode;
    }
}

class PayQube
{
    private $base;
    private $keyId;
    private $secret;
    private $timeout;

    public function __construct($keyId, $secret, $baseUrl, $timeout = 15)
    {
        if (!$keyId || !$secret || !$baseUrl) {
            throw new InvalidArgumentException('PayQube: keyId, secret and baseUrl are required');
        }
        $this->keyId = $keyId;
        $this->secret = $secret;
        $this->base = rtrim($baseUrl, '/') . '/api/v1';
        $this->timeout = $timeout;
    }

    public function createPayment(array $body) { return $this->request('POST', '/payments', $body); }
    public function fetchPayment($id) { return $this->request('GET', '/payments/' . rawurlencode($id)); }
    public function listPayments($limit = 20) { return $this->request('GET', '/payments?limit=' . (int) $limit); }
    public function refund($id, $amount) { return $this->request('POST', '/payments/' . rawurlencode($id) . '/refunds', ['amount' => $amount]); }
    public function createPayout(array $body) { return $this->request('POST', '/payouts', $body); }
    public function fetchPayout($id) { return $this->request('GET', '/payouts/' . rawurlencode($id)); }
    public function balance() { return $this->request('GET', '/balance'); }

    public function request($method, $path, $body = null)
    {
        $ch = curl_init($this->base . $path);
        $headers = ['Accept: application/json'];
        if ($body !== null) {
            $headers[] = 'Content-Type: application/json';
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($body));
        }
        curl_setopt_array($ch, [
            CURLOPT_CUSTOMREQUEST => $method,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_USERPWD => $this->keyId . ':' . $this->secret,
            CURLOPT_HTTPHEADER => $headers,
            CURLOPT_TIMEOUT => $this->timeout,
            CURLOPT_SSL_VERIFYPEER => true,
        ]);
        $raw = curl_exec($ch);
        $status = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $err = curl_error($ch);
        curl_close($ch);
        if ($raw === false) {
            throw new PayQubeException('Network error: ' . $err, 0, 'network_error');
        }
        $data = json_decode($raw, true) ?: [];
        if ($status < 200 || $status >= 300) {
            $msg = isset($data['error']['message']) ? $data['error']['message'] : 'HTTP ' . $status;
            throw new PayQubeException($msg, $status, isset($data['error']['code']) ? $data['error']['code'] : '');
        }
        return $data;
    }

    /** Constant-time check of the X-PayQube-Signature header (HMAC-SHA256 of the raw body). */
    public static function verifyWebhook($rawBody, $signature, $webhookSecret)
    {
        return hash_equals(hash_hmac('sha256', $rawBody, $webhookSecret), (string) $signature);
    }
}
