<?php
/**
 * FamGateway PHP SDK
 * A lightweight drop-in module to integrate FamGateway into any PHP website.
 */

class FamGateway {
    private $apiKey;
    private $baseUrl = "https://fam.aryanispe.in";

    public function __construct($apiKey) {
        $this->apiKey = $apiKey;
    }

    /**
     * Create a payment order and redirect the user to the secure checkout page.
     * 
     * @param float $amount The amount to charge (e.g., 500)
     * @param string $redirectUrl The URL to send the user back to after payment
     */
    public function createPayment($amount, $redirectUrl) {
        $url = $this->baseUrl . "/api/qr.php?api_key=" . urlencode($this->apiKey) . "&amount=" . urlencode((string)$amount) . "&redirect_url=" . urlencode($redirectUrl);
        
        $response = @file_get_contents($url);
        if ($response === false) {
            die("FamGateway Error: Failed to connect to API.");
        }
        
        $data = json_decode($response, true);
        
        if (isset($data['status']) && $data['status'] === 'success') {
            $orderId = $data['data']['order_id'];
            $checkoutUrl = $this->baseUrl . "/checkout.php?order_id=" . urlencode($orderId);
            header("Location: " . $checkoutUrl);
            exit;
        } else {
            $error = $data['message'] ?? 'Unknown error';
            die("FamGateway Error: " . htmlspecialchars($error));
        }
    }

    /**
     * Verify the webhook signature to ensure the request is authentically from FamGateway.
     * 
     * @param string $rawPostData The raw POST body (file_get_contents('php://input'))
     * @param string $signature The HTTP_X_FAMGATEWAY_SIGNATURE header
     * @return array|false Returns the decoded JSON payload if valid, or false if invalid.
     */
    public function verifyWebhook($rawPostData, $signature) {
        if (!$rawPostData || !$signature) {
            return false;
        }
        
        $expectedSignature = hash_hmac('sha256', $rawPostData, $this->apiKey);
        
        if (hash_equals($expectedSignature, $signature)) {
            return json_decode($rawPostData, true);
        }
        
        return false;
    }
}
?>
