<?php
// Working MTN MoMo Airtime Purchase Script
// Credentials: Isah Tasiu (nede32332)
// Date: 2025-08-29 20:11:06 UTC

class MTNAirtimeWorking {
    private $baseUrl = 'https://sandbox.momodeveloper.mtn.com';
    private $subscriptionKey = '99e10e2371e9450ab73f79bf374123cd';
    private $apiUser = 'd1441bd7-d42a-4857-81f6-42e83d6e07eb';
    private $apiKey = '13bb99363dd947ee92788c0af856f4a9';
    
    public function getAccessToken() {
        $url = $this->baseUrl . '/collection/token/';
        
        $data = 'grant_type=client_credentials';
        
        $headers = [
            'Authorization: Basic ' . base64_encode($this->apiUser . ':' . $this->apiKey),
            'Ocp-Apim-Subscription-Key: ' . $this->subscriptionKey,
            'Content-Type: application/x-www-form-urlencoded',
            'Content-Length: ' . strlen($data)
        ];
        
        echo "🔐 Getting access token...\n";
        
        $response = $this->makeRequest($url, 'POST', $headers, $data);
        
        if (!isset($response['access_token'])) {
            throw new Exception('Failed to get access token: ' . json_encode($response));
        }
        
        echo "✅ Access token obtained successfully\n";
        return $response['access_token'];
    }
    
    public function requestPayment($phone, $amount) {
        $token = $this->getAccessToken();
        $referenceId = $this->generateUUID();
        
        $url = $this->baseUrl . '/collection/v1_0/requesttopay';
        
        $requestData = [
            'amount' => (string)$amount,
            'currency' => 'EUR',
            'externalId' => 'airtime_' . time(),
            'payer' => [
                'partyIdType' => 'MSISDN',
                'partyId' => $phone
            ],
            'payerMessage' => 'Airtime Purchase',
            'payeeNote' => 'Airtime top-up for ' . $phone
        ];
        
        $data = json_encode($requestData);
        
        $headers = [
            'Authorization: Bearer ' . $token,
            'X-Reference-Id: ' . $referenceId,
            'X-Target-Environment: sandbox',
            'Ocp-Apim-Subscription-Key: ' . $this->subscriptionKey,
            'Content-Type: application/json',
            'Content-Length: ' . strlen($data)
        ];
        
        echo "💰 Requesting payment from customer...\n";
        echo "📱 Phone: $phone\n";
        echo "💵 Amount: €$amount\n";
        echo "🆔 Reference: $referenceId\n";
        
        $this->makeRequest($url, 'POST', $headers, $data);
        
        echo "✅ Payment request sent successfully\n";
        echo "📲 Customer should approve on their mobile device\n\n";
        
        return ['referenceId' => $referenceId, 'token' => $token];
    }
    
    public function checkPaymentStatus($referenceId, $token) {
        $url = $this->baseUrl . '/collection/v1_0/requesttopay/' . $referenceId;
        
        $headers = [
            'Authorization: Bearer ' . $token,
            'X-Target-Environment: sandbox',
            'Ocp-Apim-Subscription-Key: ' . $this->subscriptionKey
        ];
        
        $response = $this->makeRequest($url, 'GET', $headers);
        return $response;
    }
    
