<?php 
// Include session handling
try {
    include_once 'services/session.php';
} catch (Exception $e) {
    die("Error including session.php: " . $e->getMessage());
}

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

// Get user details
$user_role = $_SESSION['role_name'] ?? 'Customer';
$user_id = $_SESSION['user_id'] ?? 0;
$user_name = $_SESSION['full_name'] ?? $_SESSION['user'];

// Include database connection
try {
    require_once 'layouts/dbconn.php';
} catch (Exception $e) {
    die("Error including database connection: " . $e->getMessage());
}

// Test database connection
if (!isset($conn) || $conn->connect_error) {
    die("Database connection failed: " . ($conn->connect_error ?? 'Connection object not found'));
}

// MODIFIED: Allow sandbox access for all logged-in users
$has_api_access = true; // Sandbox is free for testing

// Check if user has production license (for upgrade prompts)
$has_production_license = 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%')
    ");
    if ($stmt) {
        $stmt->bind_param("i", $user_id);
        $stmt->execute();
        $result = $stmt->get_result()->fetch_assoc();
        $has_production_license = $result['count'] > 0;
        $stmt->close();
    }
} else {
    $has_production_license = true;
}

// MTN MoMo Sandbox Configuration (default fallback)
$sandbox_config = [
    'default_subscription_key' => '8055a558eeae4c29ad65d869982defef',
    'base_url' => 'https://sandbox.momodeveloper.mtn.com',
    'environment' => 'sandbox',
    'callback_host' => 'webhook.site',
    'test_phones' => [
        'success' => '46733123450',
        'insufficient' => '46733123451', 
        'invalid' => '46733123452',
        'timeout' => '46733123453'
    ]
];

// Check for existing credentials
$stored_credentials = null;
try {
    $stmt = $conn->prepare("
        SELECT credential_id, api_user_id, api_key, subscription_key_collection, created_at, updated_at
        FROM mtn_momo_credentials 
        WHERE user_id = ? AND environment = 'SANDBOX' AND status = 'ACTIVE'
        ORDER BY updated_at DESC LIMIT 1
    ");
    if ($stmt) {
        $stmt->bind_param("i", $user_id);
        $stmt->execute();
        $result = $stmt->get_result()->fetch_assoc();
        $stmt->close();
        $stored_credentials = $result;
    }
} catch (Exception $e) {
    error_log("Error fetching credentials: " . $e->getMessage());
}

// Enhanced MTN MoMo API Helper Class with Better Error Handling
if (!class_exists('MTNMoMoAPI')) {
    class MTNMoMoAPI {
        private $subscription_key;
        private $base_url;
        private $environment;
        
        public function __construct($subscription_key, $base_url, $environment = 'sandbox') {
            $this->subscription_key = $subscription_key;
            $this->base_url = $base_url;
            $this->environment = $environment;
        }
        
        public function generateApiUser() {
            $data = random_bytes(16);
            $data[6] = chr(ord($data[6]) & 0x0f | 0x40);
            $data[8] = chr(ord($data[8]) & 0x3f | 0x80);
            return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($data), 4));
        }
        
        // Test subscription key validity
        public function testSubscriptionKey() {
            $headers = [
                'Ocp-Apim-Subscription-Key: ' . $this->subscription_key
            ];
            
            $result = $this->makeApiCall($this->base_url . '/v1_0/apiuser', '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']
            ];
        }
        
        public function createApiUser($api_user, $callback_host) {
            $headers = [
                'Content-Type: application/json',
                'X-Reference-Id: ' . $api_user,
                'Ocp-Apim-Subscription-Key: ' . $this->subscription_key
            ];
            
            $data = json_encode(['providerCallbackHost' => $callback_host]);
            $result = $this->makeApiCall($this->base_url . '/v1_0/apiuser', 'POST', $headers, $data);
            
            return [
                'success' => in_array($result['status'], [201, 409]),
                'api_user' => $api_user,
                'status' => $result['status'],
                'message' => $result['status'] === 201 ? 'API User created successfully' : 
                           ($result['status'] === 409 ? 'API User already exists' : 'Failed to create API User'),
                'debug_info' => [
                    'url' => $this->base_url . '/v1_0/apiuser',
                    'headers' => $headers,
                    'response' => $result['raw']
                ]
            ];
        }
        
        public function generateApiKey($api_user) {
            $headers = [
                'Ocp-Apim-Subscription-Key: ' . $this->subscription_key,
                'Content-Length: 0'
            ];
            
            $result = $this->makeApiCall($this->base_url . '/v1_0/apiuser/' . $api_user . '/apikey', 'POST', $headers);
            
            if ($result['status'] === 201) {
                $api_key = isset($result['data']['apiKey']) ? $result['data']['apiKey'] : trim($result['raw'], '"\'');
                
                // Validate API key format
                if ($api_key && strlen($api_key) >= 16 && preg_match('/^[a-f0-9]+$/i', $api_key)) {
                    return [
                        'success' => true,
                        'api_key' => $api_key,
                        'status' => $result['status'],
                        'message' => 'API Key generated successfully'
                    ];
                } else {
                    return [
                        'success' => false,
                        'status' => $result['status'],
                        'error' => 'Invalid API Key format received',
                        'raw_response' => $result['raw']
                    ];
                }
            }
            
            return [
                'success' => false,
                'status' => $result['status'],
                'error' => $result['raw'],
                'message' => 'Failed to generate API Key'
            ];
        }
        
        public function getAccessToken($api_user, $api_key) {
            $headers = [
                'Authorization: Basic ' . base64_encode($api_user . ':' . $api_key),
                'Ocp-Apim-Subscription-Key: ' . $this->subscription_key,
                'Content-Length: 0'
            ];
            
            $result = $this->makeApiCall($this->base_url . '/collection/token/', 'POST', $headers);
            
            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
                ];
            }
            
            return [
                'success' => false,
                'status' => $result['status'],
                'error' => $result['raw'],
                'message' => 'Failed to get access token'
            ];
        }
        
        public function requestToPay($access_token, $amount, $currency, $phone) {
            $reference_id = $this->generateApiUser();
            
            $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'
            ];
            
            $payment_data = [
                'amount' => (string)$amount,
                'currency' => $currency,
                'externalId' => 'order_' . time(),
                'payer' => [
                    'partyIdType' => 'MSISDN',
                    'partyId' => $phone
                ],
                'payerMessage' => 'ConnectPay Sandbox Test Payment',
                'payeeNote' => 'Thank you for testing'
            ];
            
            $data = json_encode($payment_data);
            $result = $this->makeApiCall($this->base_url . '/collection/v1_0/requesttopay', 'POST', $headers, $data);
            
            if ($result['status'] === 202) {
                return [
                    'success' => true,
                    'reference_id' => $reference_id,
                    'status' => $result['status'],
                    'message' => 'Payment request initiated successfully'
                ];
            } else {
                return [
                    'success' => false,
                    'reference_id' => $reference_id,
                    'status' => $result['status'],
                    'message' => 'Payment request failed',
                    'error' => $result['raw']
                ];
            }
        }
        
        public function getTransactionStatus($access_token, $reference_id) {
            $headers = [
                'Authorization: Bearer ' . $access_token,
                'X-Target-Environment: ' . $this->environment,
                'Ocp-Apim-Subscription-Key: ' . $this->subscription_key
            ];
            
            $result = $this->makeApiCall($this->base_url . '/collection/v1_0/requesttopay/' . $reference_id, 'GET', $headers);
            
            if ($result['status'] === 200 && $result['data']) {
                return [
                    'success' => true,
                    'status' => $result['data']['status'],
                    'data' => $result['data'],
                    'message' => 'Transaction status retrieved successfully'
                ];
            }
            
            return [
                'success' => false,
                'status' => $result['status'],
                'error' => $result['raw'],
                'message' => 'Failed to get transaction status'
            ];
        }
        
        // Complete setup process
        public function setupCredentials($callback_host = 'webhook.site') {
            try {
                // Step 1: Test subscription key
                $keyTest = $this->testSubscriptionKey();
                if (!$keyTest['valid']) {
                    return [
                        'success' => false,
                        'message' => 'Invalid subscription key: ' . $keyTest['message'],
                        'step' => 'subscription_validation'
                    ];
                }
                
                // Step 2: Generate and create API User
                $api_user = $this->generateApiUser();
                $createResult = $this->createApiUser($api_user, $callback_host);
                
                if (!$createResult['success']) {
                    return [
                        'success' => false,
                        'message' => 'Failed to create API User: ' . $createResult['message'],
                        'step' => 'api_user_creation'
                    ];
                }
                
                // Wait for MTN to process
                sleep(2);
                
                // Step 3: Generate API Key
                $keyResult = $this->generateApiKey($api_user);
                
                if (!$keyResult['success']) {
                    // Retry once
                    sleep(3);
                    $keyResult = $this->generateApiKey($api_user);
                    
                    if (!$keyResult['success']) {
                        return [
                            'success' => false,
                            'message' => 'Failed to generate API Key: ' . $keyResult['message'],
                            'step' => 'api_key_generation'
                        ];
                    }
                }
                
                return [
                    'success' => true,
                    'credentials' => [
                        'subscription_key' => $this->subscription_key,
                        'api_user' => $api_user,
                        'api_key' => $keyResult['api_key'],
                        'environment' => $this->environment,
                        'base_url' => $this->base_url
                    ],
                    'message' => 'MTN MoMo credentials setup completed successfully'
                ];
                
            } catch (Exception $e) {
                return [
                    'success' => false,
                    'message' => 'Setup process failed: ' . $e->getMessage(),
                    'step' => 'exception'
                ];
            }
        }
        
        private function makeApiCall($url, $method, $headers, $data = null) {
            $curl = curl_init();
            
            $options = [
                CURLOPT_URL => $url,
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_TIMEOUT => 30,
                CURLOPT_CONNECTTIMEOUT => 10,
                CURLOPT_CUSTOMREQUEST => $method,
                CURLOPT_HTTPHEADER => $headers,
                CURLOPT_SSL_VERIFYPEER => false,
                CURLOPT_SSL_VERIFYHOST => false,
                CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                CURLOPT_USERAGENT => 'ConnectPay-MoMo-Platform/1.0',
                CURLOPT_VERBOSE => false
            ];
            
            if ($data && in_array($method, ['POST', 'PUT'])) {
                $options[CURLOPT_POSTFIELDS] = $data;
            }
            
            curl_setopt_array($curl, $options);
            $response = curl_exec($curl);
            $httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
            $error = curl_error($curl);
            $info = curl_getinfo($curl);
            curl_close($curl);
            
            return [
                'status' => $httpCode,
                'data' => $response ? json_decode($response, true) : null,
                'raw' => $response,
                'error' => $error,
                'info' => $info
            ];
        }
    }
}

