<?php
// Setup script using your actual MTN Developer credentials
class MTNNigeriaSetupWithCredentials {
    private $baseUrl = 'https://sandbox.momodeveloper.mtn.com';
    private $subscriptionKey;
    
    public function __construct() {
        // Using your Primary Key from the screenshot
        $this->subscriptionKey = '99e10e2371e9450ab73f79bf374123cd';
    }
    
    public function createApiUser() {
        $referenceId = $this->generateUUID();
        $url = $this->baseUrl . '/v1_0/apiuser';
        
        $headers = [
            'X-Reference-Id: ' . $referenceId,
            'Ocp-Apim-Subscription-Key: ' . $this->subscriptionKey,
            'Content-Type: application/json'
        ];
        
        $data = json_encode([
            'providerCallbackHost' => 'webhook.site' // For testing
        ]);
        
        echo "Creating API User...\n";
        echo "URL: $url\n";
        echo "Reference ID: $referenceId\n";
        echo "Subscription Key: " . $this->subscriptionKey . "\n\n";
        
        $this->makeCurlRequest($url, 'POST', $headers, $data);
        
        return $referenceId;
    }
    
    public function createApiKey($apiUser) {
        $url = $this->baseUrl . '/v1_0/apiuser/' . $apiUser . '/apikey';
        
        $headers = [
            'Ocp-Apim-Subscription-Key: ' . $this->subscriptionKey
        ];
        
        echo "Creating API Key for user: $apiUser\n";
        echo "URL: $url\n\n";
        
        $response = $this->makeCurlRequest($url, 'POST', $headers);
        
        return $response['apiKey'];
    }
    
    public function getApiUserDetails($apiUser) {
        $url = $this->baseUrl . '/v1_0/apiuser/' . $apiUser;
        
        $headers = [
            'Ocp-Apim-Subscription-Key: ' . $this->subscriptionKey
        ];
        
        echo "Getting API User details...\n";
        
        try {
            $response = $this->makeCurlRequest($url, 'GET', $headers);
            return $response;
        } catch (Exception $e) {
            echo "Note: Could not get user details (this is normal if user was just created)\n";
            return null;
        }
    }
    
    private function makeCurlRequest($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,
            CURLOPT_VERBOSE => true
        ]);
        
        if ($data && ($method === 'POST' || $method === 'PUT')) {
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        
        $response = curl_exec($curl);
        $httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
        $error = curl_error($curl);
        
        curl_close($curl);
        
        echo "HTTP Response Code: $httpCode\n";
        
        if ($error) {
            throw new Exception('CURL Error: ' . $error);
        }
        
        if ($httpCode >= 400) {
            echo "Error Response: $response\n";
            throw new Exception('HTTP Error ' . $httpCode . ': ' . $response);
        }
        
        if ($httpCode === 201 && empty($response)) {
            echo "✓ Request successful (201 Created)\n";
            return ['success' => true];
        }
        
        $decoded = json_decode($response, true);
        if ($decoded === null && !empty($response)) {
            echo "Raw Response: $response\n";
        }
        
        return $decoded;
    }
    
    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)
        );
    }
}

// Run the setup
try {
    echo "=== MTN Nigeria Sandbox Setup for Isah Tasiu ===\n";
    echo "Email: isahtasiu384@gmail.com\n";
    echo "Date: 2025-08-29 20:02:32 UTC\n";
    echo "User: nede32332\n\n";
    
    $setup = new MTNNigeriaSetupWithCredentials();
    
    echo "Step 1: Creating API User...\n";
    $apiUser = $setup->createApiUser();
    echo "✓ API User created: $apiUser\n\n";
    
    echo "Step 2: Creating API Key...\n";
    $apiKey = $setup->createApiKey($apiUser);
    echo "✓ API Key created: $apiKey\n\n";
    
    echo "Step 3: Getting user details...\n";
    $userDetails = $setup->getApiUserDetails($apiUser);
    if ($userDetails) {
        echo "User Details: " . json_encode($userDetails, JSON_PRETTY_PRINT) . "\n\n";
    }
    
    echo "=== 🎉 YOUR COMPLETE CREDENTIALS ===\n";
    echo "Subscription Key (Primary): 99e10e2371e9450ab73f79bf374123cd\n";
    echo "Subscription Key (Secondary): 99513bf335cd4ffd8e060a2305c939ad\n";
    echo "API User: $apiUser\n";
    echo "API Key: $apiKey\n";
    echo "Target Environment: sandbox\n";
    echo "Currency: EUR (sandbox) / NGN (production)\n";
    echo "Account Holder: Isah Tasiu (isahtasiu384@gmail.com)\n\n";
    
    echo "=== NEXT STEPS ===\n";
    echo "1. Copy these credentials\n";
    echo "2. Update the main airtime script\n";
    echo "3. Test with sandbox phone numbers\n";
    echo "4. For production, change environment to 'production'\n\n";
    
    // Save credentials to file
    $credentials = [
        'subscription_key_primary' => '99e10e2371e9450ab73f79bf374123cd',
        'subscription_key_secondary' => '99513bf335cd4ffd8e060a2305c939ad',
        'api_user' => $apiUser,
        'api_key' => $apiKey,
        'environment' => 'sandbox',
        'target_environment' => 'sandbox',
        'currency' => 'EUR',
        'account_email' => 'isahtasiu384@gmail.com',
        'account_name' => 'Isah Tasiu',
        'created_at' => '2025-08-29 20:02:32 UTC'
    ];
    
    file_put_contents('mtn_credentials.json', json_encode($credentials, JSON_PRETTY_PRINT));
    echo "✓ Credentials saved to mtn_credentials.json\n";
    
} catch (Exception $e) {
    echo "❌ Error: " . $e->getMessage() . "\n";
    echo "\nIf you get a 401 error, try using your Secondary Key instead:\n";
    echo "Secondary Key: 99513bf335cd4ffd8e060a2305c939ad\n";
}
?>