<?php
/**
 * Bridge.xyz API Integration for Binance P2P
 * Handles all Bridge API calls for payment processing
 */

class BridgeAPI {
    private $apiKey;
    private $baseUrl;
    
    public function __construct($apiKey) {
        $this->apiKey = $apiKey;
        $this->baseUrl = BRIDGE_API_URL;
    }
    
    /**
     * Generate UUID for idempotency
     */
    private function generateUuid() {
        return sprintf('%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
            mt_rand(0, 0xffff), mt_rand(0, 0xffff),
            mt_rand(0, 0xffff),
            mt_rand(0, 0x0fff) | 0x4000,
            mt_rand(0, 0x3fff) | 0x8000,
            mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff)
        );
    }
    
    /**
     * Send HTTP request (generic method)
     */
    private function sendRequest($method, $url, $data = null, $idempotencyKey = null) {
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        
        $headers = [
            'Api-Key: ' . $this->apiKey,
            'Content-Type: application/json',
            'accept: application/json'
        ];
        
        if ($idempotencyKey) {
            $headers[] = 'Idempotency-Key: ' . $idempotencyKey;
        }
        
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        
        if ($method === 'POST') {
            curl_setopt($ch, CURLOPT_POST, true);
            if ($data) {
                curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
            }
        } elseif ($method === 'DELETE') {
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE');
        } elseif ($method === 'PUT') {
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
            if ($data) {
                curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
            }
        } elseif ($method === 'GET') {
            curl_setopt($ch, CURLOPT_HTTPGET, true);
        }
        
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $curlError = curl_error($ch);
        curl_close($ch);
        
        if ($curlError) {
            error_log("Bridge API cURL Error ($method $url): " . $curlError);
            return ['error' => 'cURL Error: ' . $curlError];
        }
        
        $responseData = json_decode($response, true);
        
        if ($httpCode >= 200 && $httpCode < 300) {
            return $responseData;
        } else {
            $errorMessage = isset($responseData['message']) ? $responseData['message'] : 'Unknown error';
            $errorDetails = isset($responseData['errors']) ? json_encode($responseData['errors']) : '';
            $fullResponse = json_encode($responseData);
            error_log("Bridge API Error ($method $url): HTTP $httpCode - " . $errorMessage);
            if ($errorDetails) {
                error_log("Bridge API Error Details: " . $errorDetails);
            }
            error_log("Bridge API Full Response: " . $fullResponse);
            return ['error' => $errorMessage, 'http_code' => $httpCode, 'errors' => $errorDetails, 'full_response' => $responseData];
        }
    }
    
    /**
     * Create a transfer (for paying buyers)
     */
    public function createTransfer($transferData) {
        $url = $this->baseUrl . '/v0/transfers';
        $idempotencyKey = $this->generateUuid();
        return $this->sendRequest('POST', $url, $transferData, $idempotencyKey);
    }
    
    /**
     * Get transfer details
     */
    public function getTransferDetails($transferId) {
        $url = $this->baseUrl . '/v0/transfers/' . urlencode($transferId);
        return $this->sendRequest('GET', $url);
    }
    
    /**
     * Get customer details
     */
    public function getCustomerStatus($customerId) {
        $url = $this->baseUrl . '/v0/customers/' . $customerId;
        return $this->sendRequest('GET', $url);
    }
    
    /**
     * Get external accounts for a customer
     */
    public function getExternalAccounts($customerId) {
        $url = $this->baseUrl . '/v0/customers/' . $customerId . '/external_accounts';
        return $this->sendRequest('GET', $url);
    }
    
    /**
     * Get external account details by ID
     */
    public function getExternalAccountDetails($customerId, $externalAccountId) {
        $url = $this->baseUrl . '/v0/customers/' . $customerId . '/external_accounts/' . $externalAccountId;
        return $this->sendRequest('GET', $url);
    }
    
    /**
     * Create external account for buyer
     */
    public function createExternalAccount($customerId, $accountData) {
        $url = $this->baseUrl . '/v0/customers/' . $customerId . '/external_accounts';
        $idempotencyKey = $this->generateUuid();
        return $this->sendRequest('POST', $url, $accountData, $idempotencyKey);
    }
    
    /**
     * Delete external account
     */
    public function deleteExternalAccount($customerId, $externalAccountId) {
        $url = $this->baseUrl . '/v0/customers/' . $customerId . '/external_accounts/' . $externalAccountId;
        return $this->sendRequest('DELETE', $url);
    }
    
    /**
     * Get customer's liquidation addresses
     */
    public function getCustomerLiquidationAddresses($customerId) {
        $url = $this->baseUrl . '/v0/customers/' . $customerId . '/liquidation_addresses';
        return $this->sendRequest('GET', $url);
    }
    
    /**
     * Create a liquidation address
     */
    public function createLiquidationAddress($customerId, $liquidationData) {
        $url = $this->baseUrl . '/v0/customers/' . $customerId . '/liquidation_addresses';
        $idempotencyKey = $this->generateUuid();
        return $this->sendRequest('POST', $url, $liquidationData, $idempotencyKey);
    }
    
    /**
     * Get exchange rate
     */
    public function getExchangeRate($fromCurrency, $toCurrency) {
        $from = ($fromCurrency === 'usdc') ? 'usd' : $fromCurrency;
        $to = ($toCurrency === 'usdc') ? 'usd' : $toCurrency;
        $url = $this->baseUrl . '/v0/exchange_rates?from=' . strtolower($from) . '&to=' . strtolower($to);
        return $this->sendRequest('GET', $url);
    }
}