// Handle AJAX requests
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    header('Content-Type: application/json; charset=utf-8');
    
    $action = $_POST['action'];
    $response = ['success' => false, 'message' => 'Unknown action'];
    
    try {
        switch ($action) {
            case 'test_subscription_key':
                $subscription_key = $_POST['subscription_key'] ?? '';
                
                if (empty($subscription_key)) {
                    $response = ['success' => false, 'message' => 'Subscription key is required'];
                    break;
                }
                
                $mtn_api = new MTNMoMoAPI($subscription_key, $sandbox_config['base_url'], $sandbox_config['environment']);
                $testResult = $mtn_api->testSubscriptionKey();
                
                $response = [
                    'success' => $testResult['valid'],
                    'message' => $testResult['message']
                ];
                break;
                
            case 'setup_credentials':
                $subscription_key = $_POST['subscription_key'] ?? '';
                $callback_host = $_POST['callback_host'] ?? 'webhook.site';
                
                if (empty($subscription_key)) {
                    $response = ['success' => false, 'message' => 'Subscription key is required'];
                    break;
                }
                
                $mtn_api = new MTNMoMoAPI($subscription_key, $sandbox_config['base_url'], $sandbox_config['environment']);
                $setupResult = $mtn_api->setupCredentials($callback_host);
                
                if ($setupResult['success']) {
                    try {
                        $checkStmt = $conn->prepare("
                            SELECT credential_id FROM mtn_momo_credentials 
                            WHERE user_id = ? AND environment = 'SANDBOX'
                        ");
                        if (!$checkStmt) {
                            throw new Exception("Prepare failed: " . $conn->error);
                        }
                        
                        $checkStmt->bind_param("i", $user_id);
                        $checkStmt->execute();
                        $existingResult = $checkStmt->get_result();
                        $existing = $existingResult->fetch_assoc();
                        $checkStmt->close();
                        
                        $credential_name = "Custom Sandbox Credentials";
                        $api_user = $setupResult['credentials']['api_user'];
                        $api_key = $setupResult['credentials']['api_key'];
                        $environment = 'SANDBOX';
                        $base_url = $sandbox_config['base_url'];
                        $status = 'ACTIVE';
                        
                        if ($existing) {
                            $stmt = $conn->prepare("
                                UPDATE mtn_momo_credentials 
                                SET credential_name = ?,
                                    api_user_id = ?, 
                                    api_key = ?, 
                                    subscription_key_collection = ?,
                                    base_url = ?,
                                    updated_at = NOW()
                                WHERE user_id = ? AND environment = ?
                            ");
                            if (!$stmt) {
                                throw new Exception("Prepare failed: " . $conn->error);
                            }
                            
                            $stmt->bind_param("sssssiss", 
                                $credential_name,
                                $api_user, 
                                $api_key, 
                                $subscription_key,
                                $base_url,
                                $user_id,
                                $environment
                            );
                        } else {
                            $stmt = $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 (?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())
                            ");
                            if (!$stmt) {
                                throw new Exception("Prepare failed: " . $conn->error);
                            }
                            
                            $stmt->bind_param("isssssss", 
                                $user_id, 
                                $credential_name,
                                $api_user, 
                                $api_key, 
                                $subscription_key, 
                                $environment,
                                $base_url,
                                $status
                            );
                        }
                        
                        if (!$stmt->execute()) {
                            throw new Exception("Execute failed: " . $stmt->error);
                        }
                        $stmt->close();
                        
                        $response = $setupResult;
                        
                    } catch (Exception $e) {
                        $response = [
                            'success' => false, 
                            'message' => 'Failed to save credentials: ' . $e->getMessage()
                        ];
                    }
                } else {
                    $response = $setupResult;
                }
                break;
                
            case 'get_token':
                if (!$stored_credentials) {
                    $response = ['success' => false, 'message' => 'No credentials found', 'needs_setup' => true];
                    break;
                }
                
                $mtn_api = new MTNMoMoAPI($stored_credentials['subscription_key_collection'], $sandbox_config['base_url'], $sandbox_config['environment']);
                $tokenResult = $mtn_api->getAccessToken($stored_credentials['api_user_id'], $stored_credentials['api_key']);
                
                $response = $tokenResult;
                break;
                
            case 'request_payment':
                if (!$stored_credentials) {
                    $response = ['success' => false, 'message' => 'No credentials found', 'needs_setup' => true];
                    break;
                }
                
                $access_token = $_POST['access_token'] ?? '';
                $amount = $_POST['amount'] ?? '100';
                $phone = $_POST['phone'] ?? $sandbox_config['test_phones']['success'];
                $currency = $_POST['currency'] ?? 'EUR';
                
                if (empty($access_token)) {
                    $response = ['success' => false, 'message' => 'Access token is required'];
                    break;
                }
                
                $mtn_api = new MTNMoMoAPI($stored_credentials['subscription_key_collection'], $sandbox_config['base_url'], $sandbox_config['environment']);
                $paymentResult = $mtn_api->requestToPay($access_token, $amount, $currency, $phone);
                
                $response = $paymentResult;
                break;
                
            case 'check_status':
                if (!$stored_credentials) {
                    $response = ['success' => false, 'message' => 'No credentials found', 'needs_setup' => true];
                    break;
                }
                
                $access_token = $_POST['access_token'] ?? '';
                $reference_id = $_POST['reference_id'] ?? '';
                
                if (empty($access_token) || empty($reference_id)) {
                    $response = ['success' => false, 'message' => 'Access token and reference ID are required'];
                    break;
                }
                
                $mtn_api = new MTNMoMoAPI($stored_credentials['subscription_key_collection'], $sandbox_config['base_url'], $sandbox_config['environment']);
                $statusResult = $mtn_api->getTransactionStatus($access_token, $reference_id);
                
                $response = $statusResult;
                break;

            case 'request_production_access':
                $business_name = $_POST['business_name'] ?? '';
                $business_type = $_POST['business_type'] ?? '';
                $monthly_volume = $_POST['monthly_volume'] ?? '';
                $use_case = $_POST['use_case'] ?? '';
                $contact_phone = $_POST['contact_phone'] ?? '';
                
                // Save production request to database
                try {
                    $stmt = $conn->prepare("
                        INSERT INTO production_requests (
                            user_id, business_name, business_type, monthly_volume, 
                            use_case, contact_phone, status, created_at
                        ) VALUES (?, ?, ?, ?, ?, ?, 'PENDING', NOW())
                    ");
                    $stmt->bind_param("isssss", $user_id, $business_name, $business_type, $monthly_volume, $use_case, $contact_phone);
                    
                    if ($stmt->execute()) {
                        $response = [
                            'success' => true,
                            'message' => 'Production access request submitted successfully! Our team will contact you within 24 hours.'
                        ];
                    } else {
                        $response = ['success' => false, 'message' => 'Failed to submit request'];
                    }
                    $stmt->close();
                    
                } catch (Exception $e) {
                    $response = ['success' => false, 'message' => 'Database error: ' . $e->getMessage()];
                }
                break;
                
            default:
                $response = ['success' => false, 'message' => 'Invalid action: ' . $action];
                break;
        }
        
    } catch (Exception $e) {
        $response = [
            'success' => false,
            'message' => 'Server error occurred: ' . $e->getMessage()
        ];
    }
    
    echo json_encode($response, JSON_UNESCAPED_UNICODE);
    exit();
}
?>

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

<head>
    <?php 
    $title = "MTN MoMo Sandbox - Custom Subscription Key";
    if (file_exists('partials/title-meta.php')) {
        try {
            include_once 'partials/title-meta.php';
        } catch (Exception $e) {
            echo "<title>MTN MoMo Sandbox - Custom Subscription Key - ConnectPay</title>\n";
        }
    } else {
        echo "<title>MTN MoMo Sandbox - Custom Subscription Key - ConnectPay</title>\n";
    }
    ?>
    
    <?php 
    if (file_exists('partials/head-css.php')) {
        try {
            include_once 'partials/head-css.php';
        } catch (Exception $e) {
            echo '<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">' . "\n";
            echo '<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">' . "\n";
        }
    } else {
        echo '<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">' . "\n";
        echo '<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">' . "\n";
    }
    ?>
    
    <style>
        /* Base Design System - shadcn/ui inspired */
        :root {
            --background: 0 0% 100%;
            --foreground: 222.2 84% 4.9%;
            --card: 0 0% 100%;
            --card-foreground: 222.2 84% 4.9%;
            --popover: 0 0% 100%;
            --popover-foreground: 222.2 84% 4.9%;
            --primary: 221.2 83.2% 53.3%;
            --primary-foreground: 210 40% 98%;
            --secondary: 210 40% 96%;
            --secondary-foreground: 222.2 84% 4.9%;
            --muted: 210 40% 96%;
            --muted-foreground: 215.4 16.3% 46.9%;
            --accent: 210 40% 96%;
            --accent-foreground: 222.2 84% 4.9%;
            --destructive: 0 84.2% 60.2%;
            --destructive-foreground: 210 40% 98%;
            --border: 214.3 31.8% 91.4%;
            --input: 214.3 31.8% 91.4%;
            --ring: 221.2 83.2% 53.3%;
            --radius: 0.5rem;
        }

        .dark {
            --background: 222.2 84% 4.9%;
            --foreground: 210 40% 98%;
            --card: 222.2 84% 4.9%;
            --card-foreground: 210 40% 98%;
            --popover: 222.2 84% 4.9%;
            --popover-foreground: 210 40% 98%;
            --primary: 217.2 91.2% 59.8%;
            --primary-foreground: 222.2 84% 4.9%;
            --secondary: 217.2 32.6% 17.5%;
            --secondary-foreground: 210 40% 98%;
            --muted: 217.2 32.6% 17.5%;
            --muted-foreground: 215 20.2% 65.1%;
            --accent: 217.2 32.6% 17.5%;
            --accent-foreground: 210 40% 98%;
            --destructive: 0 62.8% 30.6%;
            --destructive-foreground: 210 40% 98%;
            --border: 217.2 32.6% 17.5%;
            --input: 217.2 32.6% 17.5%;
            --ring: 224.3 76.3% 94.1%;
        }

        * {
            border-color: hsl(var(--border));
        }

        body {
            background-color: hsl(var(--background));
            color: hsl(var(--foreground));
        }

        /* Card Components */
        .card {
            border-radius: calc(var(--radius) - 2px);
            border: 1px solid hsl(var(--border));
            background-color: hsl(var(--card));
            color: hsl(var(--card-foreground));
            box-shadow: 0 1px 3px 0 rgb(0 0 0 / 0.1), 0 1px 2px -1px rgb(0 0 0 / 0.1);
        }

        .card-header {
            display: flex;
            flex-direction: column;
            space-y: 1.5;
            padding: 1.5rem;
        }

        .card-title {
            font-size: 1.5rem;
            font-weight: 600;
            line-height: 1;
            letter-spacing: -0.025em;
        }

        .card-description {
            color: hsl(var(--muted-foreground));
            font-size: 0.875rem;
        }

        .card-content {
            padding: 1.5rem;
            padding-top: 0;
        }

        /* Button Components */
        .btn {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            white-space: nowrap;
            border-radius: calc(var(--radius) - 2px);
            font-size: 0.875rem;
            font-weight: 500;
            transition: all 0.2s;
            focus-visible: outline-none;
            border: 1px solid transparent;
            padding: 0.5rem 1rem;
            height: 2.5rem;
        }

        .btn:focus-visible {
            outline: 2px solid hsl(var(--ring));
            outline-offset: 2px;
        }

        .btn:disabled {
            pointer-events: none;
            opacity: 0.5;
        }

        .btn-primary {
            background-color: hsl(var(--primary));
            color: hsl(var(--primary-foreground));
        }

        .btn-primary:hover {
            background-color: hsl(var(--primary) / 0.9);
        }

        .btn-secondary {
            background-color: hsl(var(--secondary));
            color: hsl(var(--secondary-foreground));
        }

        .btn-secondary:hover {
            background-color: hsl(var(--secondary) / 0.8);
        }

        .btn-outline {
            border: 1px solid hsl(var(--border));
            background-color: hsl(var(--background));
        }

        .btn-outline:hover {
            background-color: hsl(var(--accent));
            color: hsl(var(--accent-foreground));
        }

        .btn-destructive {
            background-color: hsl(var(--destructive));
            color: hsl(var(--destructive-foreground));
        }

        .btn-destructive:hover {
            background-color: hsl(var(--destructive) / 0.9);
        }

        .btn-ghost {
            background-color: transparent;
        }

        .btn-ghost:hover {
            background-color: hsl(var(--accent));
            color: hsl(var(--accent-foreground));
        }

        /* Input Components */
        .form-control {
            display: flex;
            height: 2.5rem;
            width: 100%;
            border-radius: calc(var(--radius) - 2px);
            border: 1px solid hsl(var(--border));
            background-color: hsl(var(--background));
            padding: 0.5rem 0.75rem;
            font-size: 0.875rem;
            transition: all 0.2s;
        }

        .form-control:focus {
            outline: none;
            border-color: hsl(var(--ring));
            box-shadow: 0 0 0 2px hsl(var(--ring) / 0.2);
        }

        .form-control::placeholder {
            color: hsl(var(--muted-foreground));
        }

        .form-control:disabled {
            cursor: not-allowed;
            opacity: 0.5;
        }

        /* Alert Components */
        .alert {
            position: relative;
            width: 100%;
            border-radius: calc(var(--radius) - 2px);
            border: 1px solid hsl(var(--border));
            padding: 1rem;
            margin-bottom: 1rem;
        }

        .alert-destructive {
            border-color: hsl(var(--destructive) / 0.5);
            color: hsl(var(--destructive));
            background-color: hsl(var(--destructive) / 0.1);
        }

        .alert-warning {
            border-color: hsl(45 93% 47% / 0.5);
            color: hsl(45 93% 47%);
            background-color: hsl(45 93% 47% / 0.1);
        }

        .alert-info {
            border-color: hsl(var(--primary) / 0.5);
            color: hsl(var(--primary));
            background-color: hsl(var(--primary) / 0.1);
        }

        .alert-success {
            border-color: hsl(142 71% 45% / 0.5);
            color: hsl(142 71% 45%);
            background-color: hsl(142 71% 45% / 0.1);
        }

        /* Badge Components */
        .badge {
            display: inline-flex;
            align-items: center;
            border-radius: 9999px;
            padding: 0.25rem 0.625rem;
            font-size: 0.75rem;
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: 0.025em;
            transition: all 0.2s;
        }

        .badge-default {
            background-color: hsl(var(--primary));
            color: hsl(var(--primary-foreground));
        }

        .badge-secondary {
            background-color: hsl(var(--secondary));
            color: hsl(var(--secondary-foreground));
        }

        .badge-destructive {
            background-color: hsl(var(--destructive));
            color: hsl(var(--destructive-foreground));
        }

        .badge-outline {
            color: hsl(var(--foreground));
            border: 1px solid hsl(var(--border));
        }

        /* Custom Components */
        .sandbox-header {
            background-color: hsl(var(--card));
            border: 1px solid hsl(var(--border));
            border-radius: calc(var(--radius));
            padding: 2rem;
            margin-bottom: 2rem;
        }

        .production-upgrade {
            background-color: hsl(var(--muted));
            border: 1px solid hsl(var(--border));
            border-radius: calc(var(--radius));
            padding: 1.5rem;
            margin-bottom: 2rem;
        }

        .test-card {
            border-radius: calc(var(--radius));
            border: 1px solid hsl(var(--border));
            background-color: hsl(var(--card));
            margin-bottom: 1.5rem;
            transition: all 0.2s;
        }

        .test-card:hover {
            box-shadow: 0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1);
        }

        .status-indicator {
            width: 8px;
            height: 8px;
            border-radius: 50%;
            display: inline-block;
            margin-right: 0.5rem;
        }

        .status-ready { 
            background-color: hsl(142 71% 45%);
        }
        
        .status-pending { 
            background-color: hsl(45 93% 47%);
        }
        
        .status-error { 
            background-color: hsl(var(--destructive));
        }

        .test-phone-card {
            border: 1px solid hsl(var(--border));
            border-radius: calc(var(--radius) - 2px);
            padding: 1rem;
            margin-bottom: 0.5rem;
            cursor: pointer;
            transition: all 0.2s;
            background-color: hsl(var(--card));
        }

        .test-phone-card:hover {
            border-color: hsl(var(--primary));
            background-color: hsl(var(--accent));
        }

        .test-phone-card.selected {
            border-color: hsl(var(--primary));
            background-color: hsl(var(--primary) / 0.1);
        }

        .api-log {
            background-color: hsl(var(--muted));
            border: 1px solid hsl(var(--border));
            border-radius: calc(var(--radius) - 2px);
            padding: 1rem;
            max-height: 400px;
            overflow-y: auto;
            font-family: ui-monospace, SFMono-Regular, "SF Mono", Monaco, Consolas, "Liberation Mono", "Courier New", monospace;
            font-size: 0.875rem;
        }

        .log-entry {
            margin-bottom: 0.5rem;
            padding: 0.25rem 0;
            border-bottom: 1px solid hsl(var(--border));
        }

        .log-entry:last-child {
            border-bottom: none;
        }

        .log-success { color: hsl(142 71% 45%); }
        .log-error { color: hsl(var(--destructive)); }
        .log-info { color: hsl(var(--primary)); }
        .log-warning { color: hsl(45 93% 47%); }

        .subscription-key-section {
            background-color: hsl(var(--muted));
            border: 2px dashed hsl(var(--border));
            border-radius: calc(var(--radius));
            padding: 2rem;
            margin-bottom: 2rem;
            transition: all 0.3s ease;
        }

        .subscription-key-section.testing {
            border-color: hsl(var(--primary));
            background-color: hsl(var(--primary) / 0.05);
        }

        .subscription-key-section.valid {
            border-color: hsl(142 71% 45%);
            background-color: hsl(142 71% 45% / 0.05);
        }

        .subscription-key-section.invalid {
            border-color: hsl(var(--destructive));
            background-color: hsl(var(--destructive) / 0.05);
        }

        .credentials-display {
            background-color: hsl(var(--muted));
            border: 1px solid hsl(var(--border));
            border-radius: calc(var(--radius) - 2px);
            padding: 1.5rem;
            margin-top: 1rem;
        }

        .credential-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 0.5rem 0;
            border-bottom: 1px solid hsl(var(--border));
        }

        .credential-item:last-child {
            border-bottom: none;
        }

        .copy-btn {
            padding: 0.25rem 0.5rem;
            font-size: 0.75rem;
            height: auto;
        }

        /* Enhanced sections (hidden by default) */
        .enhanced-section {
            display: none;
        }

        .enhanced-section.active {
            display: block;
        }

        .enhanced-toggle {
            margin-bottom: 1rem;
        }

        /* Production request modal styles */
        .modal-content {
            border: 1px solid hsl(var(--border));
            border-radius: calc(var(--radius));
            background-color: hsl(var(--card));
        }

        .modal-header {
            border-bottom: 1px solid hsl(var(--border));
        }

        .modal-footer {
            border-top: 1px solid hsl(var(--border));
        }

        /* Utility classes */
        .text-muted {
            color: hsl(var(--muted-foreground));
        }

        .border {
            border: 1px solid hsl(var(--border));
        }

        .rounded {
            border-radius: calc(var(--radius) - 2px);
        }

        .shadow-sm {
            box-shadow: 0 1px 2px 0 rgb(0 0 0 / 0.05);
        }

        .shadow {
            box-shadow: 0 1px 3px 0 rgb(0 0 0 / 0.1), 0 1px 2px -1px rgb(0 0 0 / 0.1);
        }

        /* Animation utilities */
        @keyframes pulse {
            0%, 100% { opacity: 1; }
            50% { opacity: 0.5; }
        }

        .animate-pulse {
            animation: pulse 2s cubic-bezier(0.4, 0, 0.6, 1) infinite;
        }

        /* Loading states */
        .btn-loading {
            position: relative;
            color: transparent !important;
        }

        .btn-loading::after {
            content: "";
            position: absolute;
            width: 16px;
            height: 16px;
            top: 50%;
            left: 50%;
            margin-left: -8px;
            margin-top: -8px;
            border: 2px solid transparent;
            border-top-color: currentColor;
            border-radius: 50%;
            animation: spin 1s linear infinite;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
    </style>
</head>

<body>

<div id="wrapper">
    <?php 
    $pagetitle = "MTN MoMo Sandbox - Custom Subscription Key"; 
    if (file_exists('partials/menu.php')) {
        try {
            include_once 'partials/menu.php';
        } catch (Exception $e) {
            echo '<nav class="navbar navbar-expand-lg navbar-light bg-light border-bottom">
                    <div class="container">
                        <a class="navbar-brand" href="customer-dashboard.php">ConnectPay</a>
                        <span class="navbar-text">Welcome, ' . htmlspecialchars($user_name) . '</span>
                    </div>
                  </nav>';
        }
    } else {
        echo '<nav class="navbar navbar-expand-lg navbar-light bg-light border-bottom">
                <div class="container">
                    <a class="navbar-brand" href="customer-dashboard.php">ConnectPay</a>
                    <span class="navbar-text">Welcome, ' . htmlspecialchars($user_name) . '</span>
                </div>
              </nav>';
    }
    ?>

    <div class="content-page">
        <div class="content">
            <div class="container-fluid">
                
                <!-- Page Title -->
                <div class="row">
                    <div class="col-12">
                        <div class="d-flex justify-content-between align-items-center mb-4">
                            <div>
                                <h1 class="h3 mb-2">
                                    <i class="fas fa-mobile-alt me-2"></i>
                                    MTN MoMo Sandbox
                                </h1>
                                <nav aria-label="breadcrumb">
                                    <ol class="breadcrumb">
                                        <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>
                                </nav>
                            </div>
                            <div class="d-flex gap-2">
                                <span class="badge badge-secondary">FREE TESTING</span>
                                <span class="badge badge-default">CUSTOM KEY</span>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Enhanced Debug Toggle -->
                <div class="row mb-4">
                    <div class="col-12">
                        <div class="enhanced-toggle">
                            <button class="btn btn-outline" id="toggleEnhanced">
                                <i class="fas fa-cogs me-2"></i>
                                Enable Enhanced Debug Mode
                            </button>
                            <small class="text-muted ms-2">
                                Show detailed API logs and debugging information
                            </small>
                        </div>
                    </div>
                </div>

                <!-- Sandbox Header -->
                <div class="sandbox-header">
                    <div class="row align-items-center">
                        <div class="col-md-8">
                            <h2 class="mb-2">
                                <i class="fas fa-mobile-alt me-2"></i>
                                MTN Mobile Money Sandbox
                            </h2>
                            <p class="text-muted mb-0">
                                Use your own MTN MoMo subscription key to generate custom API credentials for testing.
                            </p>
                        </div>
                        <div class="col-md-4 text-md-end">
                            <div class="d-flex flex-column align-items-md-end">
                                <span class="status-indicator status-ready"></span>
                                <span class="small">Ready for Testing</span>
                                <div class="mt-2">
                                    <small class="text-muted">User: <strong><?php echo htmlspecialchars($user_name); ?></strong></small>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <?php if (!$has_production_license): ?>
                <!-- Production Upgrade Section -->
                <div class="production-upgrade">
                    <div class="row align-items-center">
                        <div class="col-md-8">
                            <h5 class="mb-2">
                                <i class="fas fa-rocket me-2"></i>
                                Ready for Production?
                            </h5>
                            <p class="text-muted mb-0">
                                Upgrade to production for live transactions, dedicated support, and advanced features.
                            </p>
                        </div>
                        <div class="col-md-4 text-md-end">
                            <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#productionRequestModal">
                                <i class="fas fa-arrow-up me-2"></i>
                                Request Production Access
                            </button>
                        </div>
                    </div>
                </div>
                <?php endif; ?>

                <!-- Subscription Key Input Section -->
                <div class="subscription-key-section" id="subscriptionKeySection">
                    <div class="row">
                        <div class="col-md-8">
                            <h5 class="mb-3">
                                <i class="fas fa-key me-2"></i>
                                Enter Your MTN MoMo Subscription Key
                            </h5>
                            <p class="text-muted mb-3">
                                Get your subscription key from the MTN MoMo Developer Portal to generate custom API credentials.
                            </p>
                            
                            <div class="row">
                                <div class="col-md-8">
                                    <div class="mb-3">
                                        <label class="form-label">Subscription Key</label>
                                        <div class="input-group">
                                            <input type="password" class="form-control" id="subscriptionKeyInput" 
                                                   placeholder="Enter your MTN MoMo subscription key"
                                                   value="<?php echo $stored_credentials ? htmlspecialchars($stored_credentials['subscription_key_collection']) : ''; ?>">
                                            <button class="btn btn-outline" type="button" id="toggleSubscriptionKey">
                                                <i class="fas fa-eye"></i>
                                            </button>
                                        </div>
                                        <small class="text-muted">
                                            Your subscription key from MTN Developer Portal
                                        </small>
                                    </div>
                                </div>
                                <div class="col-md-4">
                                    <div class="mb-3">
                                        <label class="form-label">Callback Host</label>
                                        <input type="text" class="form-control" id="callbackHostInput" 
                                               value="webhook.site" placeholder="webhook.site">
                                        <small class="text-muted">For webhook testing</small>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="d-flex gap-2">
                                <button class="btn btn-secondary" id="testSubscriptionKey">
                                    <i class="fas fa-check-circle me-2"></i>
                                    Test Subscription Key
                                </button>
                                <button class="btn btn-primary" id="generateCustomCredentials" disabled>
                                    <i class="fas fa-cog me-2"></i>
                                    Generate API Credentials
                                </button>
                            </div>
                            
                            <div class="mt-3" id="keyValidationStatus" style="display: none;">
                                <!-- Status will be populated by JavaScript -->
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="alert alert-info">
                                <h6 class="mb-2">
                                    <i class="fas fa-info-circle me-2"></i>
                                    How to Get Your Key
                                </h6>
                                <ol class="mb-0 small">
                                    <li>Visit <a href="https://momodeveloper.mtn.com" target="_blank" class="text-decoration-none">MTN MoMo Developer Portal</a></li>
                                    <li>Sign up or login to your account</li>
                                    <li>Subscribe to Collections API</li>
                                    <li>Copy your Primary Subscription Key</li>
                                    <li>Paste it here and test!</li>
                                </ol>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Credentials Display Section -->
                <?php if ($stored_credentials): ?>
                <div class="row">
                    <div class="col-12">
                        <div class="test-card">
                            <div class="card-body">
                                <h5 class="card-title">
                                    <i class="fas fa-shield-alt me-2"></i>
                                    Your Generated Credentials
                                    <span class="status-indicator status-ready"></span>
                                    <span class="badge badge-secondary">Active</span>
                                </h5>
                                
                                <div class="alert alert-success">
                                    <i class="fas fa-check-circle me-2"></i>
                                    Your custom API credentials are ready for testing! Generated from your subscription key.
                                </div>
                                
                                <div class="credentials-display">
                                    <div class="credential-item">
                                        <div>
                                            <strong>Subscription Key:</strong><br>
                                            <code><?php echo substr($stored_credentials['subscription_key_collection'], 0, 8); ?>...</code>
                                        </div>
                                        <button class="btn btn-outline copy-btn" onclick="copyToClipboard('<?php echo htmlspecialchars($stored_credentials['subscription_key_collection']); ?>')">
                                            <i class="fas fa-copy"></i>
                                        </button>
                                    </div>
                                    <div class="credential-item">
                                        <div>
                                            <strong>API User:</strong><br>
                                            <code><?php echo substr($stored_credentials['api_user_id'], 0, 20); ?>...</code>
                                        </div>
                                        <button class="btn btn-outline copy-btn" onclick="copyToClipboard('<?php echo htmlspecialchars($stored_credentials['api_user_id']); ?>')">
                                            <i class="fas fa-copy"></i>
                                        </button>
                                    </div>
                                    <div class="credential-item">
                                        <div>
                                            <strong>API Key:</strong><br>
                                            <code id="apiKeyDisplay"><?php echo substr($stored_credentials['api_key'], 0, 8); ?>...</code>
                                        </div>
                                        <div>
                                            <button class="btn btn-outline copy-btn me-1" id="toggleApiKey">
                                                <i class="fas fa-eye"></i>
                                            </button>
                                            <button class="btn btn-outline copy-btn" onclick="copyToClipboard('<?php echo htmlspecialchars($stored_credentials['api_key']); ?>')">
                                                <i class="fas fa-copy"></i>
                                            </button>
                                        </div>
                                    </div>
                                    <div class="credential-item">
                                        <div>
                                            <strong>Created:</strong><br>
                                            <small class="text-muted"><?php echo date('M j, Y g:i A', strtotime($stored_credentials['created_at'])); ?></small>
                                        </div>
                                        <button class="btn btn-outline" id="regenerateCredentials">
                                            <i class="fas fa-refresh me-1"></i>
                                            Regenerate
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <?php endif; ?>

                <!-- Main Testing Content -->
                <div class="row">
                    <!-- Test Phone Numbers -->
                    <div class="col-lg-6">
                        <div class="test-card">
                            <div class="card-body">
                                <h5 class="card-title">
                                    <i class="fas fa-mobile-alt me-2"></i>
                                    Test Phone Numbers
                                    <span class="badge badge-secondary ms-2">SANDBOX ONLY</span>
                                </h5>
                                <p class="text-muted">Select a test number for different scenarios</p>
                                
                                <?php foreach ($sandbox_config['test_phones'] as $scenario => $phone): ?>
                                <div class="test-phone-card" data-phone="<?php echo $phone; ?>" data-scenario="<?php echo $scenario; ?>">
                                    <div class="d-flex justify-content-between align-items-center">
                                        <div>
                                            <strong><?php echo $phone; ?></strong>
                                            <span class="badge badge-<?php echo $scenario === 'success' ? 'secondary' : ($scenario === 'insufficient' ? 'warning' : 'destructive'); ?> ms-2">
                                                <?php echo ucfirst($scenario); ?>
                                            </span>
                                        </div>
                                        <i class="fas fa-mobile-alt text-muted"></i>
                                    </div>
                                    <small class="text-muted">
                                        <?php 
                                        switch($scenario) {
                                            case 'success': echo 'Payment will succeed (test only)'; break;
                                            case 'insufficient': echo 'Insufficient balance error (test)'; break;
                                            case 'invalid': echo 'Invalid phone number error (test)'; break;
                                            case 'timeout': echo 'Request timeout error (test)'; break;
                                        }
                                        ?>
                                    </small>
                                </div>
                                <?php endforeach; ?>
                            </div>
                        </div>
                    </div>

                    <!-- Payment Testing -->
                    <div class="col-lg-6">
                        <div class="test-card">
                            <div class="card-body">
                                <h5 class="card-title">
                                    <i class="fas fa-credit-card me-2"></i>
                                    Payment Testing
                                    <span class="badge badge-outline ms-2">SANDBOX</span>
                                </h5>
                                
                                <div class="row">
                                    <div class="col-md-6">
                                        <div class="mb-3">
                                            <label class="form-label">Amount</label>
                                            <input type="number" class="form-control" id="paymentAmount" value="100" min="1">
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <div class="mb-3">
                                            <label class="form-label">Currency</label>
                                            <select class="form-control" id="paymentCurrency">
                                                <option value="EUR">EUR (Test)</option>
                                                <option value="USD">USD (Test)</option>
                                            </select>
                                        </div>
                                    </div>
                                </div>
                                
                                <div class="mb-3">
                                    <label class="form-label">Selected Phone</label>
                                    <input type="text" class="form-control" id="selectedPhone" value="<?php echo $sandbox_config['test_phones']['success']; ?>" readonly>
                                </div>
                                
                                <div class="d-grid gap-2">
                                    <button class="btn btn-primary" id="startPaymentTest" <?php echo !$stored_credentials ? 'disabled' : ''; ?>>
                                        <i class="fas fa-play me-2"></i>
                                        Start Test Payment
                                    </button>
                                    <button class="btn btn-outline" id="checkPaymentStatus" disabled>
                                        <i class="fas fa-search me-2"></i>
                                        Check Status
                                    </button>
                                </div>
                                
                                <?php if (!$stored_credentials): ?>
                                <div class="mt-3 p-3 border rounded">
                                    <small class="text-muted">
                                        <i class="fas fa-arrow-up me-1"></i>
                                        <strong>First enter your subscription key above</strong> to generate API credentials for testing.
                                    </small>
                                </div>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Enhanced API Activity Log (Hidden by default) -->
                <div class="row enhanced-section" id="enhancedSection">
                    <div class="col-12">
                        <div class="test-card">
                            <div class="card-body">
                                <h5 class="card-title">
                                    <i class="fas fa-terminal me-2"></i>
                                    Enhanced API Activity Log
                                    <span class="badge badge-outline ms-2">DEBUG MODE</span>
                                </h5>
                                
                                <div id="apiLog" class="api-log">
                                    <div class="text-muted text-center">
                                        <i class="fas fa-code fa-2x mb-2 d-block"></i>
                                        Enhanced debug mode ready! All API calls will show detailed information.
                                    </div>
                                </div>
                                
                                <div class="mt-3">
                                    <button class="btn btn-outline" onclick="clearLog()">
                                        <i class="fas fa-trash me-1"></i>
                                        Clear Log
                                    </button>
                                    <button class="btn btn-outline" onclick="exportLog()">
                                        <i class="fas fa-download me-1"></i>
                                        Export Debug Log
                                    </button>
                                    <button class="btn btn-outline" onclick="showLastError()">
                                        <i class="fas fa-exclamation-triangle me-1"></i>
                                        Show Last Error
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

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

<!-- Production Request Modal -->
<div class="modal fade" id="productionRequestModal" tabindex="-1" aria-labelledby="productionRequestModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="productionRequestModalLabel">
                    <i class="fas fa-rocket me-2"></i>
                    Request Production Access
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form id="productionRequestForm">
                    <div class="alert alert-info">
                        <i class="fas fa-info-circle me-2"></i>
                        Tell us about your business needs. Our team will review your request and contact you within 24 hours.
                    </div>
                    
                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="businessName" class="form-label">Business Name *</label>
                                <input type="text" class="form-control" id="businessName" required>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="businessType" class="form-label">Business Type *</label>
                                <select class="form-control" id="businessType" required>
                                    <option value="">Select business type...</option>
                                    <option value="ecommerce">E-commerce Store</option>
                                    <option value="fintech">Fintech/Payment Services</option>
                                    <option value="marketplace">Online Marketplace</option>
                                    <option value="saas">SaaS Platform</option>
                                    <option value="ngo">NGO/Non-profit</option>
                                    <option value="education">Educational Institution</option>
                                    <option value="government">Government Agency</option>
                                    <option value="other">Other</option>
                                </select>
                            </div>
                        </div>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="monthlyVolume" class="form-label">Expected Monthly Volume *</label>
                                <select class="form-control" id="monthlyVolume" required>
                                    <option value="">Select volume range...</option>
                                    <option value="0-1000">$0 - $1,000</option>
                                    <option value="1000-5000">$1,000 - $5,000</option>
                                    <option value="5000-20000">$5,000 - $20,000</option>
                                    <option value="20000-50000">$20,000 - $50,000</option>
                                    <option value="50000+">$50,000+</option>
                                </select>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="contactPhone" class="form-label">Contact Phone</label>
                                <input type="tel" class="form-control" id="contactPhone" placeholder="+211 XXX XXX XXX">
                            </div>
                        </div>
                    </div>
                    
                    <div class="mb-3">
                        <label for="useCase" class="form-label">Use Case Description *</label>
                        <textarea class="form-control" id="useCase" rows="4" 
                                  placeholder="Describe how you plan to use MTN MoMo in your business..." required></textarea>
                    </div>
                    
                    <div class="alert alert-warning">
                        <h6 class="mb-2">
                            <i class="fas fa-exclamation-triangle me-2"></i>
                            Production Requirements
                        </h6>
                        <ul class="mb-0 small">
                            <li>Valid business registration documents</li>
                            <li>MTN MoMo business account verification</li>
                            <li>Compliance with local payment regulations</li>
                            <li>Technical integration review</li>
                        </ul>
                    </div>
                </form>
            </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="submitProductionRequest">
                    <i class="fas fa-paper-plane me-2"></i>
                    Submit Request
                </button>
            </div>
        </div>
    </div>
</div>

<?php 
if (file_exists('partials/footer.php')) {
    try {
        include_once 'partials/footer.php';
    } catch (Exception $e) {
        echo '<footer class="bg-light text-center py-3 mt-5 border-top"><p>&copy; 2024 ConnectPay Platform</p></footer>';
    }
} else {
    echo '<footer class="bg-light text-center py-3 mt-5 border-top"><p>&copy; 2024 ConnectPay Platform</p></footer>';
}
?>

<?php 
if (file_exists('partials/footer-scripts.php')) {
    try {
        include_once 'partials/footer-scripts.php';
    } catch (Exception $e) {
        echo '<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>' . "\n";
        echo '<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>' . "\n";
    }
} else {
    echo '<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>' . "\n";
    echo '<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>' . "\n";
}
?>

<!-- MTN MoMo Sandbox JavaScript -->
<script>
document.addEventListener('DOMContentLoaded', function() {
    console.log('🚀 MTN MoMo Sandbox initialized');
    initializeEventHandlers();
    initializeTestPhones();
    
    <?php if ($stored_credentials): ?>
    addLogEntry('🎉 Custom credentials ready for testing!', 'success');
    addLogEntry('🔑 Using subscription key: <?php echo substr($stored_credentials['subscription_key_collection'], 0, 8); ?>...', 'info');
    <?php else: ?>
    addLogEntry('👋 Welcome! Enter your subscription key to generate custom credentials', 'info');
    <?php endif; ?>
});

// Global variables
let currentAccessToken = null;
let currentReferenceId = null;
let selectedPhoneNumber = '<?php echo $sandbox_config['test_phones']['success']; ?>';
let subscriptionKeyValid = false;
let lastError = null;
let enhancedMode = false;

// Initialize event handlers
function initializeEventHandlers() {
    // Enhanced mode toggle
    const toggleEnhanced = document.getElementById('toggleEnhanced');
    if (toggleEnhanced) {
        toggleEnhanced.addEventListener('click', function() {
            enhancedMode = !enhancedMode;
            const enhancedSection = document.getElementById('enhancedSection');
            
            if (enhancedMode) {
                enhancedSection.classList.add('active');
                this.innerHTML = '<i class="fas fa-cogs me-2"></i>Disable Enhanced Debug Mode';
                this.classList.remove('btn-outline');
                this.classList.add('btn-secondary');
                addLogEntry('🔧 Enhanced debug mode activated', 'info');
            } else {
                enhancedSection.classList.remove('active');
                this.innerHTML = '<i class="fas fa-cogs me-2"></i>Enable Enhanced Debug Mode';
                this.classList.remove('btn-secondary');
                this.classList.add('btn-outline');
                addLogEntry('🔧 Enhanced debug mode deactivated', 'info');
            }
        });
    }

    // Subscription key toggle
    const toggleKeyBtn = document.getElementById('toggleSubscriptionKey');
    if (toggleKeyBtn) {
        toggleKeyBtn.addEventListener('click', function() {
            const input = document.getElementById('subscriptionKeyInput');
            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';
            }
        });
    }
    
    // API key toggle  
    const toggleApiBtn = document.getElementById('toggleApiKey');
    if (toggleApiBtn) {
        toggleApiBtn.addEventListener('click', function() {
            const display = document.getElementById('apiKeyDisplay');
            const icon = this.querySelector('i');
            
            if (display.textContent.includes('...')) {
                display.innerHTML = '<code><?php echo $stored_credentials ? htmlspecialchars($stored_credentials['api_key']) : ''; ?></code>';
                icon.className = 'fas fa-eye-slash';
            } else {
                display.innerHTML = '<code><?php echo $stored_credentials ? substr($stored_credentials['api_key'], 0, 8) . '...' : ''; ?></code>';
                icon.className = 'fas fa-eye';
            }
        });
    }
    
    // Test subscription key
    const testKeyBtn = document.getElementById('testSubscriptionKey');
    if (testKeyBtn) {
        testKeyBtn.addEventListener('click', testSubscriptionKey);
    }
    
    // Generate credentials
    const generateBtn = document.getElementById('generateCustomCredentials');
    if (generateBtn) {
        generateBtn.addEventListener('click', generateCustomCredentials);
    }
    
    // Regenerate credentials
    const regenerateBtn = document.getElementById('regenerateCredentials');
    if (regenerateBtn) {
        regenerateBtn.addEventListener('click', regenerateCredentials);
    }
    
    // Start payment test
    const startTestBtn = document.getElementById('startPaymentTest');
    if (startTestBtn) {
        startTestBtn.addEventListener('click', startPaymentTest);
    }
    
    // Check payment status
    const checkStatusBtn = document.getElementById('checkPaymentStatus');
    if (checkStatusBtn) {
        checkStatusBtn.addEventListener('click', checkPaymentStatus);
    }

    // Production request submission
    const submitProductionBtn = document.getElementById('submitProductionRequest');
    if (submitProductionBtn) {
        submitProductionBtn.addEventListener('click', submitProductionRequest);
    }
    
    // Subscription key input validation
    const keyInput = document.getElementById('subscriptionKeyInput');
    if (keyInput) {
        keyInput.addEventListener('input', function() {
            const generateBtn = document.getElementById('generateCustomCredentials');
            const section = document.getElementById('subscriptionKeySection');
            
            if (this.value.length >= 32) {
                section.className = 'subscription-key-section';
                subscriptionKeyValid = false;
                generateBtn.disabled = true;
            } else {
                section.className = 'subscription-key-section';
                subscriptionKeyValid = false;
                generateBtn.disabled = true;
            }
        });
    }
}

