<?php
require_once 'flutterwave_config.php';

class Flutterwave {
    private $client_id;
    private $client_secret;
    private $encryption_key;
    private $environment;
    private $access_token;
    
    public function __construct() {
        $this->client_id = FLW_CLIENT_ID;
        $this->client_secret = FLW_CLIENT_SECRET;
        $this->encryption_key = FLW_ENCRYPTION_KEY;
        $this->environment = FLW_ENVIRONMENT;
        $this->getAccessToken();
    }
    
    // Get OAuth Access Token for V4 API
    private function getAccessToken() {
        $url = 'https://api.flutterwave.com/v3/auth/token';
        
        $payload = [
            'client_id' => $this->client_id,
            'client_secret' => $this->client_secret
        ];
        
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Content-Type: application/json'
        ]);
        
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        
        if ($httpCode == 200) {
            $result = json_decode($response, true);
            if (isset($result['status']) && $result['status'] == 'success') {
                $this->access_token = $result['data']['access_token'];
                return true;
            }
        }
        
        return false;
    }
    
    // Initialize payment
    public function initializePayment($data) {
        $url = FLW_API_URL . '/payments';
        
        $payload = [
            'tx_ref' => $data['tx_ref'],
            'amount' => $data['amount'],
            'currency' => $data['currency'] ?? 'NGN',
            'redirect_url' => FLW_REDIRECT_URL,
            'payment_options' => FLW_PAYMENT_OPTIONS,
            'customer' => [
                'email' => $data['email'],
                'name' => $data['name'],
                'phonenumber' => $data['phone'] ?? ''
            ],
            'customizations' => [
                'title' => $data['title'] ?? 'UHD Payment',
                'description' => $data['description'] ?? 'Payment for UHD Services',
                'logo' => 'https://uhd.com.ng/assets/images/logo.png'
            ],
            'meta' => [
                'payment_type' => $data['payment_type'],
                'user_id' => $data['user_id']
            ]
        ];
        
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Authorization: Bearer ' . $this->access_token,
            'Content-Type: application/json'
        ]);
        
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        
        $result = json_decode($response, true);
        
        if ($httpCode == 200 && isset($result['status']) && $result['status'] == 'success') {
            return [
                'success' => true,
                'link' => $result['data']['link'],
                'reference' => $result['data']['reference']
            ];
        }
        
        return [
            'success' => false, 
            'message' => $result['message'] ?? 'Payment initialization failed',
            'code' => $httpCode,
            'response' => $result
        ];
    }
    
    // Verify payment
    public function verifyPayment($reference) {
        $url = FLW_API_URL . "/transactions/{$reference}/verify";
        
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Authorization: Bearer ' . $this->access_token,
            'Content-Type: application/json'
        ]);
        
        $response = curl_exec($ch);
        curl_close($ch);
        
        $result = json_decode($response, true);
        
        if (isset($result['status']) && $result['status'] == 'success') {
            return [
                'success' => true,
                'data' => $result['data']
            ];
        }
        
        return ['success' => false, 'message' => $result['message'] ?? 'Verification failed'];
    }
    
    // Process payout (transfer to bank)
    public function initiatePayout($data) {
        $url = FLW_API_URL . '/transfers';
        
        $payload = [
            'account_bank' => $data['bank_code'],
            'account_number' => $data['account_number'],
            'amount' => $data['amount'],
            'narration' => $data['narration'] ?? 'HPS Wallet Withdrawal',
            'currency' => 'NGN',
            'reference' => $data['reference'],
            'callback_url' => FLW_WEBHOOK_URL
        ];
        
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Authorization: Bearer ' . $this->access_token,
            'Content-Type: application/json'
        ]);
        
        $response = curl_exec($ch);
        curl_close($ch);
        
        return json_decode($response, true);
    }
    
    // Get bank list for payouts
    public function getBankList() {
        $url = FLW_API_URL . '/banks/NG';
        
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Authorization: Bearer ' . $this->access_token,
            'Content-Type: application/json'
        ]);
        
        $response = curl_exec($ch);
        curl_close($ch);
        
        $result = json_decode($response, true);
        
        if (isset($result['status']) && $result['status'] == 'success') {
            return $result['data'];
        }
        
        return [];
    }
}
?>