<?php
// Fixed setup script with proper headers
class MTNNigeriaSetupFixed {
    private $baseUrl = 'https://sandbox.momodeveloper.mtn.com';
    private $subscriptionKey;
    
    public function __construct() {
        // Using your Primary Key
        $this->subscriptionKey = '99e10e2371e9450ab73f79bf374123cd';
    }
    
    public function createApiUser() {
        $referenceId = $this->generateUUID();
        $url = $this->baseUrl . '/v1_0/apiuser';
        
        $data = json_encode([
            'providerCallbackHost' => 'webhook.site'
        ]);
        
        $headers = [
            'X-Reference-Id: ' . $referenceId,
            'Ocp-Apim-Subscription-Key: ' . $this->subscriptionKey,
            'Content-Type: application/json',
            'Content-Length: ' . strlen($data)
        ];
        
        echo "Creating API User...\n";
        echo "Reference ID: $referenceId\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,
            'Content-Length: 0'  // Important: Set content length to 0 for empty body
        ];
        
        echo "Creating API Key for user: $apiUser\n";
        
        $response = $this->makeCurlRequest($url, 'POST', $headers, '');
        
        return $response['apiKey'];
    }
    
    private function makeCurlRequest($url, $method, $headers, $data = '') {
        $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_POSTFIELDS => $data,
            CURLOPT_VERBOSE => false
        ]);
        
        $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) {
            $decoded = json_decode($response, true);
            if ($decoded === null) {
                echo "✓ Request successful (201 Created)\n";
                return ['success' => true];
            }
            return $decoded;
        }
        
        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)
        );
    }
}

// Quick fix for the existing API User
echo "=== QUICK FIX FOR YOUR EXISTING API USER ===\n";
echo "Your API User: d1441bd7-d42a-4857-81f6-42e83d6e07eb\n";
echo "Let's create the API Key for this user...\n\n";

try {
    $setup = new MTNNigeriaSetupFixed();
    
    // Use your existing API User from the previous attempt
    $existingApiUser = 'd1441bd7-d42a-4857-81f6-42e83d6e07eb';
    
    echo "Creating API Key for existing user...\n";
    $apiKey = $setup->createApiKey($existingApiUser);
    echo "✓ API Key created: $apiKey\n\n";
    
    echo "=== 🎉 YOUR COMPLETE CREDENTIALS ===\n";
    echo "Subscription Key: 99e10e2371e9450ab73f79bf374123cd\n";
    echo "API User: $existingApiUser\n";
    echo "API Key: $apiKey\n";
    echo "Target Environment: sandbox\n";
    echo "Currency: EUR\n\n";
    
    // Save to file
    $credentials = [
        'subscription_key' => '99e10e2371e9450ab73f79bf374123cd',
        'api_user' => $existingApiUser,
        'api_key' => $apiKey,
        'environment' => 'sandbox',
        'currency' => 'EUR',
        'created_at' => '2025-08-29 20:08:08 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 "\nLet's try with Secondary Key...\n";
    
    // Try with secondary key
    try {
        $setupSecondary = new class {
            private $baseUrl = 'https://sandbox.momodeveloper.mtn.com';
            private $subscriptionKey = '99513bf335cd4ffd8e060a2305c939ad'; // Secondary key
            
            public function createApiKey($apiUser) {
                $url = $this->baseUrl . '/v1_0/apiuser/' . $apiUser . '/apikey';
                
                $headers = [
                    'Ocp-Apim-Subscription-Key: ' . $this->subscriptionKey,
                    'Content-Length: 0'
                ];
                
                $curl = curl_init();
                curl_setopt_array($curl, [
                    CURLOPT_URL => $url,
                    CURLOPT_RETURNTRANSFER => true,
                    CURLOPT_CUSTOMREQUEST => 'POST',
                    CURLOPT_HTTPHEADER => $headers,
                    CURLOPT_TIMEOUT => 30,
                    CURLOPT_SSL_VERIFYPEER => false,
                    CURLOPT_POSTFIELDS => ''
                ]);
                
                $response = curl_exec($curl);
                $httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
                curl_close($curl);
                
                if ($httpCode >= 400) {
                    throw new Exception("HTTP Error $httpCode: $response");
                }
                
                $decoded = json_decode($response, true);
                return $decoded['apiKey'];
            }
        };
        
        echo "Trying with Secondary Key...\n";
        $apiKey = $setupSecondary->createApiKey($existingApiUser);
        echo "✓ Success with Secondary Key!\n";
        echo "API Key: $apiKey\n";
        
        $credentials = [
            'subscription_key' => '99513bf335cd4ffd8e060a2305c939ad', // Secondary key worked
            'api_user' => $existingApiUser,
            'api_key' => $apiKey,
            'environment' => 'sandbox',
            'currency' => 'EUR'
        ];
        
        file_put_contents('mtn_credentials.json', json_encode($credentials, JSON_PRETTY_PRINT));
        echo "✓ Credentials saved with Secondary Key\n";
        
    } catch (Exception $e2) {
        echo "❌ Secondary Key also failed: " . $e2->getMessage() . "\n";
    }
}
?>