// Initialize test phone selection
function initializeTestPhones() {
    const phoneCards = document.querySelectorAll('.test-phone-card');
    
    if (phoneCards.length > 0) {
        phoneCards[0].classList.add('selected');
    }
    
    phoneCards.forEach(card => {
        card.addEventListener('click', function() {
            phoneCards.forEach(c => c.classList.remove('selected'));
            this.classList.add('selected');
            
            selectedPhoneNumber = this.dataset.phone;
            document.getElementById('selectedPhone').value = selectedPhoneNumber;
            
            const scenario = this.dataset.scenario;
            addLogEntry(`📱 Selected test phone: ${selectedPhoneNumber} (${scenario} scenario)`, 'info');
        });
    });
}

// API call function
async function makeApiCall(action, data = {}) {
    try {
        if (enhancedMode) {
            addLogEntry(`🔧 Starting API call - ${action}`, 'info');
            console.log('🔧 API Call Debug:', { action, data });
        }
        
        const formData = new FormData();
        formData.append('action', action);
        
        Object.keys(data).forEach(key => {
            formData.append(key, data[key]);
            if (enhancedMode) {
                const valuePreview = data[key] ? data[key].substring(0, 50) + (data[key].length > 50 ? '...' : '') : 'empty';
                addLogEntry(`📝 Parameter ${key}: ${valuePreview}`, 'info');
            }
        });
        
        const response = await fetch(window.location.href, {
            method: 'POST',
            body: formData
        });
        
        if (enhancedMode) {
            addLogEntry(`🌐 HTTP Response Status - ${response.status}`, response.ok ? 'success' : 'error');
        }
        
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        
        const contentType = response.headers.get('content-type');
        if (!contentType || !contentType.includes('application/json')) {
            const text = await response.text();
            if (enhancedMode) {
                addLogEntry(`❌ Non-JSON response received`, 'error');
                addLogEntry(`📄 Response: ${text.substring(0, 200)}...`, 'error');
            }
            throw new Error('Server returned non-JSON response');
        }
        
        const result = await response.json();
        
        if (enhancedMode) {
            addLogEntry(`✅ JSON parsed successfully`, 'success');
            console.log(`🔧 API Result for ${action}:`, result);
        }
        
        return result;
        
    } catch (error) {
        lastError = {
            action: action,
            error: error.message,
            timestamp: new Date().toISOString(),
            data: data
        };
        
        addLogEntry(`💥 API call failed - ${error.message}`, 'error');
        console.error(`🔧 API Error for ${action}:`, error);
        
        return {
            success: false,
            message: `Network error: ${error.message}`,
            error: error.message
        };
    }
}

