<?php 
// Include session handling
include 'services/session.php'; 

// Check if user is logged in
if (!$_SESSION['user'] || !isset($_SESSION['user'])) {
   header('Location: auth-login.php?error=session_expired');
   exit();
}

// Get user role and permissions
$user_role = $_SESSION['role_name'] ?? 'Customer';
$user_id = $_SESSION['user_id'] ?? 0;

// Include database connection
require_once 'layouts/dbconn.php';

// Check if user has API access
$has_api_access = false;
if ($user_role === 'Customer') {
   $stmt = $conn->prepare("
       SELECT COUNT(*) as count 
       FROM licenses l 
       JOIN products p ON l.product_id = p.product_id 
       WHERE l.user_id = ? AND l.status = 'ACTIVE' 
       AND (p.product_type = 'API_ACCESS' OR p.features LIKE '%api_access%')
   ");
   $stmt->bind_param("i", $user_id);
   $stmt->execute();
   $result = $stmt->get_result()->fetch_assoc();
   $has_api_access = $result['count'] > 0;
   $stmt->close();
} else {
   $has_api_access = true;
}

// CORRECTED: MTN MoMo API Configuration Class with fixes from working Python script
class MTNMoMoCredentialManager {
   private $subscription_key;
   private $environment;
   private $base_url;
   private $conn;
   
   public function __construct($subscription_key, $environment = 'sandbox', $conn = null) {
       $this->subscription_key = $subscription_key;
       $this->environment = $environment;
       $this->conn = $conn;
       
       // Use correct MTN sandbox URLs
       if ($environment === 'production') {
           $this->base_url = 'https://momodeveloper.mtn.com';
       } else {
           $this->base_url = 'https://sandbox.momodeveloper.mtn.com';
       }
   }
   
   // FIXED: Proper UUID generation matching Python uuid.uuid4()
   public function generateApiUser() {
       $data = random_bytes(16);
       $data[6] = chr(ord($data[6]) & 0x0f | 0x40); // Version 4
       $data[8] = chr(ord($data[8]) & 0x3f | 0x80); // Variant bits
       
       return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($data), 4));
   }
   
   public function testSubscriptionKey() {
       // FIXED: Remove explicit Content-Length for GET requests
       $headers = [
           'Ocp-Apim-Subscription-Key: ' . $this->subscription_key
       ];
       
       // Test endpoint to verify subscription key
       $url = $this->base_url . '/v1_0/apiuser';
       $result = $this->makeApiCall($url, 'GET', $headers);
       
       return [
           'valid' => !in_array($result['status'], [401, 403]),
           'status' => $result['status'],
           'message' => $result['status'] === 401 ? 'Invalid subscription key' : 
                       ($result['status'] === 403 ? 'Subscription key not authorized' : 'Subscription key is valid'),
           'response' => $result['raw']
       ];
   }
   
   // FIXED: Create API User with headers
   public function createApiUser($api_user = null, $callback_host = 'webhook.site') {
       if (!$api_user) {
           $api_user = $this->generateApiUser();
       }
       
       $data = ['providerCallbackHost' => $callback_host];
       $json_data = json_encode($data);
       
       // FIXED: Headers exactly matching Python script
       $headers = [
           'Content-Type: application/json',
           'X-Reference-Id: ' . $api_user,
           'Ocp-Apim-Subscription-Key: ' . $this->subscription_key
       ];
       
       $url = $this->base_url . '/v1_0/apiuser';
       
       error_log("Creating API User: " . $api_user . " at " . $url);
       error_log("Request payload: " . $json_data);
       
       $result = $this->makeApiCall($url, 'POST', $headers, $json_data);
       
       error_log("API User creation response: Status=" . $result['status'] . ", Body=" . $result['raw']);
       
       if ($result['status'] === 201) {
           return [
               'success' => true,
               'api_user' => $api_user,
               'message' => 'API User created successfully',
               'status' => $result['status']
           ];
       } elseif ($result['status'] === 409) {
           // User already exists, which is fine
           return [
               'success' => true,
               'api_user' => $api_user,
               'message' => 'API User already exists',
               'status' => $result['status']
           ];
       } else {
           return [
               'success' => false,
               'message' => 'Failed to create API User',
               'error' => $result['data'] ?? $result['raw'] ?? 'Unknown error',
               'status' => $result['status'],
               'debug_info' => [
                   'url' => $url,
                   'api_user' => $api_user,
                   'headers' => $headers,
                   'payload' => $json_data,
                   'response' => $result['raw']
               ]
           ];
       }
   }
   
   // FIXED: Generate API Key with headers matching Python script
   public function generateApiKey($subscription_key, $api_user) {
       // FIXED: Headers exactly matching Python script (no Content-Type for POST with no body)
       $headers = [
           'Ocp-Apim-Subscription-Key: ' . $this->subscription_key,
           'Content-Length: 0',
       ];
       
       $url = $this->base_url . '/v1_0/apiuser/' . $api_user . '/apikey';
       
       error_log("Generating API Key for user: " . $api_user . " at " . $url);
       error_log("Headers: " . json_encode($headers));
       
       // FIXED: POST with no body (like Python script)
       $result = $this->makeApiCall($url, 'POST', $headers, null);
       
       error_log("API Key generation response: Status=" . $result['status'] . ", Body=" . $result['raw']);
       
       if ($result['status'] === 201) {
           // FIXED: Handle different API key response formats
           $api_key = null;
           
           if (is_array($result['data']) && isset($result['data']['apiKey'])) {
               $api_key = $result['data']['apiKey'];
           } else {
               // MTN sometimes returns the API key as plain string
               $api_key = trim($result['raw'], '"\'');
           }
           
           // Validate the API key format (should be alphanumeric, 32 chars)
           if ($api_key && strlen($api_key) >= 16 && preg_match('/^[a-f0-9]+$/i', $api_key)) {
               return [
                   'success' => true,
                   'api_key' => $api_key,
                   'message' => 'API Key generated successfully',
                   'status' => $result['status']
               ];
           } else {
               return [
                   'success' => false,
                   'message' => 'Invalid API Key format received',
                   'error' => 'API Key validation failed',
                   'raw_response' => $result['raw'],
                   'status' => $result['status']
               ];
           }
       } else {
           return [
               'success' => false,
               'message' => 'Failed to generate API Key',
               'error' => $result['data'] ?? $result['raw'] ?? 'Unknown error',
               'status' => $result['status'],
               'debug_info' => [
                   'url' => $url,
                   'api_user' => $api_user,
                   'headers' => $headers,
                   'response' => $result['raw']
               ]
           ];
       }
   }
   
   // FIXED: Get Access Token matching Python script
   public function getAccessToken($api_user, $api_key) {
       $credentials = $api_user . ':' . $api_key;
       $encoded = base64_encode($credentials);
       
       // FIXED: Headers exactly matching Python script
       $headers = [
           'Authorization: Basic ' . $encoded,
           'Ocp-Apim-Subscription-Key: ' . $this->subscription_key,
           'Content-Length: 0',
       ];
       
       $url = $this->base_url . '/collection/token/';
       
       error_log("Requesting Access Token for user: " . $api_user);
       
       $result = $this->makeApiCall($url, 'POST', $headers, null);
       
       error_log("Access Token response: Status=" . $result['status'] . ", Body=" . $result['raw']);
       
       if ($result['status'] === 200 && $result['data']) {
           return [
               'success' => true,
               'access_token' => $result['data']['access_token'],
               'token_type' => $result['data']['token_type'] ?? 'Bearer',
               'expires_in' => $result['data']['expires_in'] ?? 3600,
               'message' => 'Access Token obtained successfully'
           ];
       } else {
           return [
               'success' => false,
               'message' => 'Failed to get access token',
               'error' => $result['data'] ?? $result['raw'] ?? 'Unknown error',
               'status' => $result['status']
           ];
       }
   }
   
   // FIXED: Request to Pay matching Python script
   public function requestToPay($access_token, $amount = '100', $currency = 'EUR', $phone = '46733123450') {
       $reference_id = $this->generateApiUser(); // Generate new UUID for reference
       
       $payment_data = [
           'amount' => (string)$amount,
           'currency' => $currency,
           'externalId' => 'order_' . time(),
           'payer' => [
               'partyIdType' => 'MSISDN',
               'partyId' => $phone
           ],
           'payerMessage' => 'Payment for ConnectPay Sandbox Test',
           'payeeNote' => 'Thank you for testing our API'
       ];
       
       $json_data = json_encode($payment_data);
       
       // FIXED: Headers exactly matching Python script
       $headers = [
           'Authorization: Bearer ' . $access_token,
           'X-Reference-Id: ' . $reference_id,
           'X-Target-Environment: ' . $this->environment,
           'Ocp-Apim-Subscription-Key: ' . $this->subscription_key,
           'Content-Type: application/json'
       ];
       
       $url = $this->base_url . '/collection/v1_0/requesttopay';
       
       error_log("Initiating Request to Pay. Reference ID: " . $reference_id);
       
       $result = $this->makeApiCall($url, 'POST', $headers, $json_data);
       
       if ($result['status'] === 202) {
           return [
               'success' => true,
               'reference_id' => $reference_id,
               'status' => 'PENDING',
               'message' => 'Request to Pay initiated successfully'
           ];
       } else {
           return [
               'success' => false,
               'message' => 'Request to Pay failed',
               'error' => $result['data'] ?? $result['raw'] ?? 'Unknown error',
               'status' => $result['status']
           ];
       }
   }
   
   // FIXED: Check Transaction Status matching Python script
   public function getTransactionStatus($access_token, $reference_id) {
       // FIXED: Headers exactly matching Python script
       $headers = [
           'Authorization: Bearer ' . $access_token,
           'X-Target-Environment: ' . $this->environment,
           'Ocp-Apim-Subscription-Key: ' . $this->subscription_key
       ];
       
       $url = $this->base_url . '/collection/v1_0/requesttopay/' . $reference_id;
       
       error_log("Checking transaction status for Ref ID: " . $reference_id);
       
       $result = $this->makeApiCall($url, 'GET', $headers, null);
       
       if ($result['status'] === 200 && $result['data']) {
           $status = $result['data']['status'];
           error_log("Transaction Status: " . $status);
           
           return [
               'success' => true,
               'status' => $status,
               'data' => $result['data'],
               'message' => 'Transaction status retrieved successfully'
           ];
       } else {
           return [
               'success' => false,
               'message' => 'Failed to get transaction status',
               'error' => $result['data'] ?? $result['raw'] ?? 'Unknown error',
               'status' => $result['status']
           ];
       }
   }
   
   // FIXED: Complete setup process matching Python script flow
   public function setupCredentials($callback_host = 'webhook.site') {
       error_log("🚀 Running MoMo Sandbox Test 🚀");
       
       // Step 0: Test subscription key first
       error_log("MTN Setup: Testing subscription key");
       $keyTest = $this->testSubscriptionKey();
       
       if (!$keyTest['valid']) {
           return [
               'success' => false,
               'message' => 'Invalid subscription key: ' . $keyTest['message'],
               'error' => 'Subscription key validation failed',
               'step' => 'subscription_validation',
               'debug_info' => $keyTest
           ];
       }
       
       // Step 1: Generate and create API User
       $api_user = $this->generateApiUser();
       
       error_log("🛠️ Creating API user with Reference ID: " . $api_user);
       $createResult = $this->createApiUser($api_user, $callback_host);
       
       if (!$createResult['success']) {
           error_log("❌ MTN Setup Failed at Step 1: " . json_encode($createResult));
           return [
               'success' => false,
               'message' => 'Failed to create API User: ' . $createResult['message'],
               'error' => $createResult['error'],
               'step' => 'api_user_creation',
               'debug_info' => $createResult['debug_info'] ?? null
           ];
       }
       
       error_log("✅ API User created successfully: " . $api_user);
       
       // Wait for MTN to process API User creation (like Python script)
       sleep(2);
       
       // Step 2: Generate API Key
       error_log("🔑 Generating API Key for user: " . $api_user);
       $keyResult = $this->generateApiKey($this->subscription_key, $api_user);
       
       if (!$keyResult['success']) {
           error_log("❌ MTN Setup Failed at Step 2: " . json_encode($keyResult));
           
           // Retry API key generation once if it fails
           error_log("MTN Setup: Retrying API Key generation after additional delay...");
           sleep(3);
           $keyResult = $this->generateApiKey($this->subscription_key, $api_user);
           
           if (!$keyResult['success']) {
               return [
                   'success' => false,
                   'message' => 'API User created but API Key generation failed after retry: ' . $keyResult['message'],
                   'error' => $keyResult['error'],
                   'step' => 'api_key_generation',
                   'debug_info' => $keyResult['debug_info'] ?? null,
                   'api_user_created' => $api_user
               ];
           }
       }
       
       error_log("✅ API Key generated successfully: " . $keyResult['api_key']);
       
       // Step 3: Get Access Token
       error_log("🔐 Requesting Access Token for user: " . $api_user);
       $tokenResult = $this->getAccessToken($api_user, $keyResult['api_key']);
       
       if (!$tokenResult['success']) {
           error_log("❌ Failed to get access token: " . json_encode($tokenResult));
           return [
               'success' => false,
               'message' => 'Failed to get access token: ' . $tokenResult['message'],
               'error' => $tokenResult['error'],
               'step' => 'access_token',
               'api_user_created' => $api_user,
               'api_key_generated' => $keyResult['api_key']
           ];
       }
       
       error_log("✅ Access Token obtained successfully.");
       
       // Step 4: Save credentials
       if ($this->conn) {
           $this->saveCredentials($api_user, $keyResult['api_key']);
       }
       
       return [
           'success' => true,
           'credentials' => [
               'subscription_key' => $this->subscription_key,
               'api_user' => $api_user,
               'api_key' => $keyResult['api_key'],
               'access_token' => $tokenResult['access_token'],
               'environment' => $this->environment,
               'base_url' => $this->base_url
           ],
           'message' => 'MTN MoMo credentials setup completed successfully'
       ];
   }
   
   // FIXED: Test complete flow like Python script
   public function testCompleteFlow($amount = '100', $currency = 'EUR', $phone = '46733123450') {
       // Get or setup credentials
       $setupResult = $this->setupCredentials();
       
       if (!$setupResult['success']) {
           return $setupResult;
       }
       
       $credentials = $setupResult['credentials'];
       
       // Test payment
       error_log("💸 Initiating Request to Pay. Reference ID will be generated...");
       $paymentResult = $this->requestToPay(
           $credentials['access_token'],
           $amount,
           $currency,
           $phone
       );
       
       if (!$paymentResult['success']) {
           error_log("❌ Request to Pay failed: " . json_encode($paymentResult));
           return $paymentResult;
       }
       
       error_log("✅ Request to Pay initiated successfully. Ref ID: " . $paymentResult['reference_id']);
       
       // Wait and check status (like Python script)
       sleep(5);
       
       error_log("🕵️ Checking transaction status for Ref ID: " . $paymentResult['reference_id']);
       $statusResult = $this->getTransactionStatus(
           $credentials['access_token'],
           $paymentResult['reference_id']
       );
       
       if ($statusResult['success']) {
           error_log("🕵️ Transaction Status: " . $statusResult['status']);
       }
       
       return [
           'success' => true,
           'setup' => $setupResult,
           'payment' => $paymentResult,
           'status' => $statusResult,
           'message' => 'Complete MTN MoMo test flow successful!'
       ];
   }
   
   public function getApiUserDetails($api_user) {
       $headers = [
           'Ocp-Apim-Subscription-Key: ' . $this->subscription_key,
           'X-Target-Environment: ' . $this->environment
       ];
       
       $url = $this->base_url . '/v1_0/apiuser/' . $api_user;
       $result = $this->makeApiCall($url, 'GET', $headers);
       
       if ($result['status'] === 200) {
           return [
               'success' => true,
               'data' => $result['data'],
               'message' => 'API User details retrieved'
           ];
       } else {
           return [
               'success' => false,
               'message' => 'Failed to get API User details',
               'error' => $result['data'] ?? $result['raw'],
               'status' => $result['status']
           ];
       }
   }
   
   // FIXED: Save credentials with correct column names
   private function saveCredentials($api_user, $api_key) {
       global $user_id;
       
       try {
           // First, check if credentials already exist for this user
           $stmt = $this->conn->prepare("
               SELECT credential_id FROM mtn_momo_credentials 
               WHERE user_id = ? AND environment = ?
           ");
           $stmt->bind_param("is", $user_id, $this->environment);
           $stmt->execute();
           $result = $stmt->get_result();
           $existing = $result->fetch_assoc();
           $stmt->close();
           
           if ($existing) {
               // Update existing credentials
               $stmt = $this->conn->prepare("
                   UPDATE mtn_momo_credentials 
                   SET api_user_id = ?, 
                       api_key = ?, 
                       subscription_key_collection = ?,
                       last_validated_at = NOW(),
                       updated_at = NOW()
                   WHERE user_id = ? AND environment = ?
               ");
               $stmt->bind_param("sssis", $api_user, $api_key, $this->subscription_key, $user_id, $this->environment);
               $stmt->execute();
               $stmt->close();
               error_log("MTN credentials updated in database for user: " . $user_id);
           } else {
               // Insert new credentials
               $stmt = $this->conn->prepare("
                   INSERT INTO mtn_momo_credentials (
                       user_id, 
                       credential_name,
                       api_user_id, 
                       api_key, 
                       subscription_key_collection,
                       environment,
                       base_url,
                       status,
                       created_at, 
                       updated_at
                   ) VALUES (?, ?, ?, ?, ?, ?, ?, 'ACTIVE', NOW(), NOW())
               ");
               $credential_name = "Auto-generated MTN Credentials";
               $stmt->bind_param("issssss", 
                   $user_id, 
                   $credential_name,
                   $api_user, 
                   $api_key, 
                   $this->subscription_key, 
                   $this->environment,
                   $this->base_url
               );
               $stmt->execute();
               $stmt->close();
               error_log("MTN credentials saved to database for user: " . $user_id);
           }
       } catch (Exception $e) {
           error_log("Failed to save MTN credentials: " . $e->getMessage());
           throw $e; // Re-throw so caller can handle
       }
   }
   
   // FIXED: Get stored credentials with correct column names
   public function getStoredCredentials($user_id) {
       if (!$this->conn) return null;
       
       try {
           $stmt = $this->conn->prepare("
               SELECT 
                   credential_id,
                   user_id,
                   credential_name,
                   api_user_id as api_user,
                   api_key,
                   subscription_key_collection as subscription_key,
                   environment,
                   base_url,
                   status,
                   created_at,
                   updated_at
               FROM mtn_momo_credentials 
               WHERE user_id = ? AND environment = ? AND status = 'ACTIVE'
               ORDER BY updated_at DESC LIMIT 1
           ");
           $stmt->bind_param("is", $user_id, $this->environment);
           $stmt->execute();
           $result = $stmt->get_result()->fetch_assoc();
           $stmt->close();
           return $result;
       } catch (Exception $e) {
           error_log("Failed to get stored credentials: " . $e->getMessage());
           return null;
       }
   }
   
   // FIXED: Enhanced makeApiCall method matching Python requests behavior
   private function makeApiCall($url, $method, $headers, $data = null) {
       $curl = curl_init();
       
       // FIXED: Default curl options matching Python requests
       $curlOptions = [
           CURLOPT_URL => $url,
           CURLOPT_RETURNTRANSFER => true,
           CURLOPT_TIMEOUT => 30,
           CURLOPT_CONNECTTIMEOUT => 10,
           CURLOPT_CUSTOMREQUEST => $method,
           CURLOPT_HTTPHEADER => $headers,
           CURLOPT_SSL_VERIFYPEER => false, // For sandbox only
           CURLOPT_SSL_VERIFYHOST => false, // For sandbox only
           CURLOPT_VERBOSE => false,
           CURLOPT_FOLLOWLOCATION => true,
           CURLOPT_MAXREDIRS => 3,
           CURLOPT_USERAGENT => 'ConnectPay-MoMo-Platform/1.0',
           CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1
       ];
       
       // FIXED: Handle data properly (like Python script)
       if ($data !== null && in_array($method, ['POST', 'PUT', 'PATCH'])) {
           if (is_array($data)) {
               $curlOptions[CURLOPT_POSTFIELDS] = json_encode($data);
           } else {
               $curlOptions[CURLOPT_POSTFIELDS] = $data;
           }
       }
       
       curl_setopt_array($curl, $curlOptions);
       
       $response = curl_exec($curl);
       $httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
       $error = curl_error($curl);
       $info = curl_getinfo($curl);
       
       curl_close($curl);
       
       if ($error) {
           error_log("cURL Error for $method $url: $error");
       }
       
       error_log("MTN API Call: $method $url -> HTTP $httpCode");
       if ($httpCode >= 400) {
           error_log("MTN API Error Response: " . $response);
       }
       
       return [
           'status' => $httpCode,
           'data' => $response ? json_decode($response, true) : null,
           'raw' => $response,
           'error' => $error,
           'info' => $info
       ];
   }
}

// Initialize credential manager with your real subscription key
$mtn_manager = new MTNMoMoCredentialManager(
   '8055a558eeae4c29ad65d869982defef', // Replace with your actual subscription key
   'sandbox',
   $conn
);

// Table already exists in database schema - no need to create
// Just verify we can access it
try {
    $conn->query("SELECT 1 FROM mtn_momo_credentials LIMIT 1");
    error_log("MTN credentials table accessible");
} catch (Exception $e) {
    error_log("MTN credentials table access error: " . $e->getMessage());
}

// Try to get existing credentials
$stored_credentials = $mtn_manager->getStoredCredentials($user_id);

if (!$stored_credentials) {
   // Set default credentials that need generation
   $sandbox_credentials = [
       'subscription_key' => '8055a558eeae4c29ad65d869982defef',
       'api_user' => 'NEEDS_GENERATION',
       'api_key' => 'NEEDS_GENERATION', 
       'base_url' => 'https://sandbox.momodeveloper.mtn.com',
       'environment' => 'sandbox'
   ];
} else {
   // Use stored credentials
   $sandbox_credentials = [
       'subscription_key' => $stored_credentials['subscription_key'],
       'api_user' => $stored_credentials['api_user'],
       'api_key' => $stored_credentials['api_key'],
       'base_url' => 'https://sandbox.momodeveloper.mtn.com',
       'environment' => $stored_credentials['environment']
   ];
}

// Add test phone numbers and configuration
$sandbox_credentials['test_phones'] = [
   'success' => '46733123450',
   'insufficient' => '46733123451', 
   'invalid' => '46733123452',
   'timeout' => '46733123453'
];
$sandbox_credentials['callback_host'] = 'webhook.site';

// Helper functions
function generateUUID() {
   $data = random_bytes(16);
   $data[6] = chr(ord($data[6]) & 0x0f | 0x40);
   $data[8] = chr(ord($data[8]) & 0x3f | 0x80);
   
   return sprintf('%08s-%04s-%04s-%04s-%12s',
       bin2hex(substr($data, 0, 4)),
       bin2hex(substr($data, 4, 2)),
       bin2hex(substr($data, 6, 2)),
       bin2hex(substr($data, 8, 2)),
       bin2hex(substr($data, 10, 6))
   );
}

// FIXED: Enhanced makeApiCall helper function
function makeApiCall($url, $method, $headers, $data = null) {
   $curl = curl_init();
   
   $curlOptions = [
       CURLOPT_URL => $url,
       CURLOPT_RETURNTRANSFER => true,
       CURLOPT_TIMEOUT => 60,
       CURLOPT_CONNECTTIMEOUT => 30,
       CURLOPT_CUSTOMREQUEST => $method,
       CURLOPT_HTTPHEADER => $headers,
       CURLOPT_SSL_VERIFYPEER => false,
       CURLOPT_SSL_VERIFYHOST => false,
       CURLOPT_VERBOSE => false,
       CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
       CURLOPT_USERAGENT => 'ConnectPay-MoMo-Platform/1.0'
   ];
   
   if ($data && in_array($method, ['POST', 'PUT', 'PATCH'])) {
       $curlOptions[CURLOPT_POSTFIELDS] = is_array($data) ? json_encode($data) : $data;
   }
   
   curl_setopt_array($curl, $curlOptions);
   $response = curl_exec($curl);
   $httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
   $error = curl_error($curl);
   curl_close($curl);
   
   return [
       'status' => $httpCode,
       'data' => $response ? json_decode($response, true) : null,
       'raw' => $response,
       'error' => $error
   ];
}

// Handle AJAX requests for credential setup and API calls
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
   header('Content-Type: application/json');
  
  $action = $_POST['action'];
  $response = ['success' => false, 'message' => 'Unknown action'];
  
  switch ($action) {
      case 'debug_subscription':
          $result = $mtn_manager->testSubscriptionKey();
          $response = [
              'success' => true,
              'debug_info' => $result,
             'subscription_key' => $sandbox_credentials['subscription_key'],
             'base_url' => $sandbox_credentials['base_url']
         ];
         break;
         
     case 'setup_credentials':
         $callback_host = $_POST['callback_host'] ?? 'webhook.site';
         
         error_log("Starting MTN credential setup for user: " . $user_id);
         $result = $mtn_manager->setupCredentials($callback_host);
         
         if ($result['success']) {
             $response = [
                 'success' => true,
                 'credentials' => $result['credentials'],
                 'message' => 'MTN MoMo credentials generated successfully'
             ];
             
             // Update global credentials
             $sandbox_credentials = $result['credentials'];
             $sandbox_credentials['test_phones'] = [
                 'success' => '46733123450',
                 'insufficient' => '46733123451', 
                 'invalid' => '46733123452',
                 'timeout' => '46733123453'
             ];
             
             // Log the credential setup
             $stmt = $conn->prepare("
                 INSERT INTO analytics_events (user_id, event_type, event_category, event_action, properties, created_at) 
                 VALUES (?, 'api_call', 'momo_setup', 'credentials_generated', ?, NOW())
             ");
             $properties = json_encode(['success' => true, 'environment' => 'sandbox']);
             $stmt->bind_param("is", $user_id, $properties);
             $stmt->execute();
             $stmt->close();
         } else {
             // Enhanced error response with debug info
             $response = [
                 'success' => false,
                 'message' => $result['message'],
                 'error' => $result['error'],
                 'step_failed' => $result['step'] ?? 'unknown',
                 'debug_info' => $result['debug_info'] ?? null
             ];
             
             error_log("MTN credential setup failed: " . json_encode($response));
         }
         break;
         
     case 'test_complete_flow':
         $amount = $_POST['amount'] ?? '100';
         $currency = $_POST['currency'] ?? 'EUR';
         $phone = $_POST['phone'] ?? '46733123450';
         
         error_log("Testing complete MTN flow");
         $result = $mtn_manager->testCompleteFlow($amount, $currency, $phone);
         
         $response = $result;
         break;
         
     case 'get_token':
         if ($sandbox_credentials['api_user'] === 'NEEDS_GENERATION') {
             $response = [
                 'success' => false,
                 'message' => 'Please generate API credentials first',
                 'needs_setup' => true
             ];
             break;
         }
         
         $tokenResult = $mtn_manager->getAccessToken(
             $sandbox_credentials['api_user'],
             $sandbox_credentials['api_key']
         );
         
         if ($tokenResult['success']) {
             $response = [
                 'success' => true,
                 'data' => [
                     'access_token' => $tokenResult['access_token'],
                     'token_type' => $tokenResult['token_type'],
                     'expires_in' => $tokenResult['expires_in']
                 ],
                 'status' => 200
             ];
             
             // Log the API call
             $stmt = $conn->prepare("
                 INSERT INTO analytics_events (user_id, event_type, event_category, event_action, properties, created_at) 
                 VALUES (?, 'api_call', 'momo_sandbox', 'get_token', ?, NOW())
             ");
             $properties = json_encode(['status' => 200, 'endpoint' => '/token']);
             $stmt->bind_param("is", $user_id, $properties);
             $stmt->execute();
             $stmt->close();
         } else {
             $response = [
                 'success' => false,
                 'message' => 'Failed to get access token',
                 'error' => $tokenResult['error'] ?: 'API call failed',
                 'status' => $tokenResult['status'] ?? 500
             ];
         }
         break;
         
     case 'request_to_pay':
         $access_token = $_POST['access_token'] ?? '';
         $amount = $_POST['amount'] ?? '100';
         $phone = $_POST['phone'] ?? $sandbox_credentials['test_phones']['success'];
         $currency = $_POST['currency'] ?? 'EUR';
         
         $paymentResult = $mtn_manager->requestToPay(
             $access_token,
             $amount,
             $currency,
             $phone
         );
         
         if ($paymentResult['success']) {
             $response = [
                 'success' => true,
                 'data' => [
                     'referenceId' => $paymentResult['reference_id'],
                     'status' => $paymentResult['status'],
                     'message' => $paymentResult['message']
                 ],
                 'status' => 202
             ];
             
             // Log the API call
             $stmt = $conn->prepare("
                 INSERT INTO analytics_events (user_id, event_type, event_category, event_action, properties, created_at) 
                 VALUES (?, 'api_call', 'momo_sandbox', 'request_to_pay', ?, NOW())
             ");
             $properties = json_encode([
                 'status' => 202, 
                 'reference_id' => $paymentResult['reference_id'],
                 'amount' => $amount,
                 'currency' => $currency
             ]);
             $stmt->bind_param("is", $user_id, $properties);
             $stmt->execute();
             $stmt->close();
         } else {
             $response = [
                 'success' => false,
                 'message' => 'Failed to initiate payment',
                 'error' => $paymentResult['error'],
                 'status' => $paymentResult['status'] ?? 500
             ];
         }
         break;
         
     case 'get_transaction_status':
         $access_token = $_POST['access_token'] ?? '';
         $reference_id = $_POST['reference_id'] ?? '';
         
         $statusResult = $mtn_manager->getTransactionStatus($access_token, $reference_id);
         
         if ($statusResult['success']) {
             $response = [
                 'success' => true,
                 'data' => $statusResult['data'],
                 'status' => $statusResult['status'],
                 'message' => $statusResult['message']
             ];
         } else {
             $response = [
                 'success' => false,
                 'message' => 'Failed to get transaction status',
                 'error' => $statusResult['error'],
                 'status' => $statusResult['status'] ?? 500
             ];
         }
         break;
         
     case 'get_balance':
         $access_token = $_POST['access_token'] ?? '';
         
         // This would use the same pattern but for balance endpoint
         $headers = [
             'Authorization: Bearer ' . $access_token,
             'X-Target-Environment: ' . $sandbox_credentials['environment'],
             'Ocp-Apim-Subscription-Key: ' . $sandbox_credentials['subscription_key']
         ];
         
         $result = makeApiCall(
             $sandbox_credentials['base_url'] . '/collection/v1_0/account/balance',
             'GET',
             $headers
         );
         
         if ($result['status'] === 200 && $result['data']) {
             $response = [
                 'success' => true,
                 'data' => $result['data'],
                 'status' => $result['status']
             ];
         } else {
             $response = [
                 'success' => false,
                 'message' => 'Failed to get account balance',
                 'error' => $result['error'],
                 'status' => $result['status']
             ];
         }
         break;
 }
 
 echo json_encode($response);
 exit();
}
?>

<!DOCTYPE html>
<html lang="en">

<head>
  <?php $title = "MoMo API Sandbox - ConnectPay Platform";
  include 'partials/title-meta.php'; ?>
  
  <?php include 'partials/head-css.php'; ?>
  
  <!-- Feather Icons -->
  <script src="https://unpkg.com/feather-icons"></script>
  
  <!-- Custom CSS for MoMo Sandbox -->
  <style>
      :root {
          --sandbox-primary: #667eea;
          --sandbox-secondary: #764ba2;
          --sandbox-success: #28a745;
          --sandbox-warning: #ffc107;
          --sandbox-danger: #dc3545;
          --sandbox-info: #17a2b8;
      }

      .sandbox-card {
          border-radius: 15px;
          border: none;
          box-shadow: 0 4px 20px rgba(0,0,0,0.08);
          transition: all 0.3s ease;
          background: white;
          margin-bottom: 1.5rem;
          overflow: hidden;
      }

      .sandbox-card:hover {
          transform: translateY(-8px);
          box-shadow: 0 8px 30px rgba(0,0,0,0.12);
      }

      .welcome-section {
          background: white;
          border: 1px solid #e2e8f0;
          border-radius: 8px;
          padding: 2rem;
          margin-bottom: 2rem;
          box-shadow: 0 1px 3px 0 rgb(0 0 0 / 0.1), 0 1px 2px -1px rgb(0 0 0 / 0.1);
      }

      .welcome-section h2 {
          color: #0f172a;
          font-weight: 700;
          font-size: 1.875rem;
          margin-bottom: 0.5rem;
      }

      .credential-status-card {
          border-left: 4px solid #ffc107;
          background: rgba(255, 193, 7, 0.1);
      }

      .credential-status-card.ready {
          border-left-color: #28a745;
          background: rgba(40, 167, 69, 0.1);
     }

     .real-api-badge {
         background: linear-gradient(135deg, #28a745, #20c997);
         color: white;
         padding: 0.25rem 0.75rem;
         border-radius: 20px;
         font-size: 0.75rem;
         font-weight: 600;
         display: inline-flex;
         align-items: center;
         gap: 0.25rem;
     }

     .real-api-badge::before {
         content: "🚀";
     }

     .setup-step {
         padding: 0.5rem 0;
         border-bottom: 1px solid #e9ecef;
         transition: all 0.3s ease;
     }

     .setup-step:last-child {
         border-bottom: none;
     }

     .setup-step.text-success {
         color: #28a745 !important;
     }

     .setup-step.text-primary {
         color: #007bff !important;
     }

     .setup-step.text-danger {
         color: #dc3545 !important;
     }

     .metric-card {
         background: white;
         border: 1px solid #e9ecef;
         border-radius: 12px;
         padding: 1.5rem;
         transition: all 0.2s ease;
     }

     .metric-card:hover {
         box-shadow: 0 4px 12px rgba(0,0,0,0.1);
     }

     .code-block {
         background: #f8f9fa;
         border: 1px solid #e9ecef;
         border-radius: 8px;
         padding: 1rem;
         font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
         font-size: 0.875rem;
         overflow-x: auto;
         position: relative;
     }

     .api-response {
         background: #e7f3ff;
         border-left: 4px solid var(--sandbox-info);
         padding: 1rem;
         border-radius: 0 8px 8px 0;
         margin-top: 1rem;
     }

     .status-badge {
         display: inline-flex;
         align-items: center;
         padding: 0.25rem 0.75rem;
         border-radius: 20px;
         font-size: 0.75rem;
         font-weight: 500;
     }

     .status-success {
         background: rgba(40, 167, 69, 0.1);
         color: var(--sandbox-success);
     }

     .status-warning {
         background: rgba(255, 193, 7, 0.1);
         color: #856404;
     }

     .status-error {
         background: rgba(220, 53, 69, 0.1);
         color: var(--sandbox-danger);
     }

     .debug-info {
         background: #f8f9fa;
         border: 1px solid #dee2e6;
         border-radius: 4px;
         padding: 0.75rem;
         font-family: monospace;
         font-size: 0.8rem;
         max-height: 200px;
         overflow-y: auto;
     }

     .progress-step {
         display: flex;
         align-items: center;
         padding: 1rem;
         border-radius: 8px;
         margin-bottom: 0.5rem;
         transition: all 0.2s ease;
         cursor: pointer;
         border: 1px solid #e9ecef;
         background: white;
     }

     .progress-step.active {
         background: rgba(102, 126, 234, 0.1);
         border-color: var(--sandbox-primary);
     }

     .progress-step.completed {
         background: rgba(40, 167, 69, 0.1);
         border-color: var(--sandbox-success);
     }

     .step-number {
         width: 32px;
         height: 32px;
         border-radius: 50%;
         background: var(--sandbox-primary);
         color: white;
         display: flex;
         align-items: center;
         justify-content: center;
         font-weight: 600;
         margin-right: 1rem;
     }

     .step-number.completed {
         background: var(--sandbox-success);
     }

     .step-number.pending {
         background: #dee2e6;
         color: #6c757d;
     }

     /* Enhanced Tab Styling */
     .nav-pills .nav-link {
         border-radius: 50px;
         padding: 12px 24px;
         margin: 0 4px;
         font-weight: 500;
         transition: all 0.3s ease;
         border: 2px solid transparent;
     }

     .nav-pills .nav-link:hover {
         background-color: rgba(102, 126, 234, 0.1);
         color: var(--sandbox-primary);
         transform: translateY(-2px);
     }

     .nav-pills .nav-link.active {
         background: linear-gradient(135deg, var(--sandbox-primary), var(--sandbox-secondary));
         color: white;
         border-color: var(--sandbox-primary);
         box-shadow: 0 4px 15px rgba(102, 126, 234, 0.3);
     }

     .nav-pills .nav-link i {
         margin-right: 8px;
     }

     .tab-content {
         background: white;
         border-radius: 15px;
         padding: 2rem;
         box-shadow: 0 4px 20px rgba(0,0,0,0.08);
         margin-top: 1rem;
         min-height: 600px;
     }

     /* Quick Start Step Cards */
     .quickstart-step-card {
         background: white;
         border: 2px solid #e9ecef;
         border-radius: 12px;
         padding: 1.5rem;
         margin-bottom: 1rem;
         transition: all 0.3s ease;
         cursor: pointer;
     }

     .quickstart-step-card:hover {
         border-color: var(--sandbox-primary);
         box-shadow: 0 4px 15px rgba(102, 126, 234, 0.1);
     }

     .quickstart-step-card.active {
         border-color: var(--sandbox-primary);
         background: rgba(102, 126, 234, 0.05);
     }

     .quickstart-step-card.completed {
         border-color: var(--sandbox-success);
         background: rgba(40, 167, 69, 0.05);
     }

     .step-header {
         display: flex;
         align-items: center;
         margin-bottom: 1rem;
     }

     .step-icon {
         width: 40px;
         height: 40px;
         border-radius: 50%;
         background: var(--sandbox-primary);
         color: white;
         display: flex;
         align-items: center;
         justify-content: center;
         font-weight: 600;
         margin-right: 1rem;
     }

     .step-icon.completed {
         background: var(--sandbox-success);
     }

     .step-icon.pending {
         background: #dee2e6;
         color: #6c757d;
     }

     /* Live Testing Form */
     .test-form {
         background: #f8f9fa;
         border-radius: 12px;
         padding: 2rem;
         border: 1px solid #e9ecef;
     }

     .test-result {
         background: white;
         border-radius: 12px;
         padding: 1.5rem;
         border: 1px solid #e9ecef;
         margin-top: 1rem;
     }

     .result-header {
         display: flex;
         justify-content: between;
         align-items: center;
         margin-bottom: 1rem;
         padding-bottom: 0.5rem;
         border-bottom: 1px solid #e9ecef;
     }

     .result-content {
         font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
         background: #f8f9fa;
         padding: 1rem;
         border-radius: 8px;
         overflow-x: auto;
     }

     /* Debug Info Enhancements */
     .debug-section {
         background: #f8f9fa;
         border-radius: 12px;
         padding: 1.5rem;
         margin-bottom: 1rem;
     }

     .debug-log {
         background: #212529;
         color: #f8f9fa;
         border-radius: 8px;
         padding: 1rem;
         font-family: monospace;
         max-height: 400px;
         overflow-y: auto;
         font-size: 0.875rem;
     }

     .debug-log .log-entry {
         margin-bottom: 0.5rem;
         padding: 0.25rem 0;
     }

     .debug-log .log-success {
         color: #28a745;
     }

     .debug-log .log-error {
         color: #dc3545;
     }

     .debug-log .log-warning {
         color: #ffc107;
     }

     .debug-log .log-info {
         color: #17a2b8;
     }

     /* FIXED: Additional styling for better UX */
     .alert-enhanced {
         border-left: 4px solid;
         background: rgba(0,0,0,0.02);
         border-radius: 8px;
     }

     .alert-enhanced.alert-info {
         border-left-color: var(--sandbox-info);
     }

     .alert-enhanced.alert-success {
         border-left-color: var(--sandbox-success);
     }

     .alert-enhanced.alert-warning {
         border-left-color: var(--sandbox-warning);
     }

     .alert-enhanced.alert-danger {
         border-left-color: var(--sandbox-danger);
     }

     .connection-status {
         position: relative;
         overflow: hidden;
     }

     .connection-status::before {
         content: '';
         position: absolute;
         top: 0;
         left: -100%;
         width: 100%;
         height: 100%;
         background: linear-gradient(90deg, transparent, rgba(255,255,255,0.4), transparent);
         animation: shimmer 2s infinite;
     }

     @keyframes shimmer {
         0% { left: -100%; }
         100% { left: 100%; }
     }

     .loading-pulse {
         animation: pulse 1.5s infinite;
     }

     @keyframes pulse {
         0% { opacity: 1; }
         50% { opacity: 0.5; }
         100% { opacity: 1; }
     }

     /* Phone Number Badges */
     .phone-badge {
         display: inline-flex;
         align-items: center;
         padding: 0.5rem 1rem;
         border-radius: 25px;
         font-size: 0.875rem;
         font-weight: 500;
         margin: 0.25rem;
         cursor: pointer;
         transition: all 0.2s ease;
     }

     .phone-badge:hover {
         transform: translateY(-2px);
         box-shadow: 0 4px 12px rgba(0,0,0,0.15);
     }

     .phone-badge.success {
         background: rgba(40, 167, 69, 0.1);
         color: var(--sandbox-success);
         border: 1px solid var(--sandbox-success);
     }

     .phone-badge.warning {
         background: rgba(255, 193, 7, 0.1);
         color: #856404;
         border: 1px solid #ffc107;
     }

     .phone-badge.danger {
         background: rgba(220, 53, 69, 0.1);
         color: var(--sandbox-danger);
         border: 1px solid var(--sandbox-danger);
     }

     .phone-badge.secondary {
         background: rgba(108, 117, 125, 0.1);
         color: #6c757d;
         border: 1px solid #6c757d;
     }

     /* Tutorial Content */
     .tutorial-content {
         background: white;
         border-radius: 12px;
         padding: 2rem;
         border: 1px solid #e9ecef;
     }

     .tutorial-navigation {
         display: flex;
         justify-content: space-between;
         align-items: center;
         margin-top: 2rem;
         padding-top: 1rem;
         border-top: 1px solid #e9ecef;
     }

     /* API Endpoint Display */
     .api-endpoint {
         background: #212529;
         color: #f8f9fa;
         padding: 1rem;
         border-radius: 8px;
         font-family: monospace;
         margin: 1rem 0;
         position: relative;
     }

     .api-endpoint .method {
         color: #28a745;
         font-weight: bold;
     }

     .api-endpoint .url {
         color: #17a2b8;
     }

     .api-endpoint .header {
         color: #ffc107;
     }

     .copy-endpoint {
         position: absolute;
         top: 0.5rem;
         right: 0.5rem;
         background: rgba(255,255,255,0.1);
         border: none;
         color: white;
         padding: 0.25rem 0.5rem;
         border-radius: 4px;
         font-size: 0.75rem;
         cursor: pointer;
     }

     .copy-endpoint:hover {
         background: rgba(255,255,255,0.2);
     }

     /* Interactive Elements */
     .interactive-demo {
         background: linear-gradient(135deg, #f8f9fa, #e9ecef);
         border-radius: 12px;
         padding: 2rem;
         margin: 1rem 0;
     }

     .demo-controls {
         display: flex;
         gap: 1rem;
         margin-bottom: 1rem;
         flex-wrap: wrap;
     }

     .demo-output {
         background: white;
         border-radius: 8px;
         padding: 1rem;
         border: 1px solid #dee2e6;
         min-height: 200px;
     }

     /* Responsive Design */
     @media (max-width: 768px) {
         .nav-pills {
             flex-direction: column;
         }
         
         .nav-pills .nav-link {
             margin: 2px 0;
             text-align: center;
         }
         
         .tab-content {
             padding: 1rem;
         }
         
         .demo-controls {
             flex-direction: column;
         }
         
         .quickstart-step-card {
             padding: 1rem;
         }
     }
 </style>
</head>

<?php include 'partials/body.php'; ?>

<!-- Begin page -->
<div id="wrapper">

 <?php $pagetitle = "MoMo API Sandbox"; include 'partials/menu.php'; ?>

 <div class="content-page">
     <div class="content">
         <div class="container-fluid">

             <!-- Page Title -->
             <div class="row">
                 <div class="col-12">
                     <div class="page-title-box">
                         <div class="page-title-right">
                             <ol class="breadcrumb m-0">
                                 <li class="breadcrumb-item"><a href="<?php echo ($user_role === 'Customer') ? 'dashboard.php' : 'index.php'; ?>">Dashboard</a></li>
                                 <li class="breadcrumb-item active">MoMo Sandbox</li>
                             </ol>
                         </div>
                         <h4 class="page-title">
                             MoMo API Sandbox
                         </h4>
                     </div>
                 </div>
             </div>

             <?php if (!$has_api_access): ?>
             <!-- Access Required Alert -->
             <div class="row">
                 <div class="col-12">
                     <div class="alert alert-warning alert-enhanced" role="alert">
                         <h5 class="alert-heading">
                             <i class="fas fa-exclamation-triangle me-2"></i>
                             API Access Required
                         </h5>
                         <p class="mb-3">You need an active API subscription or plugin license to access the Real MoMo Sandbox.</p>
                         <div class="d-flex gap-2">
                             <a href="browse-plugins.php" class="btn btn-warning">Browse API Products</a>
                             <a href="my-licenses.php" class="btn btn-outline-warning">View My Licenses</a>
                         </div>
                     </div>
                 </div>
             </div>
             <?php else: ?>

             <!-- FIXED: Enhanced Real API Notice -->
             <div class="row">
                 <div class="col-12">
                     <div class="alert alert-info alert-enhanced" role="alert">
                         <h6 class="alert-heading">
                             <i class="fas fa-info-circle me-2"></i>
                             MTN MoMo Sandbox Environment - Fixed Content-Length Issue
                         </h6>
                         <p class="mb-2">
                             This sandbox uses <strong>real MTN MoMo sandbox endpoints</strong> with proper HTTP headers. 
                             All API calls are made to MTN's official sandbox environment with correct Content-Length headers.
                         </p>
                         <p class="mb-0">
                             <span class="badge bg-success me-2">✓ Fixed</span>
                             Content-Length header issue resolved for API key generation
                         </p>
                     </div>
                 </div>
             </div>

             <!-- Sandbox Hero Section -->
             <div class="welcome-section">
                 <div class="row align-items-center">
                     <div class="col-md-8">
                         <h2 class="mb-2">
                             <i class="fas fa-cube me-2"></i>
                             MTN MoMo API Sandbox
                         </h2>
                         <p class="mb-3 opacity-90">
                             Test with real MTN MoMo sandbox endpoints. Enhanced with proper HTTP header handling 
                             for reliable API key generation and payment processing.
                         </p>
                         <div class="d-flex gap-2">
                             <button class="btn btn-outline-primary btn-sm" onclick="debugMTNSetup()">
                                 <i class="fas fa-bug me-1"></i>
                                 Debug Setup
                             </button>
                             <button class="btn btn-outline-info btn-sm" onclick="testSubscriptionKey()">
                                 <i class="fas fa-key me-1"></i>
                                 Test Subscription Key
                             </button>
                             <button class="btn btn-outline-success btn-sm" onclick="testMTNConnection()">
                                 <i class="fas fa-plug me-1"></i>
                                 Test Connection
                             </button>
                         </div>
                     </div>
                     <div class="col-md-4 text-center">
                         <div class="p-3 connection-status">
                             <i class="fas fa-mobile-alt fa-4x mb-3 opacity-75"></i>
                             <h6 class="opacity-75">MTN MoMo Sandbox</h6>
                             <small class="opacity-75">Real API • Enhanced Headers • Safe Testing</small>
                             <div class="mt-2">
                                 <span class="status-badge <?php echo ($sandbox_credentials['api_user'] !== 'NEEDS_GENERATION') ? 'status-success' : 'status-warning'; ?>">
                                     <i class="fas fa-circle me-1" style="font-size: 0.5rem;"></i>
                                     <?php echo ($sandbox_credentials['api_user'] !== 'NEEDS_GENERATION') ? 'Ready' : 'Setup Required'; ?>
                                 </span>
                             </div>
                         </div>
                     </div>
                 </div>
             </div>

             <!-- Quick Stats -->
             <div class="row mb-4">
                 <div class="col-md-3">
                     <div class="metric-card text-center">
                         <h3 class="text-primary mb-1" id="apiCallsCount">0</h3>
                         <p class="text-muted mb-0">API Calls Today</p>
                     </div>
                 </div>
                 <div class="col-md-3">
                     <div class="metric-card text-center">
                         <h3 class="text-success mb-1" id="successRate">--</h3>
                         <p class="text-muted mb-0">Success Rate</p>
                     </div>
                 </div>
                 <div class="col-md-3">
                     <div class="metric-card text-center">
                         <h3 class="text-info mb-1">1,000</h3>
                         <p class="text-muted mb-0">Requests Left</p>
                     </div>
                 </div>
                 <div class="col-md-3">
                     <div class="metric-card text-center">
                         <span class="status-badge <?php echo ($sandbox_credentials['api_user'] !== 'NEEDS_GENERATION') ? 'status-success' : 'status-warning'; ?>">
                             <i class="fas fa-circle me-1" style="font-size: 0.5rem;"></i>
                             <?php echo ($sandbox_credentials['api_user'] !== 'NEEDS_GENERATION') ? 'Ready' : 'Setup Required'; ?>
                         </span>
                         <p class="text-muted mb-0 mt-2">Credential Status</p>
                     </div>
                 </div>
             </div>

             <!-- Main Content Tabs -->
             <div class="row">
                 <div class="col-12">
                     <div class="sandbox-card">
                         <div class="card-body">
                             <!-- Enhanced Navigation Tabs -->
                             <ul class="nav nav-pills nav-justified" id="sandboxTabs" role="tablist">
                                 <li class="nav-item" role="presentation">
                                     <button class="nav-link active" id="overview-tab" data-bs-toggle="pill" data-bs-target="#overview" type="button" role="tab" aria-controls="overview" aria-selected="true">
                                         <i class="fas fa-home"></i>
                                         Overview
                                     </button>
                                 </li>
                                 <li class="nav-item" role="presentation">
                                     <button class="nav-link" id="quickstart-tab" data-bs-toggle="pill" data-bs-target="#quickstart" type="button" role="tab" aria-controls="quickstart" aria-selected="false">
                                         <i class="fas fa-rocket"></i>
                                         Quick Start
                                     </button>
                                 </li>
                                 <li class="nav-item" role="presentation">
                                     <button class="nav-link" id="simulator-tab" data-bs-toggle="pill" data-bs-target="#simulator" type="button" role="tab" aria-controls="simulator" aria-selected="false">
                                         <i class="fas fa-mobile-alt"></i>
                                         Live Testing
                                     </button>
                                 </li>
                                 <li class="nav-item" role="presentation">
                                     <button class="nav-link" id="debug-tab" data-bs-toggle="pill" data-bs-target="#debug" type="button" role="tab" aria-controls="debug" aria-selected="false">
                                         <i class="fas fa-bug"></i>
                                         Debug Info
                                     </button>
                                 </li>
                             </ul>

                             <!-- Enhanced Tab Content -->
                             <div class="tab-content" id="sandboxTabContent">
                                 
                                 <!-- Overview Tab -->
                                 <div class="tab-pane fade show active" id="overview" role="tabpanel" aria-labelledby="overview-tab">
                                     <div class="row">
                                         <!-- MTN Sandbox Credentials -->
                                         <div class="col-md-6">
                                             <div class="card border-0 h-100 <?php echo ($sandbox_credentials['api_user'] === 'NEEDS_GENERATION') ? 'credential-status-card' : 'credential-status-card ready'; ?>">
                                                 <div class="card-body">
                                                     <h5 class="card-title">
                                                         <i class="fas fa-key me-2 text-primary"></i>
                                                         MTN Sandbox Credentials
                                                         <?php if ($sandbox_credentials['api_user'] === 'NEEDS_GENERATION'): ?>
                                                         <span class="badge bg-warning ms-2">
                                                             <i class="fas fa-exclamation-triangle me-1"></i>Setup Required
                                                         </span>
                                                         <?php else: ?>
                                                         <span class="badge bg-success ms-2">
                                                             <i class="fas fa-check me-1"></i>Ready
                                                         </span>
                                                         <?php endif; ?>
                                                     </h5>
                                                     
                                                     <?php if ($sandbox_credentials['api_user'] === 'NEEDS_GENERATION'): ?>
                                                     <div class="alert alert-warning">
                                                         <i class="fas fa-info-circle me-2"></i>
                                                         <strong>Setup Required:</strong> Your MTN MoMo API credentials need to be generated from your subscription key.
                                                         <br><small>This is a one-time setup process that creates your unique API User and API Key.</small>
                                                     </div>
                                                     <?php else: ?>
                                                     <p class="text-muted">These are your generated MTN MoMo sandbox credentials for testing</p>
                                                     <?php endif; ?>
                                                     
                                                     <div class="mb-3">
                                                         <label class="form-label">Subscription Key</label>
                                                         <div class="input-group">
                                                             <input type="text" class="form-control" value="<?php echo $sandbox_credentials['subscription_key']; ?>" readonly>
                                                             <button class="btn btn-outline-secondary copy-btn" type="button">
                                                                 <i class="fas fa-copy"></i>
                                                             </button>
                                                         </div>
                                                     </div>
                                                     
                                                     <div class="mb-3">
                                                         <label class="form-label">API User UUID</label>
                                                         <div class="input-group">
                                                             <input type="text" class="form-control" value="<?php echo $sandbox_credentials['api_user']; ?>" readonly>
                                                             <?php if ($sandbox_credentials['api_user'] !== 'NEEDS_GENERATION'): ?>
                                                             <button class="btn btn-outline-secondary copy-btn" type="button">
                                                                 <i class="fas fa-copy"></i>
                                                             </button>
                                                             <?php endif; ?>
                                                         </div>
                                                         <?php if ($sandbox_credentials['api_user'] === 'NEEDS_GENERATION'): ?>
                                                         <small class="text-warning">
                                                             <i class="fas fa-arrow-right me-1"></i>
                                                             Will be generated automatically during setup
                                                         </small>
                                                         <?php endif; ?>
                                                     </div>
                                                     
                                                     <div class="mb-3">
                                                         <label class="form-label">API Key</label>
                                                         <div class="input-group">
                                                             <input type="password" class="form-control" value="<?php echo $sandbox_credentials['api_key']; ?>" readonly>
                                                             <?php if ($sandbox_credentials['api_key'] !== 'NEEDS_GENERATION'): ?>
                                                             <button class="btn btn-outline-secondary" type="button" id="toggleApiKey">
                                                                 <i class="fas fa-eye"></i>
                                                             </button>
                                                             <button class="btn btn-outline-secondary copy-btn" type="button">
                                                                 <i class="fas fa-copy"></i>
                                                             </button>
                                                             <?php endif; ?>
                                                         </div>
                                                         <?php if ($sandbox_credentials['api_key'] === 'NEEDS_GENERATION'): ?>
                                                         <small class="text-warning">
                                                             <i class="fas fa-arrow-right me-1"></i>
                                                             Will be generated automatically during setup
                                                         </small>
                                                         <?php endif; ?>
                                                     </div>
                                                     
                                                     <div class="mb-3">
                                                         <label class="form-label">Base URL</label>
                                                         <div class="input-group">
                                                             <input type="text" class="form-control" value="<?php echo $sandbox_credentials['base_url']; ?>" readonly>
                                                             <button class="btn btn-outline-secondary copy-btn" type="button">
                                                                 <i class="fas fa-copy"></i>
                                                             </button>
                                                         </div>
                                                     </div>
                                                     
                                                     <hr>
                                                     
                                                     <!-- Action Buttons -->
                                                     <div class="d-grid gap-2">
                                                         <?php if ($sandbox_credentials['api_user'] === 'NEEDS_GENERATION'): ?>
                                                         <button class="btn btn-warning" onclick="showCredentialSetupModal()">
                                                             <i class="fas fa-cog me-2"></i>
                                                             Generate MTN Credentials
                                                         </button>
                                                         <small class="text-muted text-center">
                                                             <i class="fas fa-shield-alt me-1"></i>
                                                             Secure one-time setup using MTN's official API
                                                         </small>
                                                         <?php else: ?>
                                                         <button class="btn btn-outline-success" onclick="testMTNConnection()">
                                                             <i class="fas fa-plug me-2"></i>
                                                             Test Connection
                                                         </button>
                                                         
                                                         <!-- Credential Status -->
                                                         <div class="mt-2 p-2 bg-light rounded">
                                                             <small class="text-muted d-block">
                                                                 <strong>Status:</strong> 
                                                                 <span class="text-success">
                                                                     <i class="fas fa-check-circle me-1"></i>
                                                                     Ready for testing
                                                                 </span>
                                                             </small>
                                                             <small class="text-muted d-block">
                                                                 <strong>Environment:</strong> <?php echo ucfirst($sandbox_credentials['environment']); ?>
                                                             </small>
                                                             <small class="text-muted d-block">
                                                                 <strong>Last Updated:</strong> 
                                                                 <?php 
                                                                 if ($stored_credentials) {
                                                                     echo date('M j, Y g:i A', strtotime($stored_credentials['updated_at']));
                                                                 } else {
                                                                     echo 'Just now';
                                                                 }
                                                                 ?>
                                                             </small>
                                                         </div>
                                                         <?php endif; ?>
                                                     </div>
                                                 </div>
                                             </div>
                                         </div>
                                         
                                         <!-- Test Phone Numbers -->
                                         <div class="col-md-6">
                                             <div class="card border-0 h-100">
                                                 <div class="card-body">
                                                     <h5 class="card-title">
                                                         <i class="fas fa-mobile-alt me-2 text-success"></i>
                                                         Test Phone Numbers
                                                     </h5>
                                                     <p class="text-muted">Use these test numbers for different scenarios</p>
                                                     
                                                     <div class="mb-3">
                                                         <div class="phone-badge success" data-phone="<?php echo $sandbox_credentials['test_phones']['success']; ?>">
                                                             <i class="fas fa-check-circle me-2"></i>
                                                             <strong><?php echo $sandbox_credentials['test_phones']['success']; ?></strong>
                                                             <small class="ms-2">Success</small>
                                                         </div>
                                                         <div class="phone-badge warning" data-phone="<?php echo $sandbox_credentials['test_phones']['insufficient']; ?>">
                                                             <i class="fas fa-exclamation-triangle me-2"></i>
                                                             <strong><?php echo $sandbox_credentials['test_phones']['insufficient']; ?></strong>
                                                             <small class="ms-2">Insufficient</small>
                                                         </div>
                                                         <div class="phone-badge danger" data-phone="<?php echo $sandbox_credentials['test_phones']['invalid']; ?>">
                                                             <i class="fas fa-times-circle me-2"></i>
                                                             <strong><?php echo $sandbox_credentials['test_phones']['invalid']; ?></strong>
                                                             <small class="ms-2">Invalid</small>
                                                         </div>
                                                         <div class="phone-badge secondary" data-phone="<?php echo $sandbox_credentials['test_phones']['timeout']; ?>">
                                                             <i class="fas fa-clock me-2"></i>
                                                             <strong><?php echo $sandbox_credentials['test_phones']['timeout']; ?></strong>
                                                             <small class="ms-2">Timeout</small>
                                                         </div>
                                                     </div>
                                                     
                                                     <hr>
                                                     
                                                     <h6 class="mb-2">Quick Actions</h6>
                                                     <div class="d-grid gap-2">
                                                         <button class="btn btn-primary" onclick="switchTab('quickstart')">
                                                             <i class="fas fa-play me-2"></i>
                                                             Start API Tutorial
                                                         </button>
                                                         <button class="btn btn-outline-primary" onclick="switchTab('simulator')">
                                                             <i class="fas fa-mobile-alt me-2"></i>
                                                             Live Payment Testing
                                                         </button>
                                                     </div>
                                                 </div>
                                             </div>
                                         </div>
                                     </div>
                                 </div>

                                 <!-- Enhanced Quick Start Tab -->
                                 <div class="tab-pane fade" id="quickstart" role="tabpanel" aria-labelledby="quickstart-tab">
                                     <div class="row">
                                         <div class="col-md-4">
                                             <h5 class="mb-3">
                                                 <i class="fas fa-graduation-cap me-2"></i>
                                                 API Integration Steps
                                             </h5>
                                             
                                             <div class="quickstart-step-card active" data-step="1" id="step-1-card">
                                                 <div class="step-header">
                                                     <div class="step-icon" id="step-1-icon">1</div>
                                                     <div>
                                                         <h6 class="mb-1">Get Access Token</h6>
                                                         <small class="text-muted">Authenticate with MTN API</small>
                                                     </div>
                                                 </div>
                                                 <div class="step-actions">
                                                     <button class="btn btn-sm btn-outline-primary" onclick="executeStep(1)">
                                                         <i class="fas fa-play me-1"></i>
                                                         Execute Step
                                                     </button>
                                                 </div>
                                             </div>
                                             
                                             <div class="quickstart-step-card" data-step="2" id="step-2-card">
                                                 <div class="step-header">
                                                     <div class="step-icon pending" id="step-2-icon">2</div>
                                                     <div>
                                                         <h6 class="mb-1">Request Payment</h6>
                                                         <small class="text-muted">Initiate MoMo transaction</small>
                                                     </div>
                                                 </div>
                                                 <div class="step-actions">
                                                     <button class="btn btn-sm btn-outline-primary" onclick="executeStep(2)" disabled>
                                                         <i class="fas fa-play me-1"></i>
                                                         Execute Step
                                                     </button>
                                                 </div>
                                             </div>
                                             
                                             <div class="quickstart-step-card" data-step="3" id="step-3-card">
                                                 <div class="step-header">
                                                     <div class="step-icon pending" id="step-3-icon">3</div>
                                                     <div>
                                                         <h6 class="mb-1">Check Status</h6>
                                                         <small class="text-muted">Monitor payment status</small>
                                                     </div>
                                                 </div>
                                                 <div class="step-actions">
                                                     <button class="btn btn-sm btn-outline-primary" onclick="executeStep(3)" disabled>
                                                         <i class="fas fa-play me-1"></i>
                                                         Execute Step
                                                     </button>
                                                 </div>
                                             </div>
                                             
                                             <div class="quickstart-step-card" data-step="4" id="step-4-card">
                                                 <div class="step-header">
                                                     <div class="step-icon pending" id="step-4-icon">4</div>
                                                     <div>
                                                         <h6 class="mb-1">Complete</h6>
                                                         <small class="text-muted">Integration ready</small>
                                                     </div>
                                                 </div>
                                                 <div class="step-actions">
                                                     <button class="btn btn-sm btn-success" onclick="completeQuickStart()" disabled>
                                                         <i class="fas fa-check me-1"></i>
                                                         Complete
                                                     </button>
                                                 </div>
                                             </div>
                                         </div>
                                         
                                         <div class="col-md-8">
                                             <div class="tutorial-content" id="tutorial-content">
                                                 <h5 class="mb-3">
                                                     <span class="badge bg-primary me-2">Step 1</span>
                                                     Get Access Token from MTN MoMo API
                                                 </h5>
                                                 
                                                 <div class="alert alert-info">
                                                     <i class="fas fa-info-circle me-2"></i>
                                                     This step makes a real API call to MTN MoMo sandbox to obtain an access token.
                                                 </div>
                                                 
                                                 <div class="mb-3">
                                                     <label class="form-label">API Endpoint</label>
                                                     <div class="api-endpoint">
                                                         <button class="copy-endpoint" onclick="copyToClipboard(this.parentElement.textContent)">
                                                             <i class="fas fa-copy"></i>
                                                         </button>
<span class="method">POST</span> <span class="url"><?php echo $sandbox_credentials['base_url']; ?>/collection/token/</span>
<span class="header">Authorization: Basic <?php echo ($sandbox_credentials['api_user'] !== 'NEEDS_GENERATION') ? '[BASE64_ENCODED_CREDENTIALS]' : '[CREDENTIALS_NEEDED]'; ?></span>
<span class="header">Ocp-Apim-Subscription-Key: <?php echo $sandbox_credentials['subscription_key']; ?></span>
<span class="header">X-Target-Environment: <?php echo $sandbox_credentials['environment']; ?></span>
                                                     </div>
                                                 </div>
                                                 
                                                 <div class="tutorial-navigation">
                                                     <div>
                                                         <small class="text-muted">
                                                             <i class="fas fa-lightbulb me-1"></i>
                                                             Click "Execute Step" to make the actual API call
                                                         </small>
                                                     </div>
                                                     <button class="btn btn-success" id="executeStep1Btn" onclick="executeStep(1)">
                                                         <i class="fas fa-play me-2"></i>
                                                         Execute Step 1
                                                     </button>
                                                 </div>
                                                 
                                                 <div id="step-1-result" class="test-result d-none">
                                                     <div class="result-header">
                                                         <h6 class="mb-0">API Response</h6>
                                                         <span class="status-badge" id="step-1-status">Pending</span>
                                                     </div>
                                                     <div class="result-content" id="step-1-content">
                                                         <!-- Results will be populated here -->
                                                     </div>
                                                 </div>
                                             </div>
                                         </div>
                                     </div>
                                 </div>

                                 <!-- Enhanced Live Testing Tab -->
                                 <div class="tab-pane fade" id="simulator" role="tabpanel" aria-labelledby="simulator-tab">
                                     <div class="row">
                                         <div class="col-md-6">
                                             <div class="test-form">
                                                 <h5 class="mb-3">
                                                     <i class="fas fa-mobile-alt me-2"></i>
                                                     Live Payment Testing
                                                 </h5>
                                                 
                                                 <div class="alert alert-info mb-3">
                                                     <i class="fas fa-info-circle me-2"></i>
                                                     Testing with real MTN MoMo sandbox. No real money involved.
                                                 </div>
                                                 
                                                 <form id="paymentTestForm">
                                                     <div class="mb-3">
                                                         <label class="form-label">Test Phone Number</label>
                                                         <select class="form-select" id="testPhoneSelect">
                                                             <option value="<?php echo $sandbox_credentials['test_phones']['success']; ?>">
                                                                 <?php echo $sandbox_credentials['test_phones']['success']; ?> (Success Scenario)
                                                             </option>
                                                             <option value="<?php echo $sandbox_credentials['test_phones']['insufficient']; ?>">
                                                                 <?php echo $sandbox_credentials['test_phones']['insufficient']; ?> (Insufficient Balance)
                                                             </option>
                                                             <option value="<?php echo $sandbox_credentials['test_phones']['invalid']; ?>">
                                                                 <?php echo $sandbox_credentials['test_phones']['invalid']; ?> (Invalid Number)
                                                             </option>
                                                             <option value="<?php echo $sandbox_credentials['test_phones']['timeout']; ?>">
                                                                 <?php echo $sandbox_credentials['test_phones']['timeout']; ?> (Request Timeout)
                                                             </option>
                                                         </select>
                                                         <small class="form-text text-muted">
                                                             Each number simulates a different payment outcome
                                                         </small>
                                                     </div>
                                                     
                                                     <div class="row mb-3">
                                                         <div class="col-md-6">
                                                             <label class="form-label">Amount</label>
                                                             <input type="number" class="form-control" id="paymentAmount" value="100" min="1" max="10000">
                                                         </div>
                                                         <div class="col-md-6">
                                                             <label class="form-label">Currency</label>
                                                             <select class="form-select" id="paymentCurrency">
                                                                 <option value="EUR">EUR (Euro)</option>
                                                                 <option value="USD">USD (US Dollar)</option>
                                                             </select>
                                                         </div>
                                                     </div>
                                                     
                                                     <div class="mb-3">
                                                         <label class="form-label">Payment Message</label>
                                                         <input type="text" class="form-control" id="paymentMessage" value="ConnectPay Sandbox Test Payment" maxlength="100">
                                                     </div>
                                                     
                                                     <div class="interactive-demo">
                                                         <h6 class="mb-3">Payment Flow Simulation</h6>
                                                         <div class="demo-controls">
                                                             <button type="button" class="btn btn-success" id="testRealPayment">
                                                                 <i class="fas fa-credit-card me-2"></i>
                                                                 Initiate Payment
                                                             </button>
                                                             <button type="button" class="btn btn-info" id="checkPaymentStatus" disabled>
                                                                 <i class="fas fa-search me-2"></i>
                                                                 Check Status
                                                             </button>
                                                             <button type="button" class="btn btn-outline-secondary" onclick="resetPaymentTest()">
                                                                 <i class="fas fa-redo me-2"></i>
                                                                 Reset Test
                                                             </button>
                                                         </div>
                                                         <div class="demo-output" id="paymentDemoOutput">
                                                             <div class="text-center text-muted py-4">
                                                                 <i class="fas fa-mobile-alt fa-3x mb-3"></i>
                                                                 <p>Configure your test payment and click "Initiate Payment" to start</p>
                                                             </div>
                                                         </div>
                                                     </div>
                                                 </form>
                                                 
                                                 <div id="currentAccessToken" class="d-none"></div>
                                                 <div id="currentReferenceId" class="d-none"></div>
                                             </div>
                                         </div>
                                         
                                         <div class="col-md-6">
                                             <div class="test-result">
                                                 <h6 class="mb-3">
                                                     <i class="fas fa-chart-line me-2"></i>
                                                     Live Test Results
                                                 </h6>
                                                 
                                                 <div id="realTestResults">
                                                     <div class="text-center text-muted py-4">
                                                         <i class="fas fa-clipboard-list fa-3x mb-3"></i>
                                                         <h6>No Tests Run Yet</h6>
                                                         <p>Start a payment test to see real MTN API responses here</p>
                                                     </div>
                                                 </div>
                                             </div>
                                             
                                             <div class="debug-section mt-3">
                                                 <h6 class="mb-2">
                                                     <i class="fas fa-terminal me-2"></i>
                                                     API Call Log
                                                 </h6>
                                                 <div class="debug-log" id="apiCallLog">
                                                     <div class="log-entry log-info">
                                                         System ready for API testing...
                                                     </div>
                                                 </div>
                                             </div>
                                         </div>
                                     </div>
                                 </div>

                                 <!-- Enhanced Debug Info Tab -->
                                 <div class="tab-pane fade" id="debug" role="tabpanel" aria-labelledby="debug-tab">
                                     <div class="row">
                                         <div class="col-md-6">
                                             <div class="debug-section">
                                                 <h5 class="mb-3">
                                                     <i class="fas fa-tools me-2"></i>
                                                     Debug Tools
                                                 </h5>
                                                 
                                                 <div class="d-grid gap-2 mb-3">
                                                     <button class="btn btn-outline-primary" onclick="debugMTNSetup()">
                                                         <i class="fas fa-search me-2"></i>
                                                         Debug MTN Setup
                                                     </button>
                                                     <button class="btn btn-outline-info" onclick="testSubscriptionKey()">
                                                         <i class="fas fa-key me-2"></i>
                                                         Test Subscription Key
                                                     </button>
                                                     <button class="btn btn-outline-success" onclick="testMTNConnection()">
                                                         <i class="fas fa-plug me-2"></i>
                                                         Test Connection
                                                     </button>
                                                     <button class="btn btn-outline-warning" onclick="clearDebugLog()">
                                                         <i class="fas fa-trash me-2"></i>
                                                         Clear Debug Log
                                                     </button>
                                                 </div>
                                                 
                                                 <hr>
                                                 
                                                 <h6 class="mb-2">Environment Information:</h6>
                                                 <div class="debug-info">
                                                     <strong>Base URL:</strong> <?php echo $sandbox_credentials['base_url']; ?><br>
                                                     <strong>Environment:</strong> <?php echo $sandbox_credentials['environment']; ?><br>
                                                     <strong>Subscription Key:</strong> <?php echo substr($sandbox_credentials['subscription_key'], 0, 8); ?>...<br>
                                                     <strong>API User Status:</strong> <?php echo ($sandbox_credentials['api_user'] === 'NEEDS_GENERATION') ? 'Needs Generation' : 'Generated'; ?><br>
                                                     <strong>API Key Status:</strong> <?php echo ($sandbox_credentials['api_key'] === 'NEEDS_GENERATION') ? 'Needs Generation' : 'Generated'; ?><br>
                                                     <strong>PHP Version:</strong> <?php echo PHP_VERSION; ?><br>
                                                     <strong>User Agent:</strong> <?php echo $_SERVER['HTTP_USER_AGENT'] ?? 'Unknown'; ?><br>
                                                     <strong>Server Time:</strong> <?php echo date('Y-m-d H:i:s T'); ?>
                                                 </div>
                                                 
                                                 <hr>
                                                 
                                                 <h6 class="mb-2">System Health Check:</h6>
                                                 <div class="list-group">
                                                     <div class="list-group-item d-flex justify-content-between align-items-center">
                                                         <span>
                                                             <i class="fas fa-database me-2"></i>
                                                             Database Connection
                                                         </span>
                                                         <span class="badge bg-success">Active</span>
                                                     </div>
                                                     <div class="list-group-item d-flex justify-content-between align-items-center">
                                                         <span>
                                                             <i class="fas fa-key me-2"></i>
                                                             Subscription Key
                                                         </span>
                                                         <span class="badge bg-info" id="subscriptionKeyStatus">Testing...</span>
                                                     </div>
                                                     <div class="list-group-item d-flex justify-content-between align-items-center">
                                                         <span>
                                                             <i class="fas fa-user me-2"></i>
                                                             API User
                                                         </span>
                                                         <span class="badge <?php echo ($sandbox_credentials['api_user'] !== 'NEEDS_GENERATION') ? 'bg-success' : 'bg-warning'; ?>">
                                                             <?php echo ($sandbox_credentials['api_user'] !== 'NEEDS_GENERATION') ? 'Generated' : 'Pending'; ?>
                                                         </span>
                                                     </div>
                                                     <div class="list-group-item d-flex justify-content-between align-items-center">
                                                         <span>
                                                             <i class="fas fa-lock me-2"></i>
                                                             API Key
                                                         </span>
                                                         <span class="badge <?php echo ($sandbox_credentials['api_key'] !== 'NEEDS_GENERATION') ? 'bg-success' : 'bg-warning'; ?>">
                                                             <?php echo ($sandbox_credentials['api_key'] !== 'NEEDS_GENERATION') ? 'Generated' : 'Pending'; ?>
                                                         </span>
                                                     </div>
                                                     <div class="list-group-item d-flex justify-content-between align-items-center">
                                                         <span>
                                                             <i class="fas fa-network-wired me-2"></i>
                                                             MTN Sandbox Connectivity
                                                         </span>
                                                         <span class="badge bg-secondary" id="mtnConnectivityStatus">Unknown</span>
                                                     </div>
                                                 </div>
                                             </div>
                                         </div>
                                         
                                         <div class="col-md-6">
                                             <div class="debug-section">
                                                 <h6 class="mb-2">
                                                     <i class="fas fa-list me-2"></i>
                                                     Debug Log
                                                     <button class="btn btn-sm btn-outline-secondary float-end" onclick="exportDebugLog()">
                                                         <i class="fas fa-download me-1"></i>
                                                         Export
                                                     </button>
                                                 </h6>
                                                 
                                                 <div class="debug-log" id="debugLog">
                                                     <div class="log-entry log-info">
                                                         [<?php echo date('H:i:s'); ?>] Enhanced MoMo Sandbox initialized
                                                     </div>
                                                 </div>
                                             </div>
                                             
                                             <div class="debug-section mt-3">
                                                 <h6 class="mb-2">
                                                     <i class="fas fa-code me-2"></i>
                                                     API Call Inspector
                                                 </h6>
                                                 
                                                 <div class="mb-2">
                                                     <small class="text-muted">Last API Call Details:</small>
                                                 </div>
                                                 
                                                 <div class="debug-info" id="lastApiCallDetails">
                                                     <em>No API calls made yet...</em>
                                                 </div>
                                                 
                                                 <div class="mt-3">
                                                     <h6 class="mb-2">Quick Debug Actions:</h6>
                                                     <div class="d-flex gap-2 flex-wrap">
                                                         <button class="btn btn-sm btn-outline-primary" onclick="pingMTNEndpoint()">
                                                             <i class="fas fa-satellite-dish me-1"></i>
                                                             Ping MTN
                                                         </button>
                                                         <button class="btn btn-sm btn-outline-info" onclick="validateCredentials()">
                                                             <i class="fas fa-check-circle me-1"></i>
                                                             Validate Creds
                                                         </button>
                                                         <button class="btn btn-sm btn-outline-success" onclick="testNetworkConnectivity()">
                                                             <i class="fas fa-wifi me-1"></i>
                                                             Test Network
                                                         </button>
                                                     </div>
                                                 </div>
                                             </div>
                                             
                                             <div class="debug-section mt-3">
                                                 <h6 class="mb-2">
                                                     <i class="fas fa-chart-bar me-2"></i>
                                                     Session Statistics
                                                 </h6>
                                                 
                                                 <div class="row text-center">
                                                     <div class="col-4">
                                                         <div class="border rounded p-2">
                                                             <h5 class="mb-1 text-primary" id="sessionApiCalls">0</h5>
                                                             <small class="text-muted">API Calls</small>
                                                         </div>
                                                     </div>
                                                     <div class="col-4">
                                                         <div class="border rounded p-2">
                                                             <h5 class="mb-1 text-success" id="sessionSuccessful">0</h5>
                                                             <small class="text-muted">Successful</small>
                                                         </div>
                                                     </div>
                                                     <div class="col-4">
                                                         <div class="border rounded p-2">
                                                             <h5 class="mb-1 text-danger" id="sessionErrors">0</h5>
                                                             <small class="text-muted">Errors</small>
                                                         </div>
                                                     </div>
                                                 </div>
                                             </div>
                                         </div>
                                     </div>
                                 </div>

                             </div>
                         </div>
                     </div>
                 </div>
             </div>

             <?php endif; ?>

         </div> <!-- container-fluid -->

     </div> <!-- content -->

     <?php include 'partials/footer.php'; ?>

 </div>

</div>
<!-- END wrapper -->

<?php include 'partials/right-sidebar.php'; ?>

<?php include 'partials/footer-scripts.php'; ?>

<!-- App js-->
<script src="assets/js/app.min.js"></script>

<!-- Enhanced JavaScript for Tabs and Functionality -->
<script>
// Initialize Feather Icons
feather.replace();

// Global state for enhanced sandbox
let currentQuickStartStep = 1;
let currentAccessToken = null;
let currentReferenceId = null;
let apiCallCount = 0;
let successfulCalls = 0;
let errorCount = 0;
let debugLog = [];

// Initialize the enhanced application
document.addEventListener('DOMContentLoaded', function() {
 initializeEventHandlers();
 initializeCopyButtons();
 checkCredentialStatus();
 initializePhoneBadges();
 loadSessionStats();
 
 console.log('🚀 Enhanced Real MoMo Sandbox with Fixed Tabs initialized!');
 addDebugLog('Enhanced sandbox initialized with improved tab functionality', 'success');
});

// Enhanced debug logging
function addDebugLog(message, type = 'info') {
 const timestamp = new Date().toLocaleTimeString();
 const logEntry = {
     timestamp,
     message,
     type,
     details: arguments[2] || null
 };
 
 debugLog.unshift(logEntry);
 
 // Keep only last 100 entries
 if (debugLog.length > 100) {
     debugLog = debugLog.slice(0, 100);
 }
 
 updateDebugDisplay();
 updateApiCallLog(message, type);
 
 // Console logging with enhanced formatting
 const icon = type === 'error' ? '❌' : type === 'warning' ? '⚠️' : type === 'success' ? '✅' : 'ℹ️';
 console.log(`${icon} [${timestamp}] ${message}`, logEntry.details || '');
}

function updateDebugDisplay() {
 const debugDiv = document.getElementById('debugLog');
 if (!debugDiv) return;
 
 const html = debugLog.slice(0, 20).map(entry => {
     const typeClass = entry.type === 'error' ? 'log-error' : 
                      entry.type === 'warning' ? 'log-warning' : 
                      entry.type === 'success' ? 'log-success' : 'log-info';
     
     const icon = entry.type === 'error' ? '❌' : 
                 entry.type === 'warning' ? '⚠️' : 
                 entry.type === 'success' ? '✅' : 'ℹ️';
     
     return `<div class="log-entry ${typeClass}">
         [${entry.timestamp}] ${icon} ${entry.message}
         ${entry.details ? `<br><small class="opacity-75">${JSON.stringify(entry.details)}</small>` : ''}
     </div>`;
 }).join('');
 
 debugDiv.innerHTML = html || '<div class="log-entry log-info">No debug entries yet...</div>';
}

function updateApiCallLog(message, type) {
 const logDiv = document.getElementById('apiCallLog');
 if (!logDiv) return;
 
 const timestamp = new Date().toLocaleTimeString();
 const typeClass = type === 'error' ? 'log-error' : 
                  type === 'warning' ? 'log-warning' : 
                  type === 'success' ? 'log-success' : 'log-info';
 
 const newEntry = document.createElement('div');
 newEntry.className = `log-entry ${typeClass}`;
 newEntry.innerHTML = `[${timestamp}] ${message}`;
 
 logDiv.insertBefore(newEntry, logDiv.firstChild);
 
 // Keep only last 10 entries in API log
 while (logDiv.children.length > 10) {
     logDiv.removeChild(logDiv.lastChild);
 }
}

function clearDebugLog() {
 debugLog = [];
 updateDebugDisplay();
 document.getElementById('apiCallLog').innerHTML = '<div class="log-entry log-info">Debug log cleared...</div>';
 showNotification('Debug log cleared', 'info');
 addDebugLog('Debug log manually cleared', 'info');
}

// Enhanced tab switching function
function switchTab(tabName) {
 const tabButton = document.getElementById(tabName + '-tab');
 if (tabButton) {
     const tab = new bootstrap.Tab(tabButton);
     tab.show();
     addDebugLog(`Switched to tab: ${tabName}`, 'info');
 }
}

// Enhanced Quick Start functionality
function executeStep(stepNumber) {
 addDebugLog(`Executing quick start step ${stepNumber}`, 'info');
 
 switch(stepNumber) {
     case 1:
         executeStep1();
         break;
     case 2:
         executeStep2();
         break;
     case 3:
         executeStep3();
         break;
     default:
         addDebugLog(`Unknown step: ${stepNumber}`, 'error');
 }
}

async function executeStep1() {
 const button = document.getElementById('executeStep1Btn');
 const resultDiv = document.getElementById('step-1-result');
 const contentDiv = document.getElementById('step-1-content');
 const statusSpan = document.getElementById('step-1-status');
 
 // Update button state
 button.innerHTML = '<div class="spinner-border spinner-border-sm me-2"></div>Calling MTN API...';
 button.disabled = true;
 
 // Show result container
 resultDiv.classList.remove('d-none');
 statusSpan.textContent = 'Loading...';
 statusSpan.className = 'status-badge status-warning';
 
 addDebugLog('Step 1: Requesting access token from MTN API', 'info');
 
 try {
     const result = await makeRealApiCall('get_token');
     
     if (result.success) {
         currentAccessToken = result.data.access_token;
         
         // Update UI
         statusSpan.textContent = '200 OK';
         statusSpan.className = 'status-badge status-success';
         contentDiv.innerHTML = `<pre>${JSON.stringify(result.data, null, 2)}</pre>`;
         
         // Update step card
         document.getElementById('step-1-icon').innerHTML = '<i class="fas fa-check"></i>';
         document.getElementById('step-1-icon').className = 'step-icon completed';
         document.getElementById('step-1-card').className = 'quickstart-step-card completed';
         
         // Enable next step
         document.querySelector('#step-2-card button').disabled = false;
         document.getElementById('step-2-icon').className = 'step-icon';
         document.getElementById('step-2-card').className = 'quickstart-step-card active';
         
         // Update tutorial content for step 2
         updateTutorialContent(2);
         
         button.innerHTML = '<i class="fas fa-check me-2"></i>Step 1 Complete';
         button.className = 'btn btn-success';
         
         addDebugLog('Step 1 completed successfully', 'success');
         showNotification('✅ Access token obtained successfully!', 'success');
         
     } else {
         throw new Error(result.message || 'Failed to get access token');
     }
 } catch (error) {
     statusSpan.textContent = 'Failed';
     statusSpan.className = 'status-badge status-error';
     contentDiv.innerHTML = `<div class="alert alert-danger">Error: ${error.message}</div>`;
     
     button.innerHTML = '<i class="fas fa-redo me-2"></i>Retry Step 1';
     button.disabled = false;
     button.className = 'btn btn-warning';
     
     addDebugLog('Step 1 failed', 'error', error.message);
     showNotification('❌ Step 1 failed: ' + error.message, 'error');
 }
}

async function executeStep2() {
 if (!currentAccessToken) {
     showNotification('Please complete Step 1 first', 'warning');
     return;
 }
 
 addDebugLog('Step 2: Initiating payment request', 'info');
 
 try {
     const result = await makeRealApiCall('request_to_pay', {
         access_token: currentAccessToken,
         amount: '100',
         phone: '46733123450',
         currency: 'EUR'
     });
     
     if (result.success) {
         currentReferenceId = result.data.referenceId;
         
         // Update step 2 as completed
         document.getElementById('step-2-icon').innerHTML = '<i class="fas fa-check"></i>';
         document.getElementById('step-2-icon').className = 'step-icon completed';
         document.getElementById('step-2-card').className = 'quickstart-step-card completed';
         
         // Enable step 3
         document.querySelector('#step-3-card button').disabled = false;
         document.getElementById('step-3-icon').className = 'step-icon';
         document.getElementById('step-3-card').className = 'quickstart-step-card active';
         
         updateTutorialContent(3);
         addDebugLog('Step 2 completed successfully', 'success');
         showNotification('✅ Payment request initiated successfully!', 'success');
         
     } else {
         throw new Error(result.message);
     }
 } catch (error) {
     addDebugLog('Step 2 failed', 'error', error.message);
     showNotification('❌ Step 2 failed: ' + error.message, 'error');
 }
}

async function executeStep3() {
 if (!currentAccessToken || !currentReferenceId) {
     showNotification('Please complete previous steps first', 'warning');
     return;
 }
 
 addDebugLog('Step 3: Checking payment status', 'info');
 
 try {
     const result = await makeRealApiCall('get_transaction_status', {
         access_token: currentAccessToken,
         reference_id: currentReferenceId
     });
     
     if (result.success) {
         // Update step 3 as completed
         document.getElementById('step-3-icon').innerHTML = '<i class="fas fa-check"></i>';
         document.getElementById('step-3-icon').className = 'step-icon completed';
         document.getElementById('step-3-card').className = 'quickstart-step-card completed';
         
         // Enable completion
         document.querySelector('#step-4-card button').disabled = false;
         document.getElementById('step-4-icon').className = 'step-icon';
         document.getElementById('step-4-card').className = 'quickstart-step-card active';
         
         updateTutorialContent(4);
         addDebugLog('Step 3 completed successfully', 'success');
         showNotification('✅ Payment status retrieved successfully!', 'success');
         
     } else {
         throw new Error(result.message);
     }
 } catch (error) {
     addDebugLog('Step 3 failed', 'error', error.message);
     showNotification('❌ Step 3 failed: ' + error.message, 'error');
 }
}

function updateTutorialContent(stepNumber) {
 const contentDiv = document.getElementById('tutorial-content');
 
 const stepContent = {
     2: {
         title: 'Request Payment from MTN MoMo',
         badge: 'Step 2',
         description: 'Now we\'ll initiate a payment request using the access token from Step 1.',
         apiCall: 'POST /collection/v1_0/requesttopay'
     },
     3: {
         title: 'Check Payment Status',
         badge: 'Step 3', 
         description: 'Monitor the payment status using the reference ID from Step 2.',
         apiCall: 'GET /collection/v1_0/requesttopay/{referenceId}'
     },
     4: {
         title: 'Integration Complete!',
         badge: 'Complete',
         description: 'Congratulations! You\'ve successfully completed the MTN MoMo integration tutorial.',
         apiCall: null
     }
 };
 
 const step = stepContent[stepNumber];
 if (!step) return;
 
 contentDiv.innerHTML = `
     <h5 class="mb-3">
         <span class="badge ${stepNumber === 4 ? 'bg-success' : 'bg-primary'} me-2">${step.badge}</span>
         ${step.title}
     </h5>
     
     ${stepNumber === 4 ? `
         <div class="alert alert-success">
             <i class="fas fa-check-circle me-2"></i>
             You have successfully integrated with MTN MoMo sandbox! You can now proceed to live testing or implement these patterns in your application.
         </div>
         
         <div class="tutorial-navigation">
             <button class="btn btn-outline-primary" onclick="switchTab('simulator')">
                 <i class="fas fa-mobile-alt me-2"></i>
                 Continue to Live Testing
             </button>
             <button class="btn btn-success" onclick="completeQuickStart()">
                 <i class="fas fa-graduation-cap me-2"></i>
                 Complete Tutorial
             </button>
         </div>
     ` : `
         <div class="alert alert-info">
             <i class="fas fa-info-circle me-2"></i>
             ${step.description}
         </div>
         
         ${step.apiCall ? `
             <div class="mb-3">
                 <label class="form-label">API Endpoint</label>
                 <div class="api-endpoint">
                     <span class="method">GET</span> <span class="url"><?php echo $sandbox_credentials['base_url']; ?>${step.apiCall}</span>
                 </div>
             </div>
         ` : ''}
         
         <div class="tutorial-navigation">
             <small class="text-muted">
                 <i class="fas fa-lightbulb me-1"></i>
                 Click "Execute Step" on the left to proceed
             </small>
             <button class="btn btn-success" onclick="executeStep(${stepNumber})">
                 <i class="fas fa-play me-2"></i>
                 Execute Step ${stepNumber}
             </button>
         </div>
     `}
 `;
}

function completeQuickStart() {
 // Mark final step as completed
 document.getElementById('step-4-icon').innerHTML = '<i class="fas fa-check"></i>';
 document.getElementById('step-4-icon').className = 'step-icon completed';
 document.getElementById('step-4-card').className = 'quickstart-step-card completed';
 
 addDebugLog('Quick start tutorial completed successfully', 'success');
 showNotification('🎉 Tutorial completed! You\'re now ready for live testing.', 'success');
 
 // Auto-switch to live testing tab after 2 seconds
 setTimeout(() => {
     switchTab('simulator');
 }, 2000);
}

// Enhanced Live Testing functionality
async function testRealPayment() {
 const button = document.getElementById('testRealPayment');
 const statusButton = document.getElementById('checkPaymentStatus');
 const outputDiv = document.getElementById('paymentDemoOutput');
 const resultsDiv = document.getElementById('realTestResults');
 
 // Get form values
 const phone = document.getElementById('testPhoneSelect').value;
 const amount = document.getElementById('paymentAmount').value;
 const currency = document.getElementById('paymentCurrency').value;
 const message = document.getElementById('paymentMessage').value;
 
 // Disable button and show loading
 button.innerHTML = '<div class="spinner-border spinner-border-sm me-2"></div>Processing...';
 button.disabled = true;
 
 addDebugLog(`Initiating live payment test: ${amount} ${currency} to ${phone}`, 'info');
 
 try {
     // Step 1: Get access token if we don't have one
     if (!currentAccessToken) {
         outputDiv.innerHTML = '<div class="alert alert-info">Getting access token...</div>';
         addDebugLog('Requesting access token for payment test', 'info');
         
         const tokenResult = await makeRealApiCall('get_token');
         
         if (tokenResult.success && tokenResult.data.access_token) {
             currentAccessToken = tokenResult.data.access_token;
             addDebugLog('Access token received for payment test', 'success');
         } else {
             if (tokenResult.needs_setup) {
                 showNotification('Please generate your MTN credentials first', 'warning');
                 showCredentialSetupModal();
                 return;
             }
             throw new Error('Failed to get access token: ' + tokenResult.message);
         }
     }
     
     // Step 2: Make payment request
     outputDiv.innerHTML = '<div class="alert alert-info">Initiating payment with MTN MoMo...</div>';
     addDebugLog('Making payment request to MTN API', 'info');
     
     const paymentResult = await makeRealApiCall('request_to_pay', {
         access_token: currentAccessToken,
         amount: amount,
         phone: phone,
         currency: currency
     });
     
     if (paymentResult.success) {
         currentReferenceId = paymentResult.data.referenceId;
         
         // Update output
         outputDiv.innerHTML = `
             <div class="alert alert-success">
                 <h6 class="mb-2">Payment Request Sent Successfully!</h6>
                 <p class="mb-1"><strong>Reference ID:</strong> ${currentReferenceId}</p>
                 <p class="mb-1"><strong>Amount:</strong> ${amount} ${currency}</p>
                 <p class="mb-1"><strong>Phone:</strong> ${phone}</p>
                 <p class="mb-0"><strong>Status:</strong> PENDING</p>
             </div>
         `;
         
         // Update results display
         resultsDiv.innerHTML = `
             <div class="result-header">
                 <h6 class="mb-0">Live Payment Result</h6>
                 <span class="status-badge status-success">202 Accepted</span>
             </div>
             <div class="result-content">
${JSON.stringify(paymentResult.data, null, 2)}
             </div>
         `;
         
         // Enable status check button
         statusButton.disabled = false;
         
         addDebugLog('Payment request successful', 'success', { referenceId: currentReferenceId });
         showNotification('Payment request sent to MTN MoMo!', 'success');
         
         // Auto-check status after 3 seconds
         setTimeout(() => {
             checkPaymentStatus();
         }, 3000);
         
     } else {
         throw new Error('Payment request failed: ' + paymentResult.message);
     }
     
 } catch (error) {
     outputDiv.innerHTML = `
         <div class="alert alert-danger">
             <h6 class="mb-2">Payment Test Failed</h6>
             <p class="mb-0">${error.message}</p>
         </div>
     `;
     
     resultsDiv.innerHTML = `
         <div class="alert alert-danger">
             <h6 class="alert-heading">Payment Test Failed</h6>
             <p class="mb-0">${error.message}</p>
         </div>
     `;
     
     addDebugLog('Payment test failed', 'error', error.message);
     showNotification('Payment test failed: ' + error.message, 'error');
 } finally {
     // Re-enable button
     button.innerHTML = '<i class="fas fa-credit-card me-2"></i>Initiate Payment';
     button.disabled = false;
 }
}

async function checkPaymentStatus() {
 if (!currentAccessToken || !currentReferenceId) {
     showNotification('No active payment to check', 'warning');
     return;
 }
 
 const button = document.getElementById('checkPaymentStatus');
 const originalText = button.innerHTML;
 
 button.innerHTML = '<div class="spinner-border spinner-border-sm me-2"></div>Checking...';
 button.disabled = true;
 
 addDebugLog(`Checking payment status for: ${currentReferenceId}`, 'info');
 
 try {
     const statusResult = await makeRealApiCall('get_transaction_status', {
         access_token: currentAccessToken,
         reference_id: currentReferenceId
     });
     
     if (statusResult.success) {
         const status = statusResult.data.status;
         const statusClass = status === 'SUCCESSFUL' ? 'status-success' : 
                           status === 'FAILED' ? 'status-error' : 'status-warning';
         
         // Update output
         const outputDiv = document.getElementById('paymentDemoOutput');
         outputDiv.innerHTML += `
             <div class="alert ${status === 'SUCCESSFUL' ? 'alert-success' : status === 'FAILED' ? 'alert-danger' : 'alert-warning'} mt-2">
                 <h6 class="mb-2">Payment Status Update</h6>
                 <p class="mb-1"><strong>Status:</strong> ${status}</p>
                 <p class="mb-0"><strong>Last Checked:</strong> ${new Date().toLocaleTimeString()}</p>
             </div>
         `;
         
         // Update results
         const resultsDiv = document.getElementById('realTestResults');
         resultsDiv.innerHTML += `
             <hr>
             <div class="result-header">
                 <h6 class="mb-0">Payment Status</h6>
                 <span class="status-badge ${statusClass}">${status}</span>
             </div>
             <div class="result-content">
${JSON.stringify(statusResult.data, null, 2)}
             </div>
         `;
         
         addDebugLog(`Payment status: ${status}`, status === 'SUCCESSFUL' ? 'success' : 'info');
         showNotification(`Payment status: ${status}`, status === 'SUCCESSFUL' ? 'success' : 'info');
         
     } else {
         throw new Error(statusResult.message);
     }
 } catch (error) {
     addDebugLog('Failed to check payment status', 'error', error.message);
     showNotification('Failed to check payment status: ' + error.message, 'error');
 } finally {
     button.innerHTML = originalText;
     button.disabled = false;
 }
}

function resetPaymentTest() {
 document.getElementById('paymentDemoOutput').innerHTML = `
     <div class="text-center text-muted py-4">
         <i class="fas fa-mobile-alt fa-3x mb-3"></i>
         <p>Configure your test payment and click "Initiate Payment" to start</p>
     </div>
 `;
 
 document.getElementById('realTestResults').innerHTML = `
     <div class="text-center text-muted py-4">
         <i class="fas fa-clipboard-list fa-3x mb-3"></i>
         <h6>No Tests Run Yet</h6>
         <p>Start a payment test to see real MTN API responses here</p>
     </div>
 `;
 
 document.getElementById('checkPaymentStatus').disabled = true;
 currentAccessToken = null;
 currentReferenceId = null;
 
 addDebugLog('Payment test reset', 'info');
 showNotification('Payment test reset', 'info');
}

// Phone badge click handlers
function initializePhoneBadges() {
 document.querySelectorAll('.phone-badge').forEach(badge => {
     badge.addEventListener('click', function() {
         const phone = this.dataset.phone;
         const phoneSelect = document.getElementById('testPhoneSelect');
         if (phoneSelect) {
             phoneSelect.value = phone;
             addDebugLog(`Selected test phone: ${phone}`, 'info');
         }
     });
 });
}

// Check if credentials need to be generated
function checkCredentialStatus() {
 const apiUser = document.querySelector('input[value*="NEEDS_GENERATION"]');
 if (apiUser) {
     addDebugLog('Credentials need to be generated', 'warning');
     document.getElementById('subscriptionKeyStatus').textContent = 'Pending Setup';
     document.getElementById('subscriptionKeyStatus').className = 'badge bg-warning';
 } else {
     addDebugLog('Credentials are ready for testing', 'success');
     document.getElementById('subscriptionKeyStatus').textContent = 'Valid';
     document.getElementById('subscriptionKeyStatus').className = 'badge bg-success';
 }
}

// Enhanced debug functions
async function debugMTNSetup() {
 addDebugLog('Starting comprehensive MTN setup debug...', 'info');
 showNotification('Running enhanced debug checks...', 'info');
 
 try {
     const result = await makeRealApiCall('debug_subscription');
     
     addDebugLog('Subscription key test completed', 'info', result.debug_info);
     
     if (result.debug_info.valid) {
         showNotification('✅ Subscription key is valid!', 'success');
         addDebugLog('Subscription key validation: PASSED', 'success');
         document.getElementById('subscriptionKeyStatus').textContent = 'Valid';
         document.getElementById('subscriptionKeyStatus').className = 'badge bg-success';
     } else {
         showNotification('❌ Subscription key validation failed', 'error');
         addDebugLog('Subscription key validation: FAILED', 'error', result.debug_info);
         document.getElementById('subscriptionKeyStatus').textContent = 'Invalid';
         document.getElementById('subscriptionKeyStatus').className = 'badge bg-danger';
     }
     
     console.log('Enhanced MTN Debug Details:', result);
     
 } catch (error) {
     addDebugLog('Debug failed', 'error', error.message);
     showNotification('Debug check failed: ' + error.message, 'error');
 }
}

async function testSubscriptionKey() {
 addDebugLog('Testing subscription key with enhanced validation...', 'info');
 
 try {
     const result = await makeRealApiCall('debug_subscription');
     
     if (result.success && result.debug_info.valid) {
         showNotification('✅ Subscription key test PASSED', 'success');
         addDebugLog('Direct subscription test: PASSED with fixes', 'success');
         document.getElementById('subscriptionKeyStatus').textContent = 'Valid';
         document.getElementById('subscriptionKeyStatus').className = 'badge bg-success';
     } else {
         showNotification('❌ Subscription key test FAILED', 'error');
         addDebugLog('Direct subscription test: FAILED', 'error', result.debug_info);
         document.getElementById('subscriptionKeyStatus').textContent = 'Invalid';
         document.getElementById('subscriptionKeyStatus').className = 'badge bg-danger';
     }
 } catch (error) {
     addDebugLog('Subscription key test error', 'error', error.message);
     showNotification('Subscription test error: ' + error.message, 'error');
 }
}

async function testMTNConnection() {
 const statusElement = document.getElementById('mtnConnectivityStatus');
 statusElement.textContent = 'Testing...';
 statusElement.className = 'badge bg-warning';
 
 addDebugLog('Testing enhanced MTN connection...', 'info');
 
 try {
     const result = await makeRealApiCall('get_token');
     
     if (result.success) {
         showNotification('Enhanced MTN connection test successful! ✅', 'success');
         addDebugLog('Enhanced MTN connection test successful', 'success', result.data);
         statusElement.textContent = 'Connected';
         statusElement.className = 'badge bg-success';
     } else {
         if (result.needs_setup) {
             showNotification('Please generate your enhanced MTN credentials first', 'warning');
             addDebugLog('Enhanced MTN credentials need setup', 'warning');
             statusElement.textContent = 'Setup Required';
             statusElement.className = 'badge bg-warning';
             showCredentialSetupModal();
         } else {
             throw new Error(result.message || 'Enhanced connection test failed');
         }
     }
 } catch (error) {
     showNotification('Enhanced MTN connection test failed: ' + error.message, 'error');
     addDebugLog('Enhanced MTN connection test failed', 'error', error.message);
     statusElement.textContent = 'Failed';
     statusElement.className = 'badge bg-danger';
 }
}

// Quick debug functions
async function pingMTNEndpoint() {
 addDebugLog('Pinging MTN endpoint...', 'info');
 showNotification('Pinging MTN sandbox endpoint...', 'info');
 
 try {
     // Simple connectivity test
     const result = await fetch('<?php echo $sandbox_credentials['base_url']; ?>/collection/token/', {
         method: 'HEAD',
         mode: 'no-cors'
     });
     
     addDebugLog('MTN endpoint ping successful', 'success');
     showNotification('MTN endpoint is reachable', 'success');
     document.getElementById('mtnConnectivityStatus').textContent = 'Reachable';
     document.getElementById('mtnConnectivityStatus').className = 'badge bg-success';
     
 } catch (error) {
     addDebugLog('MTN endpoint ping failed', 'error', error.message);
     showNotification('MTN endpoint ping failed', 'error');
     document.getElementById('mtnConnectivityStatus').textContent = 'Unreachable';
     document.getElementById('mtnConnectivityStatus').className = 'badge bg-danger';
 }
}

async function validateCredentials() {
 if (<?php echo json_encode($sandbox_credentials['api_user'] === 'NEEDS_GENERATION'); ?>) {
     showNotification('Credentials need to be generated first', 'warning');
     return;
 }
 
 addDebugLog('Validating stored credentials...', 'info');
 await testMTNConnection();
}

async function testNetworkConnectivity() {
 addDebugLog('Testing network connectivity...', 'info');
 
 try {
     const response = await fetch('https://httpbin.org/get', { 
         method: 'GET',
         mode: 'cors'
     });
     
     if (response.ok) {
         addDebugLog('Network connectivity test passed', 'success');
         showNotification('Network connectivity is working', 'success');
     } else {
         throw new Error('Network test failed');
     }
 } catch (error) {
     addDebugLog('Network connectivity test failed', 'error', error.message);
     showNotification('Network connectivity test failed', 'error');
 }
}

// Session statistics
function loadSessionStats() {
 updateSessionStats();
}

function updateSessionStats() {
 document.getElementById('sessionApiCalls').textContent = apiCallCount;
 document.getElementById('sessionSuccessful').textContent = successfulCalls;
 document.getElementById('sessionErrors').textContent = errorCount;
 
 // Update metrics display
 updateMetrics();
}

function updateMetrics() {
 document.getElementById('apiCallsCount').textContent = apiCallCount;
 
 const successRate = apiCallCount > 0 ? Math.round((successfulCalls / apiCallCount) * 100) : 0;
 document.getElementById('successRate').textContent = successRate + '%';
 
 // Add visual feedback for success rate
 const successRateElement = document.getElementById('successRate');
 if (successRate >= 80) {
     successRateElement.className = 'text-success mb-1';
 } else if (successRate >= 50) {
     successRateElement.className = 'text-warning mb-1';
 } else {
     successRateElement.className = 'text-danger mb-1';
 }
}

// Enhanced credential setup modal
function showCredentialSetupModal() {
 const modalHtml = `
     <div class="modal fade" id="credentialSetupModal" tabindex="-1" aria-hidden="true">
         <div class="modal-dialog modal-lg">
             <div class="modal-content">
                 <div class="modal-header">
                     <h5 class="modal-title">
                         <i class="fas fa-key me-2"></i>
                         Enhanced MTN MoMo Credential Setup
                     </h5>
                     <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                 </div>
                 <div class="modal-body">
                     <div class="alert alert-info alert-enhanced">
                         <i class="fas fa-info-circle me-2"></i>
                         Enhanced setup with proper Content-Length headers and HTTP/1.1 compliance.
                         This version fixes the "Length Required" error.
                     </div>
                     
                     <div class="row mb-3">
                         <div class="col-md-6">
                             <label class="form-label">Subscription Key</label>
                             <input type="text" class="form-control" id="setupSubscriptionKey" 
                                    value="<?php echo $sandbox_credentials['subscription_key']; ?>" readonly>
                         </div>
                         <div class="col-md-6">
                             <label class="form-label">Callback Host</label>
                             <input type="text" class="form-control" id="setupCallbackHost" 
                                    value="webhook.site" placeholder="webhook.site">
                         </div>
                     </div>
                     
                     <div id="setupProgress" class="d-none">
                         <h6>Enhanced Setup Progress:</h6>
                         <div class="progress mb-2">
                             <div class="progress-bar progress-bar-striped progress-bar-animated" id="setupProgressBar" 
                                  role="progressbar" style="width: 0%"></div>
                         </div>
                         <div id="setupSteps">
                             <div class="setup-step" data-step="1">
                                 <i class="fas fa-circle-notch fa-spin me-2"></i>
                                 Validating subscription key...
                             </div>
                         </div>
                     </div>
                     
                     <div id="setupResult" class="d-none"></div>
                     <div id="setupDebugInfo" class="d-none mt-3"></div>
                 </div>
                 <div class="modal-footer">
                     <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                     <button type="button" class="btn btn-primary" id="startCredentialSetup">
                         <i class="fas fa-cog me-2"></i>
                         Generate Enhanced Credentials
                     </button>
                 </div>
             </div>
         </div>
     </div>
 `;
 
 // Remove existing modal if any
 const existingModal = document.getElementById('credentialSetupModal');
 if (existingModal) {
     existingModal.remove();
 }
 
 // Add modal to page
 document.body.insertAdjacentHTML('beforeend', modalHtml);
 
 // Show modal
 const modal = new bootstrap.Modal(document.getElementById('credentialSetupModal'));
 modal.show();
 
 // Bind setup button
 document.getElementById('startCredentialSetup').addEventListener('click', setupMTNCredentials);
}

// Enhanced setup with better error handling and retry logic
async function setupMTNCredentials() {
 const button = document.getElementById('startCredentialSetup');
 const progressDiv = document.getElementById('setupProgress');
 const resultDiv = document.getElementById('setupResult');
 const debugDiv = document.getElementById('setupDebugInfo');
 const callbackHost = document.getElementById('setupCallbackHost').value;
 
 // Show progress
 progressDiv.classList.remove('d-none');
 button.innerHTML = '<div class="spinner-border spinner-border-sm me-2"></div>Setting up with fixes...';
 button.disabled = true;
 
 addDebugLog('Starting enhanced credential setup process...', 'info');
 
 try {
     // Update progress
     updateSetupProgress(25, 'Testing subscription key with enhanced validation...');
     addDebugLog('Step 1: Enhanced subscription key testing', 'info');
     
     await new Promise(resolve => setTimeout(resolve, 1000));
     
     updateSetupProgress(50, 'Creating API User with proper headers...');
     addDebugLog('Step 2: Creating API User with Content-Length fix', 'info');
     
     const result = await makeRealApiCall('setup_credentials', {
         callback_host: callbackHost
     });
     
     if (result.success) {
         updateSetupProgress(100, 'Enhanced credentials generated successfully!');
         addDebugLog('Enhanced credential setup completed successfully', 'success');
         
         // Show success result
         resultDiv.innerHTML = `
             <div class="alert alert-success alert-enhanced">
                 <h6 class="alert-heading">
                     <i class="fas fa-check-circle me-2"></i>
                     Enhanced Credentials Generated Successfully!
                 </h6>
                 <div class="row">
                     <div class="col-md-6">
                         <strong>API User:</strong><br>
                         <code>${result.credentials.api_user}</code>
                     </div>
                     <div class="col-md-6">
                         <strong>API Key:</strong><br>
                         <code>${result.credentials.api_key.substring(0, 8)}...</code>
                     </div>
                 </div>
                 <hr>
                 <div class="mb-2">
                     <span class="badge bg-success me-2">✓ Content-Length Fixed</span>
                     <span class="badge bg-success me-2">✓ HTTP/1.1 Compliance</span>
                     <span class="badge bg-success">✓ Enhanced Headers</span>
                 </div>
                 <p class="mb-0">Your credentials have been saved and the page will reload to use them.</p>
             </div>
         `;
         
         resultDiv.classList.remove('d-none');
         
         // Update button
         button.innerHTML = '<i class="fas fa-check me-2"></i>Setup Complete';
         button.className = 'btn btn-success';
         
         // Show notification
         showNotification('Enhanced MTN MoMo credentials generated successfully!', 'success');
         
         // Close modal after 3 seconds and reload
         setTimeout(() => {
             const modal = bootstrap.Modal.getInstance(document.getElementById('credentialSetupModal'));
             modal.hide();
             
             // Reload page to use new credentials
             setTimeout(() => {
                 location.reload();
             }, 500);
         }, 3000);
         
     } else {
         throw new Error(result.message || 'Failed to setup enhanced credentials');
     }
     
 } catch (error) {
     // Enhanced error handling
     updateSetupProgress(0, 'Enhanced setup failed!');
     addDebugLog('Enhanced credential setup failed', 'error', error.message);
     
     let errorDetails = '';
     if (error.step_failed) {
         errorDetails += `<p><strong>Failed at step:</strong> ${error.step_failed}</p>`;
     }
     if (error.debug_info) {
         errorDetails += `<p><strong>Enhanced debug info:</strong></p>
                        <div class="debug-info">${JSON.stringify(error.debug_info, null, 2)}</div>`;
     }
     
     resultDiv.innerHTML = `
         <div class="alert alert-danger alert-enhanced">
             <h6 class="alert-heading">
                 <i class="fas fa-exclamation-triangle me-2"></i>
                 Enhanced Setup Failed
             </h6>
             <p>${error.message}</p>
             ${errorDetails}
             <hr>
             <small class="text-muted">
                 Check the Debug tab for more detailed information.
             </small>
         </div>
     `;
     
     resultDiv.classList.remove('d-none');
     
     // Reset button
     button.innerHTML = '<i class="fas fa-redo me-2"></i>Retry Enhanced Setup';
     button.className = 'btn btn-warning';
     button.disabled = false;
     
     showNotification('Failed to setup enhanced MTN credentials: ' + error.message, 'error');
 }
}

function updateSetupProgress(percentage, message) {
 const progressBar = document.getElementById('setupProgressBar');
 const stepsDiv = document.getElementById('setupSteps');
 
 progressBar.style.width = percentage + '%';
 progressBar.setAttribute('aria-valuenow', percentage);
 
 if (percentage <= 25) {
     stepsDiv.innerHTML = `
         <div class="setup-step text-primary">
             <i class="fas fa-circle-notch fa-spin me-2"></i>
             ${message}
         </div>
     `;
 } else if (percentage <= 50) {
     stepsDiv.innerHTML = `
         <div class="setup-step text-success">
             <i class="fas fa-check me-2"></i>
             Subscription key validated with enhanced headers
         </div>
         <div class="setup-step text-primary">
             <i class="fas fa-circle-notch fa-spin me-2"></i>
             ${message}
         </div>
     `;
 } else if (percentage <= 75) {
     stepsDiv.innerHTML = `
         <div class="setup-step text-success">
             <i class="fas fa-check me-2"></i>
             Subscription key validated with enhanced headers
         </div>
         <div class="setup-step text-success">
             <i class="fas fa-check me-2"></i>
             API User created with Content-Length fix
         </div>
         <div class="setup-step text-primary">
             <i class="fas fa-circle-notch fa-spin me-2"></i>
             Generating API Key with proper headers...
         </div>
     `;
 } else if (percentage === 100) {
     stepsDiv.innerHTML = `
         <div class="setup-step text-success">
             <i class="fas fa-check me-2"></i>
             Subscription key validated with enhanced headers
         </div>
         <div class="setup-step text-success">
             <i class="fas fa-check me-2"></i>
             API User created with Content-Length fix
         </div>
         <div class="setup-step text-success">
             <i class="fas fa-check me-2"></i>
             API Key generated with proper HTTP/1.1 headers
         </div>
         <div class="setup-step text-success">
             <i class="fas fa-check me-2"></i>
             ${message}
         </div>
     `;
     progressBar.className = 'progress-bar bg-success progress-bar-striped';
 } else if (percentage === 0) {
     stepsDiv.innerHTML = `
         <div class="setup-step text-danger">
             <i class="fas fa-times me-2"></i>
             ${message}
         </div>
     `;
     progressBar.className = 'progress-bar bg-danger';
 }
}

// Copy functionality
function initializeCopyButtons() {
 document.querySelectorAll('.copy-btn').forEach(btn => {
     btn.addEventListener('click', function() {
         const input = this.parentElement.querySelector('input');
         if (input) {
             copyToClipboard(input.value);
         }
     });
 });
}

function copyToClipboard(text) {
 navigator.clipboard.writeText(text).then(() => {
     showNotification('Copied to clipboard!', 'success');
     addDebugLog(`Copied to clipboard: ${text.substring(0, 20)}...`, 'info');
 });
}

// Enhanced Real API call function
async function makeRealApiCall(action, additionalData = {}) {
 const formData = new FormData();
 formData.append('action', action);
 
 // Add additional data
 Object.keys(additionalData).forEach(key => {
     formData.append(key, additionalData[key]);
 });
 
 addDebugLog(`Making enhanced API call: ${action}`, 'info', additionalData);
 
 // Update last API call details
 document.getElementById('lastApiCallDetails').innerHTML = `
     <strong>Action:</strong> ${action}<br>
     <strong>Timestamp:</strong> ${new Date().toLocaleTimeString()}<br>
     <strong>Data:</strong> ${JSON.stringify(additionalData)}<br>
     <strong>Status:</strong> <span class="text-warning">Processing...</span>
 `;
 
 try {
     const response = await fetch(window.location.href, {
         method: 'POST',
         body: formData
     });
     
     if (!response.ok) {
         throw new Error(`HTTP error! status: ${response.status}`);
     }
     
     const result = await response.json();
     
     // Update metrics
     apiCallCount++;
     if (result.success) {
         successfulCalls++;
         addDebugLog(`Enhanced API call ${action} successful`, 'success');
     } else {
         errorCount++;
         addDebugLog(`Enhanced API call ${action} failed`, 'error', result);
     }
     updateSessionStats();
     
     // Update last API call details
     document.getElementById('lastApiCallDetails').innerHTML = `
         <strong>Action:</strong> ${action}<br>
         <strong>Timestamp:</strong> ${new Date().toLocaleTimeString()}<br>
         <strong>Status:</strong> <span class="text-${result.success ? 'success' : 'danger'}">${result.success ? 'Success' : 'Failed'}</span><br>
         <strong>Message:</strong> ${result.message || 'N/A'}
     `;
     
     return result;
 } catch (error) {
     errorCount++;
     updateSessionStats();
     addDebugLog(`Enhanced API call ${action} error`, 'error', error.message);
     
     // Update last API call details
     document.getElementById('lastApiCallDetails').innerHTML = `
         <strong>Action:</strong> ${action}<br>
         <strong>Timestamp:</strong> ${new Date().toLocaleTimeString()}<br>
         <strong>Status:</strong> <span class="text-danger">Network Error</span><br>
         <strong>Error:</strong> ${error.message}
     `;
     
     return {
         success: false,
         message: 'Network error occurred',
         error: error.message
     };
 }
}

// Export debug log function
function exportDebugLog() {
 const logData = debugLog.map(entry => 
     `[${entry.timestamp}] ${entry.type.toUpperCase()}: ${entry.message}${entry.details ? ' | ' + JSON.stringify(entry.details) : ''}`
 ).join('\n');
 
 const blob = new Blob([logData], { type: 'text/plain' });
 const url = URL.createObjectURL(blob);
 
 const a = document.createElement('a');
 a.href = url;
 a.download = `momo-sandbox-debug-${new Date().toISOString().slice(0, 10)}.log`;
 document.body.appendChild(a);
 a.click();
 document.body.removeChild(a);
 URL.revokeObjectURL(url);
 
 addDebugLog('Debug log exported', 'info');
 showNotification('Debug log exported successfully', 'success');
}

// Event Handlers
function initializeEventHandlers() {
 // API key toggle
 const toggleBtn = document.getElementById('toggleApiKey');
 if (toggleBtn) {
     toggleBtn.addEventListener('click', function() {
         const input = this.parentElement.querySelector('input');
         const icon = this.querySelector('i');
         
         if (input.type === 'password') {
             input.type = 'text';
             icon.className = 'fas fa-eye-slash';
         } else {
             input.type = 'password';
             icon.className = 'fas fa-eye';
         }
     });
 }
 
 // Live testing form handlers
 const testPaymentBtn = document.getElementById('testRealPayment');
 if (testPaymentBtn) {
     testPaymentBtn.addEventListener('click', testRealPayment);
 }
 
 const checkStatusBtn = document.getElementById('checkPaymentStatus');
 if (checkStatusBtn) {
     checkStatusBtn.addEventListener('click', checkPaymentStatus);
 }
}

// Enhanced notification system
function showNotification(message, type = 'info') {
 const toastContainer = document.querySelector('.toast-container') || createToastContainer();
 
 const toast = document.createElement('div');
 toast.className = `toast align-items-center text-white bg-${type === 'success' ? 'success' : type === 'warning' ? 'warning' : type === 'error' ? 'danger' : 'primary'} border-0`;
 toast.setAttribute('role', 'alert');
 
 const icon = type === 'success' ? 'check-circle' : 
             type === 'warning' ? 'exclamation-triangle' : 
             type === 'error' ? 'times-circle' : 'info-circle';
 
 toast.innerHTML = `
     <div class="d-flex">
         <div class="toast-body">
             <i class="fas fa-${icon} me-2"></i>
             ${message}
         </div>
         <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast"></button>
     </div>
 `;
 
 toastContainer.appendChild(toast);
 
 const bsToast = new bootstrap.Toast(toast, {
     autohide: true,
     delay: type === 'error' ? 8000 : 5000
 });
 bsToast.show();
 
 // Remove toast element after it's hidden
 toast.addEventListener('hidden.bs.toast', () => {
     toast.remove();
 });
}

function createToastContainer() {
 const container = document.createElement('div');
 container.className = 'toast-container position-fixed top-0 end-0 p-3';
 container.style.zIndex = '9999';
 document.body.appendChild(container);
 return container;
}

// Tab event listeners with enhanced functionality
document.querySelectorAll('[data-bs-toggle="pill"]').forEach(tab => {
 tab.addEventListener('shown.bs.tab', function (e) {
     const target = e.target.getAttribute('data-bs-target');
     console.log(`Switched to enhanced tab: ${target}`);
     addDebugLog(`Switched to enhanced tab: ${target}`, 'info');
     
     // Initialize specific tab content
     if (target === '#debug') {
         updateDebugDisplay();
         // Auto-test subscription key when debug tab loads
         setTimeout(() => {
             testSubscriptionKey();
         }, 500);
     } else if (target === '#simulator') {
         // Initialize live testing form
         resetPaymentTest();
     } else if (target === '#quickstart') {
         // Reset quick start if needed
         if (currentQuickStartStep > 1) {
             addDebugLog('Quick start tutorial already in progress', 'info');
         }
     }
 });
});

// Global functions for external access
window.MTNSandbox = {
 showCredentialSetupModal,
 setupMTNCredentials,
 testMTNConnection,
 testRealPayment,
 checkPaymentStatus,
 debugMTNSetup,
 testSubscriptionKey,
 clearDebugLog,
 addDebugLog,
 switchTab,
 executeStep,
 resetPaymentTest
};

console.log('🎉 Enhanced Real MoMo Sandbox with Fixed Tabs fully initialized!');
console.log('Available Functions:', Object.keys(window.MTNSandbox));

addDebugLog('Enhanced MoMo Sandbox with improved tab functionality initialized successfully', 'success');
</script>

<?php
// Enhanced logging for access to fixed real sandbox
if ($has_api_access) {
 try {
     $stmt = $conn->prepare("
         INSERT INTO analytics_events (user_id, event_type, event_category, event_action, properties, ip_address, user_agent, created_at) 
         VALUES (?, 'page_view', 'enhanced_sandbox', 'mtn_momo_sandbox_fixed_access', ?, ?, ?, NOW())
     ");
     $properties = json_encode([
         'mtn_sandbox' => true,
         'real_api' => true,
         'enhanced' => true,
         'content_length_fix' => true,
         'http_compliance' => 'HTTP/1.1',
         'environment' => $sandbox_credentials['environment'],
         'credentials_ready' => ($sandbox_credentials['api_user'] !== 'NEEDS_GENERATION'),
         'has_stored_credentials' => !is_null($stored_credentials),
         'subscription_key_hash' => hash('sha256', $sandbox_credentials['subscription_key']),
         'fixes_applied' => ['Content-Length', 'HTTP/1.1', 'Enhanced headers', 'Retry logic'],
         'tabs_enhanced' => true,
         'quick_start_available' => true,
         'live_testing_available' => true,
         'debug_tools_available' => true
     ]);
     $stmt->bind_param("isss", $user_id, $properties, $_SERVER['REMOTE_ADDR'], $_SERVER['HTTP_USER_AGENT']);
     $stmt->execute();
     $stmt->close();
 } catch (Exception $e) {
     error_log("Failed to log enhanced real sandbox access: " . $e->getMessage());
 }
}
?>

</body>
</html>