<?php
/**
 * OxaPay Payment Gateway API
 * For BTC and USDT payments
 */
class OxaPayAPI {
    private $apiUrl = 'https://api.oxapay.com/v1';
    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 = []) {
        $ch = curl_init($this->apiUrl . $endpoint);
        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 => 30
        ]);
        
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        
        if ($response === false) {
            return ['status' => 500, 'message' => 'Connection error'];
        }
        
        return json_decode($response, true) ?: ['status' => 500, 'message' => 'Invalid response'];
    }
    
    /**
     * 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 = [
            'amount' => (float)$amount,
            'currency' => 'USD',
            'lifetime' => 60, // 60 minutes
            'fee_paid_by_payer' => 0,
            'under_paid_coverage' => 2.5,
            'order_id' => $orderId,
            'description' => 'Add funds to ' . SITE_NAME,
            'sandbox' => false
        ];
        
        if (!empty($callbackUrl)) {
            $data['callback_url'] = $callbackUrl;
        }
        
        if (!empty($returnUrl)) {
            $data['return_url'] = $returnUrl;
        }
        
        return $this->request('/payment/invoice', $data);
    }
    
    /**
     * Get payment info by track_id or order_id
     */
    public function getPaymentInfo($trackId = null, $orderId = null) {
        $data = [];
        if ($trackId) $data['track_id'] = $trackId;
        if ($orderId) $data['order_id'] = $orderId;
        
        return $this->request('/payment/info', $data);
    }
    
    /**
     * Verify webhook HMAC signature
     */
    public function verifyWebhook($payload, $hmacHeader) {
        $calculatedHmac = hash_hmac('sha512', $payload, $this->merchantKey);
        return hash_equals($calculatedHmac, $hmacHeader);
    }
}