// Show last error with full details
function showLastError() {
    if (!lastError) {
        showNotification('No errors recorded in this session', 'info');
        return;
    }
    
    addLogEntry('🔍 Displaying last error details', 'warning');
    
    const errorDetails = `
        <div class="alert alert-destructive">
            <h6>🔧 Last Error Details:</h6>
            <p><strong>Action:</strong> ${lastError.action}</p>
            <p><strong>Error:</strong> ${lastError.error}</p>
            <p><strong>Time:</strong> ${lastError.timestamp}</p>
            <p><strong>Data:</strong> ${JSON.stringify(lastError.data)}</p>
        </div>
    `;
    
    // Create modal for error details
    const modal = document.createElement('div');
    modal.className = 'modal fade';
    modal.innerHTML = `
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">🔧 Enhanced Debug - Last Error</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    ${errorDetails}
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                </div>
            </div>
        </div>
    `;
    
    document.body.appendChild(modal);
    const bsModal = new bootstrap.Modal(modal);
    bsModal.show();
    
    modal.addEventListener('hidden.bs.modal', () => {
        document.body.removeChild(modal);
    });
}

// Test subscription key
async function testSubscriptionKey() {
    const button = document.getElementById('testSubscriptionKey');
    const generateBtn = document.getElementById('generateCustomCredentials');
    const section = document.getElementById('subscriptionKeySection');
    const statusDiv = document.getElementById('keyValidationStatus');
    const subscriptionKey = document.getElementById('subscriptionKeyInput').value.trim();
    
    if (!subscriptionKey || subscriptionKey.length < 32) {
        showValidationStatus('error', 'Please enter a valid subscription key (32+ characters)', statusDiv);
        return;
    }
    
    const originalText = button.innerHTML;
    
    try {
        button.innerHTML = '<i class="fas fa-spinner fa-spin me-2"></i>Testing...';
        button.disabled = true;
        section.className = 'subscription-key-section testing';
        
        addLogEntry('🔍 Testing subscription key...', 'info');
        
        const result = await makeApiCall('test_subscription_key', {
            subscription_key: subscriptionKey
        });
        
        if (result.success) {
            subscriptionKeyValid = true;
            section.className = 'subscription-key-section valid';
            generateBtn.disabled = false;
            
            showValidationStatus('success', 'Subscription key is valid! You can now generate API credentials.', statusDiv);
            addLogEntry('✅ Validation successful!', 'success');
            showNotification('✅ Subscription key is valid!', 'success');
            
        } else {
            subscriptionKeyValid = false;
            section.className = 'subscription-key-section invalid';
            generateBtn.disabled = true;
            
            showValidationStatus('error', `Subscription key validation failed: ${result.message}`, statusDiv);
            addLogEntry('❌ Validation failed: ' + result.message, 'error');
            showNotification('❌ Invalid subscription key: ' + result.message, 'error');
        }
        
    } catch (error) {
        subscriptionKeyValid = false;
        section.className = 'subscription-key-section invalid';
        generateBtn.disabled = true;
        
        showValidationStatus('error', 'Network error occurred while testing subscription key', statusDiv);
        addLogEntry('❌ Network error during validation: ' + error.message, 'error');
        showNotification('❌ Network error: ' + error.message, 'error');
    } finally {
        button.innerHTML = originalText;
        button.disabled = false;
    }
}

