<?php
/**
 * Marzpay Payment Gateway Integration Class
 * Handles all payment processing with Marzpay
 * API Documentation: https://api.marzpay.io
 */

namespace App\Classes\Payment;

class MarzpayGateway {
    private $apiKey;
    private $apiSecret;
    private $baseUrl;
    private $callbackUrl;
    private $timeout = 30;
    
    public function __construct() {
        $this->apiKey = defined('MARZPAY_API_KEY') ? MARZPAY_API_KEY : env('MARZPAY_API_KEY');
        $this->apiSecret = defined('MARZPAY_API_SECRET') ? MARZPAY_API_SECRET : env('MARZPAY_API_SECRET');
        $this->baseUrl = defined('MARZPAY_BASE_URL') ? MARZPAY_BASE_URL : env('MARZPAY_BASE_URL', 'https://api.marzpay.io');
        $this->callbackUrl = defined('MARZPAY_CALLBACK_URL') ? MARZPAY_CALLBACK_URL : env('MARZPAY_CALLBACK_URL');
        
        if (!$this->apiKey || !$this->apiSecret) {
            throw new \Exception('Marzpay credentials not configured');
        }
    }
    
    /**
     * Create a payment request
     */
    public function createPayment($amount, $currency = 'UGX', $reference = '', $description = '', $metadata = []) {
        $payload = [
            'amount' => $amount,
            'currency' => $currency,
            'reference' => $reference ?: uniqid('order_'),
            'description' => $description ?: 'SMM Services Payment',
            'callback_url' => $this->callbackUrl,
            'metadata' => $metadata,
            'timestamp' => time()
        ];
        
        return $this->request('POST', '/payments', $payload);
    }
    
    /**
     * Get payment status
     */
    public function getPaymentStatus($paymentId) {
        return $this->request('GET', '/payments/' . $paymentId);
    }
    
    /**
     * Verify payment callback
     */
    public function verifyCallback($data) {
        // Verify signature
        if (!$this->verifySignature($data)) {
            throw new \Exception('Invalid callback signature');
        }
        
        return [
            'valid' => true,
            'payment_id' => $data['payment_id'] ?? null,
            'reference' => $data['reference'] ?? null,
            'status' => $data['status'] ?? null,
            'amount' => $data['amount'] ?? null,
            'currency' => $data['currency'] ?? null
        ];
    }
    
    /**
     * Refund a payment
     */
    public function refundPayment($paymentId, $amount = null, $reason = '') {
        $payload = [
            'reason' => $reason ?: 'Customer refund request'
        ];
        
        if ($amount) {
            $payload['amount'] = $amount;
        }
        
        return $this->request('POST', '/payments/' . $paymentId . '/refund', $payload);
    }
    
    /**
     * Get account balance
     */
    public function getBalance() {
        return $this->request('GET', '/account/balance');
    }
    
    /**
     * Get transaction history
     */
    public function getTransactions($limit = 50, $offset = 0) {
        return $this->request('GET', '/transactions?limit=' . $limit . '&offset=' . $offset);
    }
    
    /**
     * Make authenticated API request
     */
    private function request($method = 'GET', $endpoint = '/', $payload = []) {
        try {
            $url = $this->baseUrl . $endpoint;
            $auth = base64_encode($this->apiKey . ':' . $this->apiSecret);
            
            $curl = curl_init();
            
            $headers = [
                'Authorization: Basic ' . $auth,
                'Content-Type: application/json',
                'Accept: application/json'
            ];
            
            curl_setopt_array($curl, [
                CURLOPT_URL => $url,
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_ENCODING => '',
                CURLOPT_MAXREDIRS => 10,
                CURLOPT_TIMEOUT => $this->timeout,
                CURLOPT_FOLLOWLOCATION => true,
                CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                CURLOPT_CUSTOMREQUEST => $method,
                CURLOPT_HTTPHEADER => $headers,
            ]);
            
            if ($method !== 'GET' && !empty($payload)) {
                curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($payload));
            }
            
            $response = curl_exec($curl);
            $httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
            $curlError = curl_error($curl);
            curl_close($curl);
            
            if ($curlError) {
                throw new \Exception('CURL Error: ' . $curlError);
            }
            
            if (!in_array($httpCode, [200, 201, 202])) {
                throw new \Exception('HTTP Error: ' . $httpCode . ' - ' . $response);
            }
            
            $decoded = json_decode($response, true);
            
            if ($decoded === null) {
                throw new \Exception('Invalid JSON response');
            }
            
            return $decoded;
            
        } catch (\Exception $e) {
            error_log('Marzpay API Error: ' . $e->getMessage());
            return [
                'status' => 'error',
                'message' => $e->getMessage()
            ];
        }
    }
    
    /**
     * Verify callback signature (implement your signature verification logic)
     */
    private function verifySignature($data) {
        // This is a placeholder - implement actual signature verification based on Marzpay docs
        if (!isset($data['signature'])) {
            return false;
        }
        
        // Reconstruct the signature based on Marzpay's algorithm
        $expectedSignature = hash_hmac('sha256', json_encode($data), $this->apiSecret);
        
        return hash_equals($expectedSignature, $data['signature']);
    }
    
    /**
     * Check if response is successful
     */
    public static function isSuccess($response) {
        return is_array($response) && ($response['status'] === 'success' || $response['status'] === 'completed' || $response['status'] === 'completed');
    }
    
    /**
     * Get error message from response
     */
    public static function getError($response) {
        if (is_array($response)) {
            return $response['message'] ?? ($response['error'] ?? 'Unknown error');
        }
        return 'Invalid response format';
    }
}
?>
