<?php
/**
 * MIPL Payment Gateway - PHP SDK
 * Moldable Infotech Pvt Ltd
 *
 * Usage:
 *   require 'MiplPay.php';
 *   $pg = new MiplPay('mipl_live_xxx', 'sk_xxx', 'https://pay.moldable.in');
 *   $order = $pg->createOrder(['amount' => 499, 'order_id' => 'INV1001']);
 *   header('Location: ' . $order['payment_url']);
 */
class MiplPay
{
    private string $key;
    private string $secret;
    private string $base;

    public function __construct(string $apiKey, string $apiSecret, string $baseUrl = 'https://pay.moldable.in')
    {
        $this->key = $apiKey;
        $this->secret = $apiSecret;
        $this->base = rtrim($baseUrl, '/') . '/api/v1/';
    }

    /** Creates a new payment order. Return: data array (payment_id, payment_url, pay_amount ...) */
    public function createOrder(array $params): array
    {
        return $this->request('POST', 'create_order.php', $params);
    }

    /** Order status: ['order_id' => '...'] or ['payment_id' => '...'] */
    public function orderStatus(array $params): array
    {
        return $this->request('GET', 'order_status.php?' . http_build_query($params));
    }

    /** Whether the payment succeeded (server-side verification) */
    public function isPaid(string $orderId, ?float $expectedAmount = null): bool
    {
        $o = $this->orderStatus(['order_id' => $orderId]);
        if (($o['status'] ?? '') !== 'success') return false;
        return $expectedAmount === null || abs((float)$o['amount'] - $expectedAmount) < 0.001;
    }

    /**
     * Verifies a webhook. Returns the decoded payload, or null if the signature is invalid.
     *   $event = $pg->verifyWebhook(file_get_contents('php://input'), $_SERVER['HTTP_X_MIPL_SIGNATURE'] ?? '');
     */
    public function verifyWebhook(string $rawBody, string $signature): ?array
    {
        $expected = hash_hmac('sha256', $rawBody, $this->secret);
        if (!$signature || !hash_equals($expected, $signature)) return null;
        $data = json_decode($rawBody, true);
        return is_array($data) ? $data : null;
    }

    private function request(string $method, string $path, array $body = []): array
    {
        $ch = curl_init($this->base . $path);
        $headers = ['Accept: application/json', 'X-Api-Key: ' . $this->key, 'X-Api-Secret: ' . $this->secret];
        if ($method === 'POST') {
            $headers[] = 'Content-Type: application/json';
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($body));
        }
        curl_setopt_array($ch, [CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 20, CURLOPT_HTTPHEADER => $headers]);
        $resp = curl_exec($ch);
        if ($resp === false) {
            $err = curl_error($ch);
            curl_close($ch);
            throw new RuntimeException('MIPL Pay connection error: ' . $err);
        }
        curl_close($ch);
        $json = json_decode($resp, true);
        if (!is_array($json)) throw new RuntimeException('MIPL Pay invalid response');
        if (empty($json['status'])) throw new RuntimeException($json['error']['message'] ?? 'MIPL Pay error');
        return $json['data'];
    }
}