// Show validation status
function showValidationStatus(type, message, container) {
    const alertClass = type === 'success' ? 'alert-success' : type === 'error' ? 'alert-destructive' : 'alert-info';
    const icon = type === 'success' ? 'check-circle' : type === 'error' ? 'times-circle' : 'info-circle';
    
    container.innerHTML = `
        <div class="alert ${alertClass}">
            <i class="fas fa-${icon} me-2"></i>
            ${message}
        </div>
    `;
    container.style.display = 'block';
}

// Generate custom credentials
async function generateCustomCredentials() {
    if (!subscriptionKeyValid) {
        showNotification('Please test your subscription key first', 'warning');
        return;
    }
    
    const button = document.getElementById('generateCustomCredentials');
    const subscriptionKey = document.getElementById('subscriptionKeyInput').value.trim();
    const callbackHost = document.getElementById('callbackHostInput').value.trim();
    const originalText = button.innerHTML;
    
    try {
        button.classList.add('btn-loading');
        button.disabled = true;
        
        addLogEntry('🔄 Credential generation starting...', 'info');
        
        const result = await makeApiCall('setup_credentials', {
            subscription_key: subscriptionKey,
            callback_host: callbackHost
        });
        
        if (result.success) {
            addLogEntry('✅ Credentials generated successfully!', 'success');
            showNotification('🎉 Credentials generated! Page will reload.', 'success');
            
            setTimeout(() => {
                window.location.reload();
            }, 2000);
        } else {
            throw new Error(result.message || 'Failed to generate credentials');
        }
        
    } catch (error) {
        addLogEntry('❌ Failed to generate credentials: ' + error.message, 'error');
        showNotification('❌ Failed to generate credentials: ' + error.message, 'error');
    } finally {
        button.classList.remove('btn-loading');
        button.disabled = false;
    }
}