    public function purchaseAirtime($phone, $amount) {
        echo "🚀 === MTN MOMO AIRTIME PURCHASE === 🚀\n";
        echo "👤 Account: Isah Tasiu (isahtasiu384@gmail.com)\n";
        echo "👤 User: nede32332\n";
        echo "📅 Date: 2025-08-29 20:11:06 UTC\n";
        echo "🎯 Environment: Sandbox\n";
        echo "📱 Customer: $phone\n";
        echo "💰 Amount: €$amount EUR\n";
        echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n\n";
        
        try {
            // Step 1: Request payment
            echo "📋 STEP 1: Requesting Payment\n";
            $payment = $this->requestPayment($phone, $amount);
            
            // Step 2: Monitor payment status
            echo "⏳ STEP 2: Monitoring Payment Status\n";
            echo "🔄 Checking payment status (max 5 minutes)...\n";
            
            $maxAttempts = 60; // 5 minutes with 5-second intervals
            $attempts = 0;
            
            while ($attempts < $maxAttempts) {
                sleep(5);
                $status = $this->checkPaymentStatus($payment['referenceId'], $payment['token']);
                
                $statusIcon = $this->getStatusIcon($status['status']);
                echo "🔍 Check " . ($attempts + 1) . "/60: $statusIcon " . $status['status'] . "\n";
                
                if ($status['status'] === 'SUCCESSFUL') {
                    echo "\n🎉 === SUCCESS! === 🎉\n";
                    echo "✅ Airtime purchased successfully!\n";
                    echo "🆔 Reference: " . $payment['referenceId'] . "\n";
                    echo "📱 Customer: $phone\n";
                    echo "💰 Amount: €$amount EUR\n";
                    echo "📅 Completed: " . date('Y-m-d H:i:s') . " UTC\n";
                    echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n";
                    
                    return [
                        'success' => true,
                        'referenceId' => $payment['referenceId'],
                        'phone' => $phone,
                        'amount' => $amount,
                        'currency' => 'EUR',
                        'timestamp' => date('Y-m-d H:i:s') . ' UTC'
                    ];
                    
                } elseif ($status['status'] === 'FAILED') {
                    echo "\n❌ === FAILED === ❌\n";
                    echo "Payment failed\n";
                    echo "🆔 Reference: " . $payment['referenceId'] . "\n";
                    if (isset($status['reason'])) {
                        echo "📋 Reason: " . $status['reason'] . "\n";
                    }
                    return ['success' => false, 'error' => 'Payment failed'];
                    
                } elseif ($status['status'] === 'REJECTED') {
                    echo "\n🚫 === REJECTED === 🚫\n";
                    echo "Payment rejected by customer\n";
                    echo "🆔 Reference: " . $payment['referenceId'] . "\n";
                    return ['success' => false, 'error' => 'Payment rejected'];
                }
                
                $attempts++;
            }
            
            echo "\n⏰ === TIMEOUT === ⏰\n";
            echo "Payment timeout - customer did not approve within 5 minutes\n";
            echo "🆔 Reference: " . $payment['referenceId'] . "\n";
            return ['success' => false, 'error' => 'Payment timeout'];
            
        } catch (Exception $e) {
            echo "\n💥 === ERROR === 💥\n";
            echo "❌ Error: " . $e->getMessage() . "\n";
            echo "📅 Time: " . date('Y-m-d H:i:s') . " UTC\n";
            return ['success' => false, 'error' => $e->getMessage()];
        }
    }
    
    private function getStatusIcon($status) {
        switch ($status) {
            case 'PENDING': return '⏳';
            case 'SUCCESSFUL': return '✅';
            case 'FAILED': return '❌';
            case 'REJECTED': return '🚫';
            default: return '❓';
        }
    }
    
    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 !== null) {
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        
        $response = curl_exec($curl);
        $httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
        $error = curl_error($curl);
        
        curl_close($curl);
        
        if ($error) {
            throw new Exception('CURL Error: ' . $error);
        }
        
        if ($httpCode >= 400) {
            throw new Exception("HTTP Error $httpCode: $response");
        }
        
        // For 202 Accepted (async operations) and 201 Created
        if ($httpCode === 202 || $httpCode === 201) {
            $decoded = json_decode($response, true);
            return $decoded ?: ['success' => true];
        }
        
        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)
        );
    }
}

// === TESTING SCENARIOS ===
echo "🧪 === MTN MOMO AIRTIME TESTING === 🧪\n";
echo "📅 Date: 2025-08-29 20:11:06 UTC\n";
echo "👤 User: nede32332 (Isah Tasiu)\n";
echo "🎯 Environment: Sandbox\n";
echo "💱 Currency: EUR\n\n";

$airtime = new MTNAirtimeWorking();

// Test scenarios
$testScenarios = [
    ['phone' => '46733123456', 'amount' => 10, 'expected' => 'SUCCESS'],
    ['phone' => '46733123450', 'amount' => 5, 'expected' => 'FAILED'],
    ['phone' => '46733123451', 'amount' => 15, 'expected' => 'REJECTED']
];

echo "🎭 Available Test Scenarios:\n";
foreach ($testScenarios as $i => $scenario) {
    echo ($i + 1) . ". Phone: {$scenario['phone']} | Amount: €{$scenario['amount']} | Expected: {$scenario['expected']}\n";
}

echo "\n🚀 Starting Test 1 (Success scenario)...\n";
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n\n";

// Run the success test
$result = $airtime->purchaseAirtime('46733123456', 10);

echo "\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n";
echo "🏁 === FINAL RESULT === 🏁\n";

if ($result['success']) {
    echo "🎉 Airtime purchase completed successfully!\n";
    echo "📋 Details:\n";
    echo "   🆔 Reference: " . $result['referenceId'] . "\n";
    echo "   📱 Phone: " . $result['phone'] . "\n";
    echo "   💰 Amount: €" . $result['amount'] . " " . $result['currency'] . "\n";
    echo "   📅 Time: " . $result['timestamp'] . "\n";
} else {
    echo "❌ Airtime purchase failed\n";
    echo "📋 Error: " . $result['error'] . "\n";
}

echo "\n💡 === NEXT STEPS === 💡\n";
echo "1. ✅ Your API credentials are working!\n";
echo "2. 🔄 Test with different phone numbers for various scenarios\n";
echo "3. 🏭 For production, change environment and use NGN currency\n";
echo "4. 🔧 Integrate this into your application\n";
echo "5. 📱 Add Nigerian phone number formatting for production\n";
?>