<?php
/**
 * KamiPay API Integration Class
 * Integración completa con el sistema de pagos PIX de KamiPay
 * 
 * @author Panel L2Jade
 * @version 1.0
 */

class KamiPayAPI {
    private $baseUrl;
    private $username;
    private $password;
    private $accessToken;
    private $tokenExpiry;
    private $logFile;
    
    public function __construct($isDevelopment = true) {
        // URLs base según el entorno
        $this->baseUrl = $isDevelopment 
            ? 'https://devnakamotoapi2.kamipay.io' 
            : 'https://api2.kamipay.io';
            
        // Configurar credenciales (estas deben ser proporcionadas por KamiPay)
        $this->username = $isDevelopment ? 'YOUR_DEV_USERNAME' : 'YOUR_PROD_USERNAME';
        $this->password = $isDevelopment ? 'YOUR_DEV_PASSWORD' : 'YOUR_PROD_PASSWORD';
        
        $this->logFile = __DIR__ . '/../kamipay_log.txt';
        
        // Cargar token existente si está disponible
        $this->loadStoredToken();
    }
    
    /**
     * Obtener token de acceso JWT
     */
    public function authenticate() {
        try {
            $url = $this->baseUrl . '/auth/token';
            
            // Crear FormData
            $postData = [
                'username' => $this->username,
                'password' => $this->password
            ];
            
            $ch = curl_init();
            curl_setopt_array($ch, [
                CURLOPT_URL => $url,
                CURLOPT_POST => true,
                CURLOPT_POSTFIELDS => $postData,
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_TIMEOUT => 30,
                CURLOPT_SSL_VERIFYPEER => true,
                CURLOPT_HTTPHEADER => [
                    'User-Agent: L2Jade-Panel/1.0'
                ]
            ]);
            
            $response = curl_exec($ch);
            $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            $error = curl_error($ch);
            curl_close($ch);
            
            if ($error) {
                throw new Exception("cURL Error: " . $error);
            }
            
            if ($httpCode !== 200) {
                throw new Exception("HTTP Error: " . $httpCode . " - " . $response);
            }
            
            $data = json_decode($response, true);
            
            if (!isset($data['access_token'])) {
                throw new Exception("No access token received: " . $response);
            }
            
            $this->accessToken = $data['access_token'];
            $this->tokenExpiry = time() + 3600; // Token válido por 1 hora
            
            // Guardar token para reutilización
            $this->storeToken();
            
            $this->log("Authentication successful");
            return true;
            
        } catch (Exception $e) {
            $this->log("Authentication failed: " . $e->getMessage());
            return false;
        }
    }
    
    /**
     * Verificar si el token es válido
     */
    private function isTokenValid() {
        return !empty($this->accessToken) && time() < $this->tokenExpiry;
    }
    
    /**
     * Asegurar que tenemos un token válido
     */
    private function ensureAuthenticated() {
        if (!$this->isTokenValid()) {
            if (!$this->authenticate()) {
                throw new Exception("Failed to authenticate with KamiPay API");
            }
        }
    }
    
    /**
     * Obtener cotización en tiempo real
     * 
     * @param string $pair Par de monedas (BRLUSDT, USDTBRL)
     * @param string $type Tipo de operación (charge, pay)
     * @param float $amount Cantidad
     * @return array|false
     */
    public function getOracle($pair = 'BRLUSDT', $type = 'charge', $amount = 100.0) {
        try {
            $this->ensureAuthenticated();
            
            $url = $this->baseUrl . '/v2/oracle?' . http_build_query([
                'pair' => $pair,
                'type' => $type,
                'amount' => $amount,
                'chain' => 'polygon'
            ]);
            
            $ch = curl_init();
            curl_setopt_array($ch, [
                CURLOPT_URL => $url,
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_TIMEOUT => 30,
                CURLOPT_SSL_VERIFYPEER => true,
                CURLOPT_HTTPHEADER => [
                    'Authorization: Bearer ' . $this->accessToken,
                    'Content-Type: application/json',
                    'User-Agent: L2Jade-Panel/1.0'
                ]
            ]);
            
            $response = curl_exec($ch);
            $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            $error = curl_error($ch);
            curl_close($ch);
            
            if ($error) {
                throw new Exception("cURL Error: " . $error);
            }
            
            if ($httpCode !== 200) {
                throw new Exception("HTTP Error: " . $httpCode . " - " . $response);
            }
            
            $data = json_decode($response, true);
            
            if ($data['status_code'] !== 200) {
                throw new Exception("API Error: " . $data['msg']);
            }
            
            $this->log("Oracle request successful for $pair $type $amount");
            return $data['data'];
            
        } catch (Exception $e) {
            $this->log("Oracle request failed: " . $e->getMessage());
            return false;
        }
    }
    