// Regenerate credentials
async function regenerateCredentials() {
    if (!confirm('Are you sure you want to regenerate your custom credentials? This will invalidate the current ones.')) {
        return;
    }
    
    document.getElementById('subscriptionKeyInput').value = '';
    document.getElementById('subscriptionKeySection').className = 'subscription-key-section';
    document.getElementById('keyValidationStatus').style.display = 'none';
    document.getElementById('generateCustomCredentials').disabled = true;
    subscriptionKeyValid = false;
    
    addLogEntry('🔄 Credentials cleared. Enter your subscription key to regenerate.', 'warning');
    showNotification('Enter your subscription key and test it to regenerate credentials', 'info');
}

// Start payment test
async function startPaymentTest() {
    const button = document.getElementById('startPaymentTest');
    
    try {
        button.classList.add('btn-loading');
        button.disabled = true;
        
        addLogEntry('🚀 Starting payment test...', 'info');
        
        // Step 1: Get access token
        addLogEntry('1️⃣ Getting access token...', 'info');
        const tokenResult = await makeApiCall('get_token');
        
        if (!tokenResult.success) {
            addLogEntry(`❌ Token request failed: ${tokenResult.message}`, 'error');
            throw new Error('Failed to get access token: ' + tokenResult.message);
        }
        
        currentAccessToken = tokenResult.access_token;
        addLogEntry('✅ Access token obtained successfully', 'success');
        
        // Step 2: Request payment
        addLogEntry('2️⃣ Requesting test payment...', 'info');
        const amount = document.getElementById('paymentAmount').value;
        const currency = document.getElementById('paymentCurrency').value;
        
        addLogEntry(`💰 Payment details: ${amount} ${currency} to ${selectedPhoneNumber}`, 'info');
        
        const paymentResult = await makeApiCall('request_payment', {
            access_token: currentAccessToken,
            amount: amount,
            currency: currency,
            phone: selectedPhoneNumber
        });
        
        if (!paymentResult.success) {
            addLogEntry(`❌ Payment request failed: ${paymentResult.message}`, 'error');
            throw new Error('Failed to request payment: ' + paymentResult.message);
        }
        
        currentReferenceId = paymentResult.reference_id;
        addLogEntry(`✅ Test payment requested successfully`, 'success');
        addLogEntry(`🆔 Reference ID: ${currentReferenceId}`, 'info');
        
        document.getElementById('checkPaymentStatus').disabled = false;
        
        setTimeout(() => {
            checkPaymentStatus();
        }, 3000);
        
        showNotification('🎉 Test payment started! Checking status...', 'success');
        
    } catch (error) {
        addLogEntry('❌ Test payment failed: ' + error.message, 'error');
        showNotification('❌ Test payment failed: ' + error.message, 'error');
        
        lastError = {
            action: 'start_payment_test',
            error: error.message,
            timestamp: new Date().toISOString()
        };
    } finally {
        button.classList.remove('btn-loading');
        button.disabled = false;
    }
}

