<?php
// Ready-to-use airtime purchase script with your credentials

class MTNAirtimePurchaseReady {
    private $credentials;
    
    public function __construct() {
        // Load credentials from file or set directly
        if (file_exists('mtn_credentials.json')) {
            $this->credentials = json_decode(file_get_contents('mtn_credentials.json'), true);
        } else {
            // Fallback - use your credentials directly
            $this->credentials = [
                'subscription_key_primary' => '99e10e2371e9450ab73f79bf374123cd',
                'subscription_key_secondary' => '99513bf335cd4ffd8e060a2305c939ad',
                'api_user' => 'YOUR_API_USER_HERE', // Will be generated
                'api_key' => 'YOUR_API_KEY_HERE',   // Will be generated
                'environment' => 'sandbox',
                'currency' => 'EUR' // EUR for sandbox, NGN for production
            ];
        }
    }
    
    public function setApiCredentials($apiUser, $apiKey) {
        $this->credentials['api_user'] = $apiUser;
        $this->credentials['api_key'] = $apiKey;
    }
    
    public function purchaseAirtime($phoneNumber, $amount) {
        echo "=== MTN MOMO AIRTIME PURCHASE ===\n";
        echo "Account: Isah Tasiu (isahtasiu384@gmail.com)\n";
        echo "Date: 2025-08-29 20:02:32 UTC\n";
        echo "Customer: $phoneNumber\n";
        echo "Amount: " . $this->credentials['currency'] . " $amount\n\n";
        
        try {
            // Step 1: Get Access Token
            echo "Step 1: Getting access token...\n";
            $token = $this->getAccessToken();
            echo "✓ Access token obtained\n\n";
            
            // Step 2: Request Payment
            echo "Step 2: Requesting payment from customer...\n";
            $paymentRef = $this->requestPayment($token, $phoneNumber, $amount);
            echo "✓ Payment request sent\n";
            echo "Reference: $paymentRef\n";
            echo "Customer should approve on MTN MoMo app\n\n";
            
            // Step 3: Monitor Status
            echo "Step 3: Monitoring payment status...\n";
            $result = $this->monitorPayment($token, $paymentRef);
            
            return $result;
            
        } catch (Exception $e) {
            return [
                'success' => false,
                'error' => $e->getMessage()
            ];
        }
    }
    
    private function getAccessToken() {
        $url = 'https://sandbox.momodeveloper.mtn.com/collection/token/';
        
        $headers = [
            'Authorization: Basic ' . base64_encode($this->credentials['api_user'] . ':' . $this->credentials['api_key']),
            'Ocp-Apim-Subscription-Key: ' . $this->credentials['subscription_key_primary'],
            'Content-Type: application/x-www-form-urlencoded'
        ];
        
        $response = $this->makeRequest($url, 'POST', $headers, 'grant_type=client_credentials');
        
        if (!isset($response['access_token'])) {
            throw new Exception('Failed to get access token');
        }
        
        return $response['access_token'];
    }
    
    private function requestPayment($token, $phone, $amount) {
        $referenceId = $this->generateUUID();
        $url = 'https://sandbox.momodeveloper.mtn.com/collection/v1_0/requesttopay';
        
        $headers = [
            'Authorization: Bearer ' . $token,
            'X-Reference-Id: ' . $referenceId,
            'X-Target-Environment: sandbox',
            'Ocp-Apim-Subscription-Key: ' . $this->credentials['subscription_key_primary'],
            'Content-Type: application/json'
        ];
        
        $data = [
            'amount' => (string)$amount,
            'currency' => $this->credentials['currency'],
            'externalId' => 'airtime_' . time(),
            'payer' => [
                'partyIdType' => 'MSISDN',
                'partyId' => $phone
            ],
            'payerMessage' => 'Airtime Purchase',
            'payeeNote' => 'Airtime for ' . $phone
        ];
        
        $this->makeRequest($url, 'POST', $headers, json_encode($data));
        
        return $referenceId;
    }
    
    private function monitorPayment($token, $referenceId) {
        $url = 'https://sandbox.momodeveloper.mtn.com/collection/v1_0/requesttopay/' . $referenceId;
        
        $headers = [
            'Authorization: Bearer ' . $token,
            'X-Target-Environment: sandbox',
            'Ocp-Apim-Subscription-Key: ' . $this->credentials['subscription_key_primary']
        ];
        
        $maxAttempts = 30;
        $attempts = 0;
        
        while ($attempts < $maxAttempts) {
            sleep(5);
            $response = $this->makeRequest($url, 'GET', $headers);
            
            echo "Status check " . ($attempts + 1) . ": " . $response['status'] . "\n";
            
            if ($response['status'] === 'SUCCESSFUL') {
                echo "✓ Payment successful!\n";
                return [
                    'success' => true,
                    'reference' => $referenceId,
                    'message' => 'Airtime purchased successfully'
                ];
            } elseif ($response['status'] === 'FAILED') {
                throw new Exception('Payment failed');
            }
            
            $attempts++;
        }
        
        throw new Exception('Payment timeout');
    }
    
    private function makeRequest($url, $method, $headers, $data = null) {
        $curl = curl_init();
        
        curl_setopt_array($curl, [
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_CUSTOMREQUEST => $method,
            CURLOPT_HTTPHEADER => $headers,
            CURLOPT_TIMEOUT => 30,
            CURLOPT_SSL_VERIFYPEER => false
        ]);
        
        if ($data) {
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        
        $response = curl_exec($curl);
        $httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
        curl_close($curl);
        
        if ($httpCode >= 400) {
            throw new Exception("HTTP Error $httpCode: $response");
        }
        
        return json_decode($response, true);
    }
    
    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)
        );
    }
}

// Usage
$airtime = new MTNAirtimePurchaseReady();

// You'll need to set these after running the setup script
$airtime->setApiCredentials('YOUR_GENERATED_API_USER', 'YOUR_GENERATED_API_KEY');

// Test with sandbox numbers
$result = $airtime->purchaseAirtime('46733123456', 10); // Success test number

if ($result['success']) {
    echo "🎉 SUCCESS: " . $result['message'] . "\n";
} else {
    echo "❌ ERROR: " . $result['error'] . "\n";
}
?>