    /**
     * Crear QR Code PIX dinámico
     * 
     * @param string $address Dirección de wallet USDT
     * @param float $amountBRL Cantidad en BRL
     * @param int $expireSeconds Tiempo de expiración en segundos
     * @param string $externalReference Referencia externa opcional
     * @return array|false
     */
    public function createPixQR($address, $amountBRL, $expireSeconds = 300, $externalReference = '') {
        try {
            $this->ensureAuthenticated();
            
            $url = $this->baseUrl . '/v2/charge/create_dynamic_pix_b2b';
            
            $postData = [
                'address' => $address,
                'expire' => $expireSeconds,
                'amount' => $amountBRL,
                'chain' => 'polygon'
            ];
            
            if (!empty($externalReference)) {
                $postData['external_reference'] = $externalReference;
            }
            
            $ch = curl_init();
            curl_setopt_array($ch, [
                CURLOPT_URL => $url,
                CURLOPT_POST => true,
                CURLOPT_POSTFIELDS => json_encode($postData),
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_TIMEOUT => 30,
                CURLOPT_SSL_VERIFYPEER => true,
                CURLOPT_HTTPHEADER => [
                    'Authorization: Bearer ' . $this->accessToken,
                    'Content-Type: application/json',
                    'User-Agent: L2Jade-Panel/1.0'
                ]
            ]);
            
            $response = curl_exec($ch);
            $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            $error = curl_error($ch);
            curl_close($ch);
            
            if ($error) {
                throw new Exception("cURL Error: " . $error);
            }
            
            if ($httpCode !== 200) {
                throw new Exception("HTTP Error: " . $httpCode . " - " . $response);
            }
            
            $data = json_decode($response, true);
            
            if (!isset($data['emv']) || !isset($data['operation_id'])) {
                throw new Exception("Invalid response: " . $response);
            }
            
            $this->log("PIX QR created successfully. Operation ID: " . $data['operation_id']);
            return $data;
            
        } catch (Exception $e) {
            $this->log("PIX QR creation failed: " . $e->getMessage());
            return false;
        }
    }
    
    /**
     * Verificar estado de transacción
     * 
     * @param string $operationId ID de operación
     * @param string $type Tipo (charge, pay)
     * @return array|false
     */
    public function getTransactionStatus($operationId, $type = 'charge') {
        try {
            $this->ensureAuthenticated();
            
            $url = $this->baseUrl . '/v2/status/tx_status?' . http_build_query([
                'target' => 'operation_id',
                'type' => $type,
                'id' => $operationId,
                'chain' => 'polygon'
            ]);
            
            $ch = curl_init();
            curl_setopt_array($ch, [
                CURLOPT_URL => $url,
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_TIMEOUT => 30,
                CURLOPT_SSL_VERIFYPEER => true,
                CURLOPT_HTTPHEADER => [
                    'Authorization: Bearer ' . $this->accessToken,
                    'Content-Type: application/json',
                    'User-Agent: L2Jade-Panel/1.0'
                ]
            ]);
            
            $response = curl_exec($ch);
            $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            $error = curl_error($ch);
            curl_close($ch);
            
            if ($error) {
                throw new Exception("cURL Error: " . $error);
            }
            
            if ($httpCode !== 200) {
                throw new Exception("HTTP Error: " . $httpCode . " - " . $response);
            }
            
            $data = json_decode($response, true);
            
            $this->log("Status check for operation $operationId: " . $data['status']);
            return $data;
            
        } catch (Exception $e) {
            $this->log("Status check failed: " . $e->getMessage());
            return false;
        }
    }
    
    /**
     * Guardar token para reutilización
     */
    private function storeToken() {
        $tokenData = [
            'access_token' => $this->accessToken,
            'expiry' => $this->tokenExpiry
        ];
        
        $tokenFile = __DIR__ . '/../kamipay_token.json';
        file_put_contents($tokenFile, json_encode($tokenData), LOCK_EX);
    }
    
    /**
     * Cargar token almacenado
     */
    private function loadStoredToken() {
        $tokenFile = __DIR__ . '/../kamipay_token.json';
        
        if (file_exists($tokenFile)) {
            $tokenData = json_decode(file_get_contents($tokenFile), true);
            
            if ($tokenData && isset($tokenData['access_token']) && $tokenData['expiry'] > time()) {
                $this->accessToken = $tokenData['access_token'];
                $this->tokenExpiry = $tokenData['expiry'];
            }
        }
    }
    
    /**
     * Logging de eventos
     */
    private function log($message) {
        $timestamp = date('Y-m-d H:i:s');
        $logEntry = "[$timestamp] KamiPay: $message" . PHP_EOL;
        file_put_contents($this->logFile, $logEntry, FILE_APPEND | LOCK_EX);
    }
    
    /**
     * Obtener configuración recomendada de wallet USDT
     * Esta dirección debe ser proporcionada por KamiPay y estar en whitelist
     */
    public function getDefaultWalletAddress() {
        // Esta dirección debe ser configurada según las instrucciones de KamiPay
        return "0x46d52020**********1fbdcc297d"; // Placeholder - reemplazar con dirección real
    }
}
?>