// Check payment status
async function checkPaymentStatus() {
    if (!currentAccessToken || !currentReferenceId) {
        addLogEntry('❌ No active payment to check', 'error');
        return;
    }
    
    const button = document.getElementById('checkPaymentStatus');
    
    try {
        button.classList.add('btn-loading');
        button.disabled = true;
        
        addLogEntry('🔍 Payment status check...', 'info');
        
        const result = await makeApiCall('check_status', {
            access_token: currentAccessToken,
            reference_id: currentReferenceId
        });
        
        if (result.success) {
            const status = result.status;
            const statusColor = getStatusColor(status);
            
            addLogEntry(`📊 Payment Status: ${status}`, statusColor);
            
            if (result.data) {
                if (result.data.amount) {
                    addLogEntry(`💰 Amount: ${result.data.amount} ${result.data.currency}`, 'info');
                }
                if (result.data.financialTransactionId) {
                    addLogEntry(`🆔 Transaction ID: ${result.data.financialTransactionId}`, 'info');
                }
            }
            
            if (status === 'SUCCESSFUL') {
                showNotification('🎉 Test payment completed successfully!', 'success');
                addLogEntry('🎯 Test completed! Ready for production? Request access above.', 'warning');
            } else if (status === 'FAILED') {
                showNotification('❌ Test payment failed (as expected for this scenario)', 'error');
            } else if (status === 'PENDING') {
                showNotification('⏳ Test payment is still pending', 'warning');
                setTimeout(() => {
                    if (!document.getElementById('checkPaymentStatus').disabled) {
                        checkPaymentStatus();
                    }
                }, 5000);
            }
            
        } else {
            addLogEntry(`❌ Status check failed: ${result.message}`, 'error');
            throw new Error(result.error || 'Failed to check status');
        }
        
    } catch (error) {
        addLogEntry('❌ Failed to check status: ' + error.message, 'error');
        showNotification('❌ Failed to check status: ' + error.message, 'error');
    } finally {
        button.classList.remove('btn-loading');
        button.disabled = false;
    }
}

