<?php
// app/Payment/Flutterwave.php - Flutterwave Payment Gateway Integration

class Flutterwave implements PaymentInterface {
    private $secret_key;
    private $public_key;
    private $encryption_key;
    private $base_url = 'https://api.flutterwave.com/v3';
    
    public function __construct() {
        $this->secret_key = FLW_SECRET_KEY;
        $this->public_key = FLW_PUBLIC_KEY;
        $this->encryption_key = FLW_ENCRYPTION_KEY;
    }
    
    /**
     * Initialize payment
     */
    public function initialize($data) {
        $url = $this->base_url . '/payments';
        
        $fields = [
            'tx_ref' => $data['reference'],
            'amount' => $data['amount'],
            'currency' => 'NGN',
            'redirect_url' => $data['callback_url'] ?? APP_URL . '/customer/payment-callback.php',
            'payment_options' => 'card,banktransfer,ussd',
            'customer' => [
                'email' => $data['email'],
                'name' => $data['customer_name'] ?? 'Customer'
            ],
            'customizations' => [
                'title' => APP_NAME,
                'description' => 'Payment for Order #' . ($data['order_number'] ?? ''),
                'logo' => APP_URL . '/public/assets/images/logo.png'
            ],
            'meta' => [
                'order_id' => $data['order_id'] ?? null,
                'order_number' => $data['order_number'] ?? null
            ]
        ];
        
        $response = $this->makeRequest($url, 'POST', $fields);
        
        if ($response['status'] === 'success' && isset($response['data']['link'])) {
            return [
                'success' => true,
                'authorization_url' => $response['data']['link'],
                'reference' => $data['reference']
            ];
        }
        
        return [
            'success' => false,
            'message' => $response['message'] ?? 'Payment initialization failed'
        ];
    }
    
    /**
     * Verify payment
     */
    public function verify($reference) {
        $url = $this->base_url . '/transactions/verify_by_reference?tx_ref=' . $reference;
        
        $response = $this->makeRequest($url, 'GET');
        
        if ($response['status'] === 'success' && $response['data']['status'] === 'successful') {
            return [
                'success' => true,
                'status' => 'success',
                'amount' => $response['data']['amount'],
                'reference' => $response['data']['tx_ref'],
                'transaction_id' => $response['data']['id'],
                'transaction_date' => $response['data']['created_at'],
                'channel' => $response['data']['payment_type'] ?? 'card',
                'currency' => $response['data']['currency'] ?? 'NGN',
                'gateway_response' => $response['data']['processor_response'] ?? 'Successful',
                'customer' => [
                    'email' => $response['data']['customer']['email'] ?? null,
                    'name' => $response['data']['customer']['name'] ?? null
                ],
                'metadata' => $response['data']['meta'] ?? []
            ];
        }
        
        return [
            'success' => false,
            'status' => $response['data']['status'] ?? 'failed',
            'message' => $response['message'] ?? 'Payment verification failed'
        ];
    }
    
    /**
     * Process refund
     */
    public function refund($reference, $amount = null) {
        // Get transaction details first
        $transaction = $this->getTransaction($reference);
        
        if (!$transaction['success']) {
            return [
                'success' => false,
                'message' => 'Transaction not found'
            ];
        }
        
        $transaction_id = $transaction['data']['id'];
        $url = $this->base_url . '/transactions/' . $transaction_id . '/refund';
        
        $fields = [];
        
        // If partial refund, specify amount
        if ($amount !== null) {
            $fields['amount'] = $amount;
        }
        
        $response = $this->makeRequest($url, 'POST', $fields);
        
        if ($response['status'] === 'success') {
            return [
                'success' => true,
                'message' => 'Refund processed successfully',
                'refund_id' => $response['data']['id'] ?? null,
                'status' => $response['data']['status'] ?? 'pending'
            ];
        }
        
        return [
            'success' => false,
            'message' => $response['message'] ?? 'Refund processing failed'
        ];
    }
    
    /**
     * Get transaction details
     */
    public function getTransaction($reference) {
        $url = $this->base_url . '/transactions/verify_by_reference?tx_ref=' . $reference;
        
        $response = $this->makeRequest($url, 'GET');
        
        if ($response['status'] === 'success') {
            return [
                'success' => true,
                'data' => $response['data']
            ];
        }
        
        return [
            'success' => false,
            'message' => $response['message'] ?? 'Transaction not found'
        ];
    }
    
    /**
     * Get public key
     */
    public function getPublicKey() {
        return $this->public_key;
    }
    
    /**
     * Get encryption key
     */
    public function getEncryptionKey() {
        return $this->encryption_key;
    }
    
    /**
     * Make API request
     */
    private function makeRequest($url, $method = 'GET', $data = null) {
        $ch = curl_init();
        
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Authorization: Bearer ' . $this->secret_key,
            'Content-Type: application/json'
        ]);
        
        if ($method === 'POST') {
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
        }
        
        $response = curl_exec($ch);
        $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        
        if (curl_errno($ch)) {
            $error = curl_error($ch);
            curl_close($ch);
            
            log_message("Flutterwave API Error: {$error}", 'error');
            
            return [
                'status' => 'error',
                'message' => 'Connection error: ' . $error
            ];
        }
        
        curl_close($ch);
        
        $result = json_decode($response, true);
        
        if ($http_code >= 200 && $http_code < 300) {
            return $result;
        }
        
        log_message("Flutterwave API Error: HTTP {$http_code} - " . ($result['message'] ?? 'Unknown error'), 'error');
        
        return [
            'status' => 'error',
            'message' => $result['message'] ?? 'API request failed',
            'http_code' => $http_code
        ];
    }
    
    /**
     * Validate webhook signature
     */
    public function validateWebhook($signature) {
        return $signature === $this->secret_key;
    }
}