<?php
/**
 * Heleket Payment Gateway API
 * For BTC and USDT payments
 */
class HeleketAPI {
    private $apiUrl = 'https://api.heleket.com/v1';
    private $merchantId;
    private $apiKey;
    
    public function __construct() {
        $pdo = getDBConnection();
        $stmt = $pdo->query("SELECT * FROM api_settings WHERE provider = 'heleket' AND status = 'active' LIMIT 1");
        $settings = $stmt->fetch();
        
        if ($settings) {
            $this->merchantId = $settings['merchant_id'] ?? '';
            $this->apiKey = $settings['api_key'] ?? '';
        }
    }
    
    public function isConfigured() {
        return !empty($this->merchantId) && !empty($this->apiKey);
    }
    
    private function generateSign($data) {
        $json = json_encode($data, JSON_UNESCAPED_UNICODE);
        return md5(base64_encode($json) . $this->apiKey);
    }
    
    private function request($endpoint, $data = []) {
        $sign = $this->generateSign($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: ' . $this->merchantId,
                'sign: ' . $sign
            ],
            CURLOPT_TIMEOUT => 30
        ]);
        
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        
        if ($response === false) {
            return ['state' => 1, 'message' => 'Connection error'];
        }
        
        return json_decode($response, true) ?: ['state' => 1, 'message' => 'Invalid response'];
    }
    
    /**
     * Create invoice for payment
     * @param float $amount Amount in USD
     * @param string $orderId Unique order ID
     * @param string $currency BTC or USDT
     * @param string $network Network (e.g., tron for USDT, btc for BTC)
     * @param string $callbackUrl Webhook URL
     * @return array
     */
    public function createInvoice($amount, $orderId, $currency = 'USDT', $network = 'tron', $callbackUrl = '') {
        $data = [
            'amount' => (string)$amount,
            'currency' => 'USD',
            'to_currency' => $currency,
            'network' => $network,
            'order_id' => $orderId,
            'is_payment_multiple' => false,
            'lifetime' => 3600 // 1 hour
        ];
        
        if (!empty($callbackUrl)) {
            $data['url_callback'] = $callbackUrl;
        }
        
        return $this->request('/payment/invoice', $data);
    }
    
    /**
     * Get payment info by UUID or order_id
     */
    public function getPaymentInfo($uuid = null, $orderId = null) {
        $data = [];
        if ($uuid) $data['uuid'] = $uuid;
        if ($orderId) $data['order_id'] = $orderId;
        
        return $this->request('/payment/info', $data);
    }
    
    /**
     * Get available payment services
     */
    public function getServices() {
        return $this->request('/payment/services', []);
    }
    
    /**
     * Verify webhook signature
     */
    public function verifyWebhook($payload, $receivedSign) {
        $json = json_encode($payload, JSON_UNESCAPED_UNICODE);
        $expectedSign = md5(base64_encode($json) . $this->apiKey);
        return hash_equals($expectedSign, $receivedSign);
    }
}