// Submit production request
async function submitProductionRequest() {
    const form = document.getElementById('productionRequestForm');
    const button = document.getElementById('submitProductionRequest');
    
    // Validate form
    if (!form.checkValidity()) {
        form.reportValidity();
        return;
    }
    
    const businessName = document.getElementById('businessName').value;
    const businessType = document.getElementById('businessType').value;
    const monthlyVolume = document.getElementById('monthlyVolume').value;
    const useCase = document.getElementById('useCase').value;
    const contactPhone = document.getElementById('contactPhone').value;
    
    try {
        button.classList.add('btn-loading');
        button.disabled = true;
        
        const result = await makeApiCall('request_production_access', {
            business_name: businessName,
            business_type: businessType,
            monthly_volume: monthlyVolume,
            use_case: useCase,
            contact_phone: contactPhone
        });
        
        if (result.success) {
            showNotification('🎉 Production request submitted successfully!', 'success');
            addLogEntry('📝 Production access request submitted', 'success');
            
            // Close modal and reset form
            const modal = bootstrap.Modal.getInstance(document.getElementById('productionRequestModal'));
            modal.hide();
            form.reset();
        } else {
            throw new Error(result.message || 'Failed to submit request');
        }
        
    } catch (error) {
        showNotification('❌ Failed to submit request: ' + error.message, 'error');
        addLogEntry('❌ Production request failed: ' + error.message, 'error');
    } finally {
        button.classList.remove('btn-loading');
        button.disabled = false;
    }
}

// Get status color for logging
function getStatusColor(status) {
    switch (status) {
        case 'SUCCESSFUL': return 'success';
        case 'FAILED': return 'error';
        case 'PENDING': return 'warning';
        default: return 'info';
    }
}

// Log entry with better formatting
function addLogEntry(message, type = 'info') {
    const logContainer = document.getElementById('apiLog');
    
    if (logContainer.querySelector('.text-muted.text-center')) {
        logContainer.innerHTML = '';
    }
    
    const timestamp = new Date().toLocaleTimeString();
    const logEntry = document.createElement('div');
    logEntry.className = `log-entry log-${type}`;
    
    const typeIcon = type === 'error' ? '❌' : type === 'warning' ? '⚠️' : type === 'success' ? '✅' : 'ℹ️';
    logEntry.innerHTML = `<span class="text-muted">[${timestamp}]</span> ${typeIcon} ${message}`;
    
    logContainer.insertBefore(logEntry, logContainer.firstChild);
    
    const entries = logContainer.querySelectorAll('.log-entry');
    if (entries.length > 100) {
        entries[entries.length - 1].remove();
    }
    
    logContainer.scrollTop = 0;
}

// Clear log
function clearLog() {
    const logContainer = document.getElementById('apiLog');
    logContainer.innerHTML = `
        <div class="text-muted text-center">
            <i class="fas fa-code fa-2x mb-2 d-block"></i>
            Enhanced debug mode ready! All API calls will show detailed information.
        </div>
    `;
    
    lastError = null;
    addLogEntry('🧹 Log cleared', 'info');
}

// Export log
function exportLog() {
    const logEntries = document.querySelectorAll('.log-entry');
    if (logEntries.length === 0) {
        showNotification('No log entries to export', 'warning');
        return;
    }
    
    const logText = Array.from(logEntries).reverse().map(entry => entry.textContent).join('\n');
    const debugHeader = `MTN MoMo Debug Log\nGenerated: ${new Date().toISOString()}\nEnhanced Mode: ${enhancedMode ? 'Active' : 'Inactive'}\n${'='.repeat(50)}\n\n`;
    
    const fullLog = debugHeader + logText;
    
    const blob = new Blob([fullLog], { type: 'text/plain' });
    const url = URL.createObjectURL(blob);
    
    const a = document.createElement('a');
    a.href = url;
    a.download = `mtn-momo-debug-log-${new Date().toISOString().slice(0, 10)}.txt`;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);
    
    addLogEntry('📁 Debug log exported successfully', 'info');
    showNotification('Debug log exported successfully', 'success');
}

// Copy to clipboard
function copyToClipboard(text) {
    navigator.clipboard.writeText(text).then(() => {
        showNotification('Copied to clipboard!', 'success');
        addLogEntry(`📋 Copied to clipboard: ${text.substring(0, 20)}...`, 'info');
    }).catch(() => {
        // Fallback for older browsers
        const textArea = document.createElement('textarea');
        textArea.value = text;
        document.body.appendChild(textArea);
        textArea.select();
        document.execCommand('copy');
        document.body.removeChild(textArea);
        showNotification('Copied to clipboard!', 'success');
    });
}

// Show notification using modern toast-style notifications
function showNotification(message, type = 'info') {
    // Create toast container if it doesn't exist
    let toastContainer = document.getElementById('toast-container');
    if (!toastContainer) {
        toastContainer = document.createElement('div');
        toastContainer.id = 'toast-container';
        toastContainer.style.cssText = `
            position: fixed;
            top: 20px;
            right: 20px;
            z-index: 9999;
            display: flex;
            flex-direction: column;
            gap: 10px;
            max-width: 400px;
        `;
        document.body.appendChild(toastContainer);
    }
    
    // Create toast
    const toast = document.createElement('div');
    const bgColor = type === 'error' ? 'hsl(var(--destructive))' : 
                   type === 'warning' ? 'hsl(45 93% 47%)' : 
                   type === 'success' ? 'hsl(142 71% 45%)' : 
                   'hsl(var(--primary))';
    
    toast.style.cssText = `
        background-color: ${bgColor};
        color: white;
        padding: 12px 16px;
        border-radius: calc(var(--radius));
        box-shadow: 0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1);
        font-size: 0.875rem;
        font-weight: 500;
        display: flex;
        align-items: center;
        justify-content: space-between;
        min-width: 300px;
        opacity: 0;
        transform: translateX(100%);
        transition: all 0.3s ease;
    `;
    
    const icon = type === 'error' ? '❌' : type === 'warning' ? '⚠️' : type === 'success' ? '✅' : 'ℹ️';
    
    toast.innerHTML = `
        <span>${icon} ${message}</span>
        <button style="
            background: none;
            border: none;
            color: white;
            cursor: pointer;
            font-size: 16px;
            padding: 0;
            margin-left: 12px;
            opacity: 0.7;
            transition: opacity 0.2s;
        " onclick="this.parentElement.remove()">×</button>
    `;
    
    // Add hover effect to close button
    const closeBtn = toast.querySelector('button');
    closeBtn.addEventListener('mouseenter', () => closeBtn.style.opacity = '1');
    closeBtn.addEventListener('mouseleave', () => closeBtn.style.opacity = '0.7');
    
    toastContainer.appendChild(toast);
    
    // Animate in
    requestAnimationFrame(() => {
        toast.style.opacity = '1';
        toast.style.transform = 'translateX(0)';
    });
    
    // Auto remove
    setTimeout(() => {
        toast.style.opacity = '0';
        toast.style.transform = 'translateX(100%)';
        setTimeout(() => {
            if (toast.parentNode) {
                toast.remove();
            }
        }, 300);
    }, type === 'error' ? 8000 : 5000);
}

// Initialize tooltips if Bootstrap is available
if (typeof bootstrap !== 'undefined') {
    document.addEventListener('DOMContentLoaded', function() {
        var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
        var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
            return new bootstrap.Tooltip(tooltipTriggerEl);
        });
    });
}
</script>

</body>
</html> '