<?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%')
    ");
    $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
$sandbox_config = [
    '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, created_at, updated_at
        FROM mtn_momo_credentials 
        WHERE user_id = ? AND environment = 'SANDBOX' AND status = 'ACTIVE'
        ORDER BY updated_at DESC LIMIT 1
    ");
    $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());
}

// MTN MoMo API Helper Class
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));
        }
        
        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' : 'API User already exists'
            ];
        }
        
        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'], '"\'');
                
                return [
                    'success' => true,
                    'api_key' => $api_key,
                    'status' => $result['status']
                ];
            }
            
            return [
                'success' => false,
                'status' => $result['status'],
                'error' => $result['raw']
            ];
        }
        
        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']
            ];
        }
        
        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'
            ];
            
            $data = json_encode([
                'amount' => (string)$amount,
                'currency' => $currency,
                'externalId' => 'order_' . time(),
                'payer' => [
                    'partyIdType' => 'MSISDN',
                    'partyId' => $phone
                ],
                'payerMessage' => 'ConnectPay Sandbox Test Payment',
                'payeeNote' => 'Thank you for testing'
            ]);
            
            $result = $this->makeApiCall($this->base_url . '/collection/v1_0/requesttopay', 'POST', $headers, $data);
            
            return [
                'success' => $result['status'] === 202,
                'reference_id' => $reference_id,
                'status' => $result['status']
            ];
        }
        
        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']
                ];
            }
            
            return [
                'success' => false,
                'status' => $result['status'],
                'error' => $result['raw']
            ];
        }
        
        private function makeApiCall($url, $method, $headers, $data = null) {
            $curl = curl_init();
            
            $options = [
                CURLOPT_URL => $url,
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_TIMEOUT => 30,
                CURLOPT_CUSTOMREQUEST => $method,
                CURLOPT_HTTPHEADER => $headers,
                CURLOPT_SSL_VERIFYPEER => false,
                CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1
            ];
            
            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);
            curl_close($curl);
            
            return [
                'status' => $httpCode,
                'data' => $response ? json_decode($response, true) : null,
                'raw' => $response
            ];
        }
    }
}

// Initialize API
$mtn_api = new MTNMoMoAPI($sandbox_config['subscription_key'], $sandbox_config['base_url'], $sandbox_config['environment']);

// Handle AJAX requests
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    header('Content-Type: application/json');
    
    $action = $_POST['action'];
    $response = ['success' => false, 'message' => 'Unknown action'];
    
    switch ($action) {
        case 'setup_credentials':
            $api_user = $mtn_api->generateApiUser();
            $callback_host = $_POST['callback_host'] ?? 'webhook.site';
            
            // Step 1: Create API User
            $createResult = $mtn_api->createApiUser($api_user, $callback_host);
            if (!$createResult['success']) {
                $response = ['success' => false, 'message' => 'Failed to create API User', 'step' => 'create_user'];
                break;
            }
            
            // Step 2: Generate API Key
            sleep(2); // Wait for MTN to process
            $keyResult = $mtn_api->generateApiKey($api_user);
            if (!$keyResult['success']) {
                $response = ['success' => false, 'message' => 'Failed to generate API Key', 'step' => 'generate_key'];
                break;
            }
            
            // Step 3: Save credentials
            try {
                $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 (?, ?, ?, ?, ?, ?, ?, 'ACTIVE', NOW(), NOW())
                    ON DUPLICATE KEY UPDATE 
                    api_user_id = VALUES(api_user_id),
                    api_key = VALUES(api_key),
                    updated_at = NOW()
                ");
                $credential_name = "Sandbox Test Credentials";
                $stmt->bind_param("issssss", 
                    $user_id, 
                    $credential_name,
                    $api_user, 
                    $keyResult['api_key'], 
                    $sandbox_config['subscription_key'], 
                    'SANDBOX',
                    $sandbox_config['base_url']
                );
                $stmt->execute();
                $stmt->close();
                
                $response = [
                    'success' => true,
                    'credentials' => [
                        'api_user' => $api_user,
                        'api_key' => $keyResult['api_key']
                    ],
                    'message' => 'Sandbox credentials generated successfully'
                ];
            } catch (Exception $e) {
                $response = ['success' => false, 'message' => 'Failed to save credentials'];
            }
            break;
            
        case 'get_token':
            if (!$stored_credentials) {
                $response = ['success' => false, 'message' => 'No credentials found', 'needs_setup' => true];
                break;
            }
            
            $tokenResult = $mtn_api->getAccessToken($stored_credentials['api_user_id'], $stored_credentials['api_key']);
            $response = $tokenResult;
            break;
            
        case 'request_payment':
            $access_token = $_POST['access_token'] ?? '';
            $amount = $_POST['amount'] ?? '100';
            $phone = $_POST['phone'] ?? $sandbox_config['test_phones']['success'];
            $currency = $_POST['currency'] ?? 'EUR';
            
            $paymentResult = $mtn_api->requestToPay($access_token, $amount, $currency, $phone);
            $response = $paymentResult;
            break;
            
        case 'check_status':
            $access_token = $_POST['access_token'] ?? '';
            $reference_id = $_POST['reference_id'] ?? '';
            
            $statusResult = $mtn_api->getTransactionStatus($access_token, $reference_id);
            $response = $statusResult;
            break;
    }
    
    echo json_encode($response);
    exit();
}
?>

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

<head>
    <?php 
    $title = "MTN MoMo Sandbox - Free Testing";
    if (file_exists('../partials/title-meta.php')) {
        try {
            include_once '../partials/title-meta.php';
        } catch (Exception $e) {
            echo "<title>MTN MoMo Sandbox - Free Testing - ConnectPay</title>\n";
        }
    } else {
        echo "<title>MTN MoMo Sandbox - Free Testing - 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>
        body {
            background-color: #f8f9fa;
        }
        
        .sandbox-header {
            background: linear-gradient(135deg, #28a745 0%, #20c997 100%);
            color: white;
            border-radius: 15px;
            padding: 2rem;
            margin-bottom: 2rem;
        }
        
        .upgrade-banner {
            background: linear-gradient(135deg, #6f42c1 0%, #e83e8c 100%);
            color: white;
            border-radius: 10px;
            padding: 1.5rem;
            margin-bottom: 2rem;
        }
        
        .test-card {
            border-radius: 15px;
            border: none;
            box-shadow: 0 4px 20px rgba(0,0,0,0.08);
            margin-bottom: 1.5rem;
            overflow: hidden;
            background: white;
            transition: all 0.3s ease;
        }
        
        .test-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 30px rgba(0,0,0,0.12);
        }
        
        .status-indicator {
            width: 10px;
            height: 10px;
            border-radius: 50%;
            display: inline-block;
            margin-right: 0.5rem;
            animation: pulse 2s infinite;
        }
        
        .status-ready { background-color: #28a745; }
        .status-pending { background-color: #ffc107; }
        .status-error { background-color: #dc3545; }
        
        .test-phone-card {
            border: 1px solid #e9ecef;
            border-radius: 8px;
            padding: 1rem;
            margin-bottom: 0.5rem;
            cursor: pointer;
            transition: all 0.3s ease;
        }
        
        .test-phone-card:hover {
            border-color: #007bff;
            background-color: #f8f9fa;
        }
        
        .test-phone-card.selected {
            border-color: #28a745;
            background-color: #d4edda;
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(40,167,69,0.3);
        }
        
        .api-log {
            background: #f8f9fa;
            border: 1px solid #dee2e6;
            border-radius: 8px;
            padding: 1rem;
            max-height: 400px;
            overflow-y: auto;
            font-family: monospace;
            font-size: 0.85rem;
        }
        
        .log-entry {
            margin-bottom: 0.5rem;
            padding: 0.25rem 0;
            border-bottom: 1px solid #e9ecef;
            transition: all 0.3s ease;
        }
        
        .log-entry:last-child {
            border-bottom: none;
        }
        
        .log-entry:hover {
            background-color: rgba(0,0,0,0.05);
            border-radius: 4px;
            padding: 0.25rem 0.5rem;
            margin: 0 -0.5rem;
        }
        
        .log-success { color: #28a745; }
        .log-error { color: #dc3545; }
        .log-info { color: #17a2b8; }
        .log-warning { color: #ffc107; }
        
        .sandbox-header {
            position: relative;
            overflow: hidden;
        }
        
        .sandbox-header::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 20"><path d="M0 20h100V0z" fill="rgba(255,255,255,0.1)"/></svg>');
            background-size: 20px 20px;
            opacity: 0.1;
        }
        
        @keyframes pulse {
            0% { opacity: 1; }
            50% { opacity: 0.5; }
            100% { opacity: 1; }
        }
        
        .btn[disabled] {
            position: relative;
            color: transparent !important;
        }
        
        .btn[disabled] i.fa-spinner {
            position: absolute;
            left: 50%;
            top: 50%;
            transform: translate(-50%, -50%);
            color: white;
        }
        
        .alert-enhanced {
            border: none;
            border-left: 4px solid;
        }
        
        .alert-info.alert-enhanced {
            border-left-color: #17a2b8;
            background: linear-gradient(135deg, #d1ecf1 0%, #bee5eb 100%);
        }
        
        .alert-success.alert-enhanced {
            border-left-color: #28a745;
            background: linear-gradient(135deg, #d4edda 0%, #c3e6cb 100%);
        }
        
        .free-badge {
            background: linear-gradient(135deg, #28a745 0%, #20c997 100%);
            color: white;
            padding: 0.25rem 0.75rem;
            border-radius: 50px;
            font-size: 0.75rem;
            font-weight: 600;
        }
    </style>
</head>

<body>

<div id="wrapper">
    <?php 
    $pagetitle = "MTN MoMo Sandbox - Free Testing"; 
    if (file_exists('../partials/menu.php')) {
        try {
            include_once '../partials/menu.php';
        } catch (Exception $e) {
            echo '<nav class="navbar navbar-expand-lg navbar-dark bg-primary">
                    <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-dark bg-primary">
                <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="page-title-box mb-4">
                            <h4 class="page-title">
                                <i class="fas fa-mobile-alt me-2"></i>
                                MTN MoMo Sandbox
                                <span class="free-badge ms-2">FREE TESTING</span>
                            </h4>
                            <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>
                </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="mb-0">
                                🎉 <strong>FREE for everyone!</strong> Test MTN Mobile Money integration safely. Real API endpoints, no real money, no license required.
                            </p>
                        </div>
                        <div class="col-md-4 text-md-end">
                            <span class="badge bg-success text-white fs-6 mb-2">
                                <i class="fas fa-gift me-1"></i>
                                FREE TESTING
                            </span>
                            <div class="mt-2">
                                <small>User: <strong><?php echo htmlspecialchars($user_name); ?></strong></small>
                            </div>
                        </div>
                    </div>
                </div>

                <?php if (!$has_production_license): ?>
                <!-- Upgrade Banner -->
                <div class="upgrade-banner">
                    <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="mb-0">
                                Upgrade to a production license for live transactions, advanced features, and priority support.
                            </p>
                        </div>
                        <div class="col-md-4 text-md-end">
                            <a href="../browse-plugins.php" class="btn btn-light btn-lg">
                                <i class="fas fa-arrow-up me-2"></i>
                                Upgrade Now
                            </a>
                        </div>
                    </div>
                </div>
                <?php endif; ?>

                <!-- Main Content -->
                <div class="row">
                    <!-- Credentials Setup -->
                    <div class="col-lg-6">
                        <div class="test-card">
                            <div class="card-body">
                                <h5 class="card-title">
                                    <i class="fas fa-key me-2 text-primary"></i>
                                    Sandbox Credentials
                                    <span class="badge bg-success ms-2">FREE</span>
                                    <?php if ($stored_credentials): ?>
                                    <span class="status-indicator status-ready"></span>
                                    <span class="badge bg-success">Ready</span>
                                    <?php else: ?>
                                    <span class="status-indicator status-pending"></span>
                                    <span class="badge bg-warning">Setup Required</span>
                                    <?php endif; ?>
                                </h5>
                                
                                <?php if (!$stored_credentials): ?>
                                <div class="alert alert-success alert-enhanced">
                                    <i class="fas fa-gift me-2"></i>
                                    <strong>Free sandbox testing!</strong> Generate your MTN MoMo sandbox credentials at no cost. Perfect for development and testing.
                                </div>
                                
                                <div class="mb-3">
                                    <label class="form-label">Callback Host</label>
                                    <input type="text" class="form-control" id="callbackHost" 
                                           value="webhook.site" placeholder="webhook.site">
                                    <small class="form-text text-muted">
                                        Used for webhook notifications (testing only)
                                    </small>
                                </div>
                                
                                <button class="btn btn-success" id="generateCredentials">
                                    <i class="fas fa-cog me-2"></i>
                                    Generate Free Credentials
                                </button>
                                <?php else: ?>
                                <div class="alert alert-success alert-enhanced">
                                    <i class="fas fa-check-circle me-2"></i>
                                    Your free sandbox credentials are ready for testing!
                                </div>
                                
                                <div class="mb-3">
                                    <label class="form-label">API User</label>
                                    <input type="text" class="form-control" value="<?php echo substr($stored_credentials['api_user_id'], 0, 20); ?>..." readonly>
                                </div>
                                
                                <div class="mb-3">
                                    <label class="form-label">Created</label>
                                    <input type="text" class="form-control" value="<?php echo date('M j, Y g:i A', strtotime($stored_credentials['created_at'])); ?>" readonly>
                                </div>
                                
                                <button class="btn btn-outline-success" id="regenerateCredentials">
                                    <i class="fas fa-refresh me-2"></i>
                                    Regenerate
                                </button>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>

                    <!-- 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 text-success"></i>
                                    Test Phone Numbers
                                    <span class="badge bg-info 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 bg-<?php echo $scenario === 'success' ? 'success' : ($scenario === 'insufficient' ? 'warning' : 'danger'); ?> 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>
                </div>

                <!-- Payment Testing -->
                <!-- Payment Testing -->
               <div class="row">
                   <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 text-warning"></i>
                                   Payment Testing
                                   <span class="badge bg-warning text-dark ms-2">SANDBOX</span>
                               </h5>
                               
                               <div class="alert alert-info alert-enhanced mb-3">
                                   <i class="fas fa-info-circle me-2"></i>
                                   <strong>Safe Testing:</strong> All transactions are simulated. No real money involved!
                               </div>
                               
                               <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-select" 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-success" id="startPaymentTest" <?php echo !$stored_credentials ? 'disabled' : ''; ?>>
                                       <i class="fas fa-play me-2"></i>
                                       Start Free Test Payment
                                   </button>
                                   <button class="btn btn-outline-info" id="checkPaymentStatus" disabled>
                                       <i class="fas fa-search me-2"></i>
                                       Check Status
                                   </button>
                               </div>
                               
                               <?php if (!$has_production_license): ?>
                               <div class="mt-3 p-3 bg-light rounded">
                                   <small class="text-muted">
                                       <i class="fas fa-lightbulb me-1"></i>
                                       <strong>Need real transactions?</strong> 
                                       <a href="../browse-plugins.php" class="text-decoration-none">Upgrade to a production license</a> 
                                       for live MTN MoMo integration.
                                   </small>
                               </div>
                               <?php endif; ?>
                           </div>
                       </div>
                   </div>
                   
                   <div class="col-lg-6">
                       <div class="test-card">
                           <div class="card-body">
                               <h5 class="card-title">
                                   <i class="fas fa-terminal me-2 text-info"></i>
                                   API Activity Log
                                   <span class="badge bg-secondary ms-2">REAL-TIME</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>
                                       Ready for free testing! Start a payment test to see real API activity.
                                   </div>
                               </div>
                               
                               <div class="mt-3">
                                   <button class="btn btn-sm btn-outline-secondary" onclick="clearLog()">
                                       <i class="fas fa-trash me-1"></i>
                                       Clear Log
                                   </button>
                                   <button class="btn btn-sm btn-outline-info" onclick="showSampleCode()">
                                       <i class="fas fa-code me-1"></i>
                                       View Sample Code
                                   </button>
                               </div>
                           </div>
                       </div>
                   </div>
               </div>

               <!-- Features Comparison -->
               <div class="row">
                   <div class="col-12">
                       <div class="test-card">
                           <div class="card-body">
                               <h5 class="card-title">
                                   <i class="fas fa-balance-scale me-2 text-primary"></i>
                                   Sandbox vs Production Features
                               </h5>
                               
                               <div class="row">
                                   <div class="col-md-6">
                                       <h6 class="text-success">
                                           <i class="fas fa-check-circle me-2"></i>
                                           Sandbox Features (FREE)
                                       </h6>
                                       <ul class="list-unstyled">
                                           <li><i class="fas fa-check text-success me-2"></i> Test all API endpoints</li>
                                           <li><i class="fas fa-check text-success me-2"></i> Simulate payment scenarios</li>
                                           <li><i class="fas fa-check text-success me-2"></i> Real API responses</li>
                                           <li><i class="fas fa-check text-success me-2"></i> Development testing</li>
                                           <li><i class="fas fa-check text-success me-2"></i> Code samples & documentation</li>
                                           <li><i class="fas fa-check text-success me-2"></i> No time limits</li>
                                       </ul>
                                   </div>
                                   <div class="col-md-6">
                                       <h6 class="text-primary">
                                           <i class="fas fa-rocket me-2"></i>
                                           Production Features (License Required)
                                       </h6>
                                       <ul class="list-unstyled">
                                           <li><i class="fas fa-star text-warning me-2"></i> Real money transactions</li>
                                           <li><i class="fas fa-star text-warning me-2"></i> Live MTN MoMo integration</li>
                                           <li><i class="fas fa-star text-warning me-2"></i> Customer payment processing</li>
                                           <li><i class="fas fa-star text-warning me-2"></i> Webhook notifications</li>
                                           <li><i class="fas fa-star text-warning me-2"></i> Priority support</li>
                                           <li><i class="fas fa-star text-warning me-2"></i> White-label solutions</li>
                                       </ul>
                                       <?php if (!$has_production_license): ?>
                                       <a href="../browse-plugins.php" class="btn btn-primary">
                                           <i class="fas fa-arrow-up me-2"></i>
                                           Upgrade to Production
                                       </a>
                                       <?php endif; ?>
                                   </div>
                               </div>
                           </div>
                       </div>
                   </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"><p>&copy; 2024 ConnectPay Platform</p></footer>';
           }
       } else {
           echo '<footer class="bg-light text-center py-3 mt-5"><p>&copy; 2024 ConnectPay Platform</p></footer>';
       }
       ?>

   </div>
</div>

<?php 
if (file_exists('../partials/right-sidebar.php')) {
   try {
       include_once '../partials/right-sidebar.php';
   } catch (Exception $e) {
       // Silent fallback
   }
}
?>

<?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";
}
?>

<!-- Sample Code Modal -->
<div class="modal fade" id="sampleCodeModal" tabindex="-1" aria-hidden="true">
   <div class="modal-dialog modal-lg">
       <div class="modal-content">
           <div class="modal-header">
               <h5 class="modal-title">
                   <i class="fas fa-code me-2"></i>
                   Sample Integration Code
               </h5>
               <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
           </div>
           <div class="modal-body">
               <div class="alert alert-info">
                   <i class="fas fa-info-circle me-2"></i>
                   Here's how you can integrate MTN MoMo into your application:
               </div>
               
               <ul class="nav nav-tabs" role="tablist">
                   <li class="nav-item">
                       <a class="nav-link active" data-bs-toggle="tab" href="#php-code">PHP</a>
                   </li>
                   <li class="nav-item">
                       <a class="nav-link" data-bs-toggle="tab" href="#javascript-code">JavaScript</a>
                   </li>
                   <li class="nav-item">
                       <a class="nav-link" data-bs-toggle="tab" href="#curl-code">cURL</a>
                   </li>
               </ul>
               
               <div class="tab-content mt-3">
                   <div class="tab-pane active" id="php-code">
                       <pre><code class="language-php">&lt;?php
// MTN MoMo API Integration Example
$api_user = 'your-api-user-id';
$api_key = 'your-api-key';
$subscription_key = 'your-subscription-key';

// Step 1: Get Access Token
$auth = base64_encode($api_user . ':' . $api_key);
$token_url = 'https://sandbox.momodeveloper.mtn.com/collection/token/';

$ch = curl_init($token_url);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
   'Authorization: Basic ' . $auth,
   'Ocp-Apim-Subscription-Key: ' . $subscription_key
]);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$token_response = curl_exec($ch);
$token_data = json_decode($token_response, true);
$access_token = $token_data['access_token'];

// Step 2: Request Payment
$reference_id = uniqid();
$payment_url = 'https://sandbox.momodeveloper.mtn.com/collection/v1_0/requesttopay';

$payment_data = [
   'amount' => '100',
   'currency' => 'EUR',
   'externalId' => 'order_123',
   'payer' => [
       'partyIdType' => 'MSISDN',
       'partyId' => '46733123450'
   ],
   'payerMessage' => 'Payment for order #123',
   'payeeNote' => 'Thank you for your purchase'
];

curl_setopt($ch, CURLOPT_URL, $payment_url);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
   'Authorization: Bearer ' . $access_token,
   'X-Reference-Id: ' . $reference_id,
   'X-Target-Environment: sandbox',
   'Ocp-Apim-Subscription-Key: ' . $subscription_key,
   'Content-Type: application/json'
]);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payment_data));

$payment_response = curl_exec($ch);
curl_close($ch);

echo "Payment initiated with reference: " . $reference_id;
?&gt;</code></pre>
                   </div>
                   
                   <div class="tab-pane" id="javascript-code">
                       <pre><code class="language-javascript">// MTN MoMo API Integration with JavaScript
async function initiateMoMoPayment(amount, phone) {
   try {
       // Step 1: Get access token
       const tokenResponse = await fetch('/api/momo/token', {
           method: 'POST',
           headers: {
               'Content-Type': 'application/json'
           }
       });
       
       const { access_token } = await tokenResponse.json();
       
       // Step 2: Request payment
       const paymentData = {
           amount: amount.toString(),
           currency: 'EUR',
           externalId: 'order_' + Date.now(),
           payer: {
               partyIdType: 'MSISDN',
               partyId: phone
           },
           payerMessage: 'Payment request',
           payeeNote: 'Thank you'
       };
       
       const paymentResponse = await fetch('/api/momo/payment', {
           method: 'POST',
           headers: {
               'Content-Type': 'application/json',
               'Authorization': 'Bearer ' + access_token
           },
           body: JSON.stringify(paymentData)
       });
       
       const result = await paymentResponse.json();
       console.log('Payment initiated:', result);
       
       return result;
   } catch (error) {
       console.error('Payment failed:', error);
       throw error;
   }
}

// Usage
initiateMoMoPayment(100, '46733123450')
   .then(result => console.log('Success:', result))
   .catch(error => console.error('Error:', error));</code></pre>
                   </div>
                   
                   <div class="tab-pane" id="curl-code">
                       <pre><code class="language-bash"># MTN MoMo API Integration with cURL

# Step 1: Get Access Token
curl -X POST \
 https://sandbox.momodeveloper.mtn.com/collection/token/ \
 -H "Authorization: Basic $(echo -n 'api_user:api_key' | base64)" \
 -H "Ocp-Apim-Subscription-Key: your-subscription-key"

# Step 2: Request Payment
curl -X POST \
 https://sandbox.momodeveloper.mtn.com/collection/v1_0/requesttopay \
 -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
 -H "X-Reference-Id: $(uuidgen)" \
 -H "X-Target-Environment: sandbox" \
 -H "Ocp-Apim-Subscription-Key: your-subscription-key" \
 -H "Content-Type: application/json" \
 -d '{
   "amount": "100",
   "currency": "EUR",
   "externalId": "order_123",
   "payer": {
     "partyIdType": "MSISDN",
     "partyId": "46733123450"
   },
   "payerMessage": "Payment for order",
   "payeeNote": "Thank you"
 }'

# Step 3: Check Payment Status
curl -X GET \
 https://sandbox.momodeveloper.mtn.com/collection/v1_0/requesttopay/REFERENCE_ID \
 -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
 -H "X-Target-Environment: sandbox" \
 -H "Ocp-Apim-Subscription-Key: your-subscription-key"</code></pre>
                   </div>
               </div>
           </div>
           <div class="modal-footer">
               <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
               <a href="../browse-plugins.php" class="btn btn-primary">Get Production License</a>
           </div>
       </div>
   </div>
</div>

<!-- MTN MoMo Sandbox JavaScript -->
<script>
document.addEventListener('DOMContentLoaded', function() {
   console.log('🚀 MTN MoMo Sandbox (FREE) initialized');
   initializeEventHandlers();
   initializeTestPhones();
   
   <?php if ($stored_credentials): ?>
   addLogEntry('🎉 Free sandbox credentials ready for testing!', 'success');
   <?php else: ?>
   addLogEntry('👋 Welcome! Generate free credentials to start testing', 'info');
   <?php endif; ?>
});

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

// Initialize event handlers
function initializeEventHandlers() {
   const generateBtn = document.getElementById('generateCredentials');
   if (generateBtn) {
       generateBtn.addEventListener('click', generateCredentials);
   }
   
   const regenerateBtn = document.getElementById('regenerateCredentials');
   if (regenerateBtn) {
       regenerateBtn.addEventListener('click', regenerateCredentials);
   }
   
   const startTestBtn = document.getElementById('startPaymentTest');
   if (startTestBtn) {
       startTestBtn.addEventListener('click', startPaymentTest);
   }
   
   const checkStatusBtn = document.getElementById('checkPaymentStatus');
   if (checkStatusBtn) {
       checkStatusBtn.addEventListener('click', checkPaymentStatus);
   }
}

// 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');
       });
   });
}

// Generate new credentials
async function generateCredentials() {
   const button = document.getElementById('generateCredentials');
   const originalText = button.innerHTML;
   
   try {
       button.innerHTML = '<i class="fas fa-spinner fa-spin me-2"></i>Generating...';
       button.disabled = true;
       
       addLogEntry('🔄 Generating free sandbox credentials...', 'info');
       
       const formData = new FormData();
       formData.append('action', 'setup_credentials');
       formData.append('callback_host', document.getElementById('callbackHost').value);
       
       const response = await fetch(window.location.href, {
           method: 'POST',
           body: formData
       });
       
       const result = await response.json();
       
       if (result.success) {
           addLogEntry('✅ Free credentials generated successfully!', 'success');
           addLogEntry(`🔑 API User: ${result.credentials.api_user.substring(0, 20)}...`, 'info');
           
           showNotification('🎉 Free sandbox 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.innerHTML = originalText;
       button.disabled = false;
   }
}

// Regenerate credentials
async function regenerateCredentials() {
   if (!confirm('Are you sure you want to regenerate your free credentials? This will invalidate the current ones.')) {
       return;
   }
   
   await generateCredentials();
}

// Start payment test
async function startPaymentTest() {
   const button = document.getElementById('startPaymentTest');
   const originalText = button.innerHTML;
   
   try {
       button.innerHTML = '<i class="fas fa-spinner fa-spin me-2"></i>Processing...';
       button.disabled = true;
       
       addLogEntry('🚀 Starting free payment test...', 'info');
       addLogEntry('💡 This is a sandbox test - no real money involved!', 'warning');
       
       // Step 1: Get access token
       addLogEntry('1️⃣ Getting access token...', 'info');
       const tokenResult = await getAccessToken();
       
       if (!tokenResult.success) {
           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;
       
       const paymentResult = await requestPayment(currentAccessToken, amount, currency, selectedPhoneNumber);
       
       if (!paymentResult.success) {
           throw new Error('Failed to request payment: ' + paymentResult.message);
       }
       
       currentReferenceId = paymentResult.reference_id;
       addLogEntry(`✅ Test payment requested successfully`, 'success');
       addLogEntry(`🆔 Reference ID: ${currentReferenceId}`, 'info');
       addLogEntry(`💰 Amount: ${amount} ${currency} (SANDBOX)`, 'info');
       addLogEntry(`📱 Phone: ${selectedPhoneNumber}`, 'info');
       
       document.getElementById('checkPaymentStatus').disabled = false;
       
       setTimeout(() => {
           checkPaymentStatus();
       }, 3000);
       
       showNotification('🎉 Free test payment started! Checking status...', 'success');
       
   } catch (error) {
       addLogEntry('❌ Test payment failed: ' + error.message, 'error');
       showNotification('❌ Test payment failed: ' + error.message, 'error');
   } finally {
       button.innerHTML = originalText;
       button.disabled = false;
   }
}

// Get access token
async function getAccessToken() {
   const formData = new FormData();
   formData.append('action', 'get_token');
   
   const response = await fetch(window.location.href, {
       method: 'POST',
       body: formData
   });
   
   return await response.json();
}

// Request payment
async function requestPayment(accessToken, amount, currency, phone) {
   const formData = new FormData();
   formData.append('action', 'request_payment');
   formData.append('access_token', accessToken);
   formData.append('amount', amount);
   formData.append('currency', currency);
   formData.append('phone', phone);
   
   const response = await fetch(window.location.href, {
       method: 'POST',
       body: formData
   });
   
   return await response.json();
}

// Check payment status
async function checkPaymentStatus() {
   if (!currentAccessToken || !currentReferenceId) {
       addLogEntry('❌ No active payment to check', 'error');
       return;
   }
   
   const button = document.getElementById('checkPaymentStatus');
   const originalText = button.innerHTML;
   
   try {
       button.innerHTML = '<i class="fas fa-spinner fa-spin me-2"></i>Checking...';
       button.disabled = true;
       
       addLogEntry('🔍 Checking test payment status...', 'info');
       
       const formData = new FormData();
       formData.append('action', 'check_status');
       formData.append('access_token', currentAccessToken);
       formData.append('reference_id', currentReferenceId);
       
       const response = await fetch(window.location.href, {
           method: 'POST',
           body: formData
       });
       
       const result = await response.json();
       
       if (result.success) {
           const status = result.status;
           const statusColor = getStatusColor(status);
           
           addLogEntry(`📊 Test Payment Status: ${status}`, statusColor);
           
           if (result.data) {
               if (result.data.amount) {
                   addLogEntry(`💰 Amount: ${result.data.amount} ${result.data.currency} (SANDBOX)`, '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? Consider upgrading.', '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 === false) {
                       checkPaymentStatus();
                   }
               }, 5000);
           }
           
       } else {
           throw new Error(result.error || 'Failed to check status');
       }
       
   } catch (error) {
       addLogEntry('❌ Failed to check test status: ' + error.message, 'error');
       showNotification('❌ Failed to check test status: ' + error.message, 'error');
   } finally {
       button.innerHTML = originalText;
       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';
   }
}

// Add entry to API log
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}`;
   logEntry.innerHTML = `<span class="text-muted">[${timestamp}]</span> ${message}`;
   
   logContainer.insertBefore(logEntry, logContainer.firstChild);
   
   const entries = logContainer.querySelectorAll('.log-entry');
   if (entries.length > 50) {
       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>
           Ready for free testing! Start a payment test to see real API activity.
       </div>
   `;
}

// Show sample code modal
function showSampleCode() {
   const modal = new bootstrap.Modal(document.getElementById('sampleCodeModal'));
   modal.show();
}

// Show notification
function showNotification(message, type = 'info') {
   const notification = document.createElement('div');
   notification.className = `alert alert-${type === 'error' ? 'danger' : type} alert-dismissible fade show position-fixed`;
   notification.style.cssText = 'top: 20px; right: 20px; z-index: 9999; min-width: 300px; max-width: 500px;';
   notification.innerHTML = `
       ${message}
       <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
   `;
   
   document.body.appendChild(notification);
   
   setTimeout(() => {
       if (notification.parentNode) {
           notification.remove();
       }
   }, 5000);
}

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

</body>
</html>