<?php
/**
 * FimPaypoint PHP & Laravel Official Lightweight Client SDK
 * 
 * Single-file, zero-dependency drop-in class for FimPaypoint Checkout & Virtual Accounts.
 * Compatible with PHP 7.4, 8.0, 8.1, 8.2, 8.3+
 * 
 * Documentation: https://fimpaypoint.com/api/docs
 * Support: support@fimpaypoint.com
 * 
 * Quick Start Example:
 * 
 * require_once __DIR__ . '/FimPayClient.php';
 * 
 * $fimpay = new FimPayClient('sk_live_your_secret_key', 'pk_live_your_public_key', 'whsec_your_webhook_secret');
 * 
 * // 1. Initialize Checkout
 * $result = $fimpay->initializeCheckout([
 *     'amount'         => 5000,
 *     'customer_email' => 'customer@example.com',
 *     'customer_name'  => 'John Doe',
 *     'customer_phone' => '08012345678',
 *     'reference'      => 'ORD_' . time(),
 *     'callback_url'   => 'https://yoursite.com/payment/callback',
 *     'fee_bearer'     => 'customer', // 'customer' or 'merchant'
 *     'metadata'       => ['user_id' => 123, 'cart_id' => 456]
 * ]);
 * 
 * header('Location: ' . $result['checkout_url']);
 * exit;
 */

namespace FimPay;

use Exception;

class FimPayClient {

    private string $secretKey;
    private ?string $publicKey;
    private ?string $webhookSecret;
    private string $baseUrl;
    private int $timeout;

    /**
     * @param string      $secretKey     Your secret key (sk_live_... or sk_test_...)
     * @param string|null $publicKey     Your public key (pk_live_... or pk_test_...)
     * @param string|null $webhookSecret Your webhook secret key (whsec_live_...)
     * @param string      $baseUrl       FimPaypoint API base URL
     * @param int         $timeout       HTTP cURL timeout in seconds (default: 30)
     */
    public function __construct(
        string $secretKey, 
        ?string $publicKey = null, 
        ?string $webhookSecret = null, 
        string $baseUrl = 'https://fimpaypoint.com', 
        int $timeout = 30
    ) {
        $this->secretKey = trim($secretKey);
        $this->publicKey = $publicKey ? trim($publicKey) : null;
        $this->webhookSecret = $webhookSecret ? trim($webhookSecret) : null;
        $this->baseUrl = rtrim($baseUrl, '/');
        $this->timeout = $timeout;

        if (empty($this->secretKey)) {
            throw new Exception("FimPayClient: Secret key cannot be empty.");
        }
    }

    /**
     * Initialize a Checkout Session (Hosted Payment Page)
     * 
     * @param array $params Required: amount, customer_email, customer_name
     *                      Optional: reference, callback_url, fee_bearer, metadata, narration
     * @return array Returns ['status' => true, 'checkout_url' => ..., 'reference' => ..., 'data' => ...]
     * @throws Exception
     */
    public function initializeCheckout(array $params): array {
        if (empty($params['amount']) || (float)$params['amount'] <= 0) {
            throw new Exception("FimPayClient: 'amount' must be a positive number.");
        }
        if (empty($params['customer_email']) || !filter_var($params['customer_email'], FILTER_VALIDATE_EMAIL)) {
            throw new Exception("FimPayClient: A valid 'customer_email' is required.");
        }

        // Support callback_url, redirect_url, or redirect_link interchangeably
        $callbackUrl = $params['callback_url'] ?? ($params['redirect_url'] ?? ($params['redirect_link'] ?? ''));

        $payload = [
            'amount'         => (float)$params['amount'],
            'customer_email' => trim($params['customer_email']),
            'customer_name'  => trim($params['customer_name'] ?? 'Valued Customer'),
            'customer_phone' => trim($params['customer_phone'] ?? ''),
            'reference'      => trim($params['reference'] ?? ('ORD_' . date('YmdHis') . '_' . mt_rand(100, 999))),
            'callback_url'   => $callbackUrl,
            'redirect_url'   => $callbackUrl,
            'redirect_link'  => $callbackUrl,
            'fee_bearer'     => strtolower(trim($params['fee_bearer'] ?? 'merchant')),
            'narration'      => trim($params['narration'] ?? ''),
            'metadata'       => $params['metadata'] ?? []
        ];

        $response = $this->request('POST', '/api/v1/checkout/initialize', $payload);

        $checkoutUrl = $response['checkout_url'] ?? ($response['data']['checkout_url'] ?? ($response['data']['link'] ?? ''));
        $ref = $response['reference'] ?? ($response['data']['reference'] ?? $payload['reference']);

        return [
            'status'             => true,
            'checkout_url'       => $checkoutUrl,
            'reference'          => $ref,
            'merchant_reference' => $payload['reference'],
            'data'               => $response['data'] ?? $response,
            'raw'                => $response
        ];
    }

    /**
     * Create a Dynamic Virtual Account for Instant Bank Transfer
     * 
     * @param array $params Required: amount, customer_email, customer_name
     *                      Optional: reference, fee_bearer, metadata, expires_in_minutes
     * @return array
     * @throws Exception
     */
    public function createDynamicAccount(array $params): array {
        if (empty($params['amount']) || (float)$params['amount'] <= 0) {
            throw new Exception("FimPayClient: 'amount' must be a positive number.");
        }

        $payload = [
            'amount'             => (float)$params['amount'],
            'customer_email'     => trim($params['customer_email'] ?? ''),
            'customer_name'      => trim($params['customer_name'] ?? 'Customer'),
            'customer_phone'     => trim($params['customer_phone'] ?? ''),
            'reference'          => trim($params['reference'] ?? ('DYN_' . date('YmdHis') . '_' . mt_rand(100, 999))),
            'fee_bearer'         => strtolower(trim($params['fee_bearer'] ?? 'merchant')),
            'metadata'           => $params['metadata'] ?? [],
            'expires_in_minutes' => (int)($params['expires_in_minutes'] ?? 60)
        ];

        return $this->request('POST', '/api/v1/dynamic-accounts', $payload);
    }

    /**
     * Verify any Transaction by its Reference
     * 
     * Safe URL-encoding prevents errors with pipe (|) or special characters.
     * 
     * @param string $reference FimPaypoint reference or Merchant reference
     * @return array
     * @throws Exception
     */
    public function verifyTransaction(string $reference): array {
        $cleanRef = trim($reference);
        if (empty($cleanRef)) {
            throw new Exception("FimPayClient: Transaction reference cannot be empty.");
        }

        $url = '/api/v1/transaction/verify/' . rawurlencode($cleanRef);
        return $this->request('GET', $url);
    }

    /**
     * Helper to check if a verification response represents a successful payment
     * 
     * @param array $verificationResponse Response returned by verifyTransaction()
     * @return bool
     */
    public function isSuccessful(array $verificationResponse): bool {
        $status = strtolower($verificationResponse['data']['status'] ?? ($verificationResponse['status'] ?? ''));
        return in_array($status, ['success', 'successful', 'paid', 'completed'], true);
    }

    /**
     * Purchase Airtime Topup
     * 
     * @param array $data ['phone' => '08134943416', 'amount' => 1000, 'network' => 'MTN', 'reference' => '...']
     * @return array
     * @throws Exception
     */
    public function purchaseAirtime(array $data): array {
        return $this->request('POST', '/api/v1/vas/airtime', $data);
    }

    /**
     * Fetch Data Bundle Catalog for a phone number
     * 
     * @param string $phone Recipient phone number
     * @return array
     * @throws Exception
     */
    public function getDataPlans(string $phone): array {
        return $this->request('GET', '/api/v1/vas/data-plans', ['phone' => $phone]);
    }

    /**
     * Purchase Data Bundle Topup
     * 
     * @param array $data ['phone' => '08134943416', 'product_id' => 'MTN-1GB', 'amount' => 500, 'network' => 'MTN', 'reference' => '...']
     * @return array
     * @throws Exception
     */
    public function purchaseData(array $data): array {
        return $this->request('POST', '/api/v1/vas/data', $data);
    }

    /**
     * Verify Incoming Webhook Signature & Return Payload
     * 
     * Validates HMAC SHA-512 signature using your Webhook Secret or Secret Key.
     * Prevents timing attacks with hash_equals().
     * 
     * @param string|null $rawPayload      Raw HTTP request body (defaults to php://input)
     * @param string|null $signatureHeader X-Fimpay-Signature header (auto-detected if null)
     * @return array Decoded webhook event payload
     * @throws Exception If signature is invalid or payload cannot be parsed
     */
    public function verifyWebhook(?string $rawPayload = null, ?string $signatureHeader = null): array {
        if ($rawPayload === null) {
            $rawPayload = file_get_contents('php://input');
        }

        if (empty($rawPayload)) {
            throw new Exception("FimPayClient: Webhook body is empty.");
        }

        if ($signatureHeader === null) {
            $signatureHeader = $_SERVER['HTTP_X_FIMPAY_SIGNATURE'] 
                ?? ($_SERVER['HTTP_X_SIGNATURE'] 
                ?? (function_exists('getallheaders') ? (getallheaders()['X-Fimpay-Signature'] ?? '') : ''));
        }

        $signingSecret = !empty($this->webhookSecret) ? $this->webhookSecret : $this->secretKey;

        // Verify HMAC SHA-512 Signature
        $expectedSignature = hash_hmac('sha512', $rawPayload, $signingSecret);

        if (!hash_equals($expectedSignature, (string)$signatureHeader)) {
            // Also attempt fallback check with Secret Key if Webhook Secret was passed
            if (!empty($this->webhookSecret) && $this->webhookSecret !== $this->secretKey) {
                $fallbackSig = hash_hmac('sha512', $rawPayload, $this->secretKey);
                if (hash_equals($fallbackSig, (string)$signatureHeader)) {
                    $event = json_decode($rawPayload, true);
                    return is_array($event) ? $event : [];
                }
            }
            throw new Exception("FimPayClient: Invalid webhook signature. Expected HMAC SHA-512 signature does not match.");
        }

        $event = json_decode($rawPayload, true);
        if (!is_array($event)) {
            throw new Exception("FimPayClient: Invalid JSON payload in webhook.");
        }

        return $event;
    }

    /**
     * Send an immediate 200 OK acknowledgement to FimPaypoint webhook dispatcher
     */
    public function acknowledgeWebhook(): void {
        if (!headers_sent()) {
            http_response_code(200);
            header('Content-Type: application/json; charset=utf-8');
        }
        echo json_encode(['status' => 'success', 'message' => 'Webhook acknowledged']);
        if (function_exists('fastcgi_finish_request')) {
            fastcgi_finish_request();
        }
    }

    /**
     * Internal cURL Request Dispatcher
     */
    private function request(string $method, string $endpoint, array $data = []): array {
        $url = $this->baseUrl . $endpoint;
        $ch = curl_init();

        $headers = [
            'Authorization: Bearer ' . $this->secretKey,
            'Content-Type: application/json',
            'Accept: application/json',
            'User-Agent: FimPaypoint-PHP-SDK/2.0'
        ];

        $options = [
            CURLOPT_URL            => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT        => $this->timeout,
            CURLOPT_CONNECTTIMEOUT => 10,
            CURLOPT_HTTPHEADER     => $headers,
            CURLOPT_SSL_VERIFYPEER => true,
            CURLOPT_SSL_VERIFYHOST => 2
        ];

        if (strtoupper($method) === 'POST') {
            $options[CURLOPT_POST] = true;
            $options[CURLOPT_POSTFIELDS] = json_encode($data);
        } elseif (strtoupper($method) === 'GET' && !empty($data)) {
            $options[CURLOPT_URL] = $url . '?' . http_build_query($data);
        }

        curl_setopt_array($ch, $options);

        $rawResponse = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $curlError = curl_error($ch);
        $curlErrno = curl_errno($ch);
        curl_close($ch);

        if ($curlErrno !== 0) {
            throw new Exception("FimPayClient cURL Error ({$curlErrno}): {$curlError}");
        }

        $json = json_decode($rawResponse, true);

        if ($httpCode >= 400 || ($json && isset($json['status']) && $json['status'] === false)) {
            $errorMsg = $json['message'] ?? ($json['error'] ?? "API Request failed with HTTP {$httpCode}");
            throw new Exception("FimPayClient API Error ({$httpCode}): {$errorMsg}");
        }

        return is_array($json) ? $json : ['raw_response' => $rawResponse];
    }
}

