<?php
/**
 * OxaPay Payment Gateway API
 * For BTC and USDT payments
 */
class OxaPayAPI {
    private $apiUrl = 'https://api.oxapay.com';
    private $merchantKey;
    
    public function __construct() {
        $pdo = getDBConnection();
        $stmt = $pdo->query("SELECT * FROM api_settings WHERE provider = 'oxapay' AND status = 'active' LIMIT 1");
        $settings = $stmt->fetch();
        
        if ($settings) {
            $this->merchantKey = $settings['api_key'] ?? '';
        }
    }
    
    public function isConfigured() {
        return !empty($this->merchantKey);
    }
    
    public function getMerchantKey() {
        return $this->merchantKey;
    }
    
    private function request($endpoint, $data = []) {
        $url = $this->apiUrl . $endpoint;
        
        $ch = curl_init($url);
        curl_setopt_array($ch, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_POST => true,
            CURLOPT_POSTFIELDS => json_encode($data),
            CURLOPT_HTTPHEADER => [
                'Content-Type: application/json',
                'merchant_api_key: ' . $this->merchantKey
            ],
            CURLOPT_TIMEOUT => 15,
            CURLOPT_CONNECTTIMEOUT => 10,
            CURLOPT_SSL_VERIFYPEER => true,
            CURLOPT_SSL_VERIFYHOST => 2
        ]);
        
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $error = curl_error($ch);
        curl_close($ch);
        
        if ($response === false) {
            error_log("OxaPay API Error: $error");
            return ['status' => 500, 'message' => 'Connection error: ' . $error];
        }
        
        $decoded = json_decode($response, true);
        if ($decoded === null) {
            error_log("OxaPay API Invalid Response: $response");
            return ['status' => 500, 'message' => 'Invalid response'];
        }
        
        return $decoded;
    }
    
    /**
     * Create invoice for payment
     * @param float $amount Amount in USD
     * @param string $orderId Unique order ID
     * @param string $callbackUrl Webhook URL
     * @param string $returnUrl Return URL after payment
     * @return array
     */
    public function createInvoice($amount, $orderId, $callbackUrl = '', $returnUrl = '') {
        $data = [
            'merchant' => $this->merchantKey,
            'amount' => (float)$amount,
            'currency' => 'USD',
            'lifeTime' => 60,
            'feePaidByPayer' => 1,
            'underPaidCover' => 2.5,
            'orderId' => $orderId,
            'description' => 'Add funds - Order ' . $orderId
        ];
        
        if (!empty($callbackUrl)) {
            $data['callbackUrl'] = $callbackUrl;
        }
        
        if (!empty($returnUrl)) {
            $data['returnUrl'] = $returnUrl;
        }
        
        return $this->request('/merchants/request', $data);
    }
    
    /**
     * Get payment info by track_id
     * Uses the payment inquiry endpoint
     */
    public function getPaymentInfo($trackId = null, $orderId = null) {
        $data = [
            'merchant' => $this->merchantKey
        ];
        
        if ($trackId) {
            $data['trackId'] = $trackId;
        }
        if ($orderId) {
            $data['orderId'] = $orderId;
        }
        
        return $this->request('/merchants/inquiry', $data);
    }
    
    /**
     * Verify webhook HMAC signature
     */
    public function verifyWebhook($payload, $hmacHeader) {
        $calculatedHmac = hash_hmac('sha512', $payload, $this->merchantKey);
        return hash_equals($calculatedHmac, $hmacHeader);
    }
}