<?php
// Complete working airtime script
class MTNAirtimeComplete {
    private $baseUrl = 'https://sandbox.momodeveloper.mtn.com';
    private $subscriptionKey;
    private $apiUser;
    private $apiKey;
    
    public function __construct() {
        // Load from saved credentials file
        if (file_exists('mtn_credentials.json')) {
            $creds = json_decode(file_get_contents('mtn_credentials.json'), true);
            $this->subscriptionKey = $creds['subscription_key'];
            $this->apiUser = $creds['api_user'];
            $this->apiKey = $creds['api_key'];
        } else {
            // Use your credentials directly
            $this->subscriptionKey = '99e10e2371e9450ab73f79bf374123cd'; // Primary key
            $this->apiUser = 'd1441bd7-d42a-4857-81f6-42e83d6e07eb';     // Your API User
            $this->apiKey = 'YOUR_API_KEY_HERE';                          // Generated API Key
        }
    }
    
    public function setCredentials($subscriptionKey, $apiUser, $apiKey) {
        $this->subscriptionKey = $subscriptionKey;
        $this->apiUser = $apiUser;
        $this->apiKey = $apiKey;
    }
    
    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";
        echo "API User: " . $this->apiUser . "\n";
        echo "API Key: " . substr($this->apiKey, 0, 8) . "...\n";
        echo "Subscription Key: " . substr($this->subscriptionKey, 0, 8) . "...\n\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\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 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 $phone...\n";
        echo "Amount: EUR $amount\n";
        echo "Reference: $referenceId\n";
        
        $this->makeRequest($url, 'POST', $headers, $data);
        
        echo "✓ Payment request sent\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 "Date: 2025-08-29 20:08:08 UTC\n";
        echo "User: nede32332\n";
        echo "Customer: $phone\n";
        echo "Amount: EUR $amount\n\n";
        
        try {
            // Request payment
            $payment = $this->requestPayment($phone, $amount);
            
            // Monitor payment status
            echo "\nMonitoring payment status...\n";
            $maxAttempts = 30;
            $attempts = 0;
            
            while ($attempts < $maxAttempts) {
                sleep(5);
                $status = $this->checkPaymentStatus($payment['referenceId'], $payment['token']);
                
                echo "Check " . ($attempts + 1) . ": " . $status['status'] . "\n";
                
                if ($status['status'] === 'SUCCESSFUL') {
                    echo "\n🎉 SUCCESS! Airtime purchased successfully!\n";
                    echo "Reference: " . $payment['referenceId'] . "\n";
                    echo "Customer: $phone\n";
                    echo "Amount: EUR $amount\n";
                    return true;
                } elseif ($status['status'] === 'FAILED') {
                    echo "\n❌ Payment failed\n";
                    return false;
                } elseif ($status['status'] === 'REJECTED') {
                    echo "\n❌ Payment rejected by customer\n";
                    return false;
                }
                
                $attempts++;
            }
            
            echo "\n⏰ Payment timeout\n";
            return false;
            
        } catch (Exception $e) {
            echo "\n❌ ERROR: " . $e->getMessage() . "\n";
            return false;
        }
    }
    
    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");
        }
        
        if ($httpCode === 202 || $httpCode === 201) {
            return json_decode($response, true) ?: ['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)
        );
    }
}

// Test the airtime purchase
$airtime = new MTNAirtimeComplete();

// If you have the API key, set it here:
// $airtime->setCredentials('subscription_key', 'd1441bd7-d42a-4857-81f6-42e83d6e07eb', 'your_api_key');

// Test with success number
echo "Testing airtime purchase...\n";
$result = $airtime->purchaseAirtime('46733123456', 10);

if ($result) {
    echo "\n✅ Test completed successfully!\n";
} else {
    echo "\n❌ Test failed\n";
}
?>