<?php
// Include required classes
require_once 'app/classes/ApiKeyManager.php';
require_once 'app/classes/CustomPricingManager.php';

// Initialize API key manager
$apiKeyManager = new ApiKeyManager($conn);

// Handle form submissions
$message = '';
$message_type = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['action'])) {
        switch ($_POST['action']) {
            case 'generate_key':
                $name = trim($_POST['key_name']);
                $description = trim($_POST['key_description']);
                $rateLimit = intval($_POST['rate_limit']);
                
                if (empty($name)) {
                    $message = 'Key name is required';
                    $message_type = 'error';
                } else {
                    $result = $apiKeyManager->generateApiKey($user_id, $name, $description, null, $rateLimit);
                    if ($result['success']) {
                        $message = 'API key generated successfully! Please save your API secret now - it will not be shown again.';
                        $message_type = 'success';
                        $new_api_key = $result['api_key'];
                        $new_api_secret = $result['api_secret'];
                    } else {
                        $message = $result['message'];
                        $message_type = 'error';
                    }
                }
                break;
                
            case 'delete_key':
                $key_id = intval($_POST['key_id']);
                if ($apiKeyManager->deleteApiKey($key_id, $user_id)) {
                    $message = 'API key deleted successfully';
                    $message_type = 'success';
                } else {
                    $message = 'Failed to delete API key';
                    $message_type = 'error';
                }
                break;
                
            case 'toggle_key':
                $key_id = intval($_POST['key_id']);
                $is_active = intval($_POST['is_active']);
                if ($apiKeyManager->updateApiKey($key_id, '', '', null, 0, $is_active, null)) {
                    $message = 'API key status updated successfully';
                    $message_type = 'success';
                } else {
                    $message = 'Failed to update API key status';
                    $message_type = 'error';
                }
                break;
        }
    }
}

// Get user's API keys
$api_keys = $apiKeyManager->getUserApiKeys($user_id);

// Get API usage statistics
$usage_stats = $apiKeyManager->getApiUsageStats($user_id, 30);

// Get dynamic pricing data for documentation
function getPricingForDocumentation($conn) {
    $pricingManager = new CustomPricingManager($conn);
    
    // Organize pricing by role and network
    $pricingData = [
        'agent' => [],
        'super_agent' => []
    ];
    
    // Common package sizes to display
    $commonPackages = ['500MB', '1GB', '2GB', '4GB', '10GB'];
    
    foreach ($commonPackages as $package) {
        // Get agent pricing (try 'all' networks first, then specific networks)
        $agentPricing = $pricingManager->calculatePrice($package, 'all', 'agent');
        if ($agentPricing['price'] !== null) {
            $pricingData['agent'][$package] = $agentPricing['price'];
        } else {
            // Try specific networks if no general pricing found
            $networks = ['mtn', 'telecel', 'airtel_tigo'];
            foreach ($networks as $network) {
                $networkPricing = $pricingManager->calculatePrice($package, $network, 'agent');
                if ($networkPricing['price'] !== null) {
                    $pricingData['agent'][$package] = $networkPricing['price'];
                    break; // Use first found pricing
                }
            }
        }
        
        // Get super agent pricing (try 'all' networks first, then specific networks)
        $superAgentPricing = $pricingManager->calculatePrice($package, 'all', 'super_agent');
        if ($superAgentPricing['price'] !== null) {
            $pricingData['super_agent'][$package] = $superAgentPricing['price'];
        } else {
            // Try specific networks if no general pricing found
            $networks = ['mtn', 'telecel', 'airtel_tigo'];
            foreach ($networks as $network) {
                $networkPricing = $pricingManager->calculatePrice($package, $network, 'super_agent');
                if ($networkPricing['price'] !== null) {
                    $pricingData['super_agent'][$package] = $networkPricing['price'];
                    break; // Use first found pricing
                }
            }
        }
    }
    
    return $pricingData;
}

$pricingData = getPricingForDocumentation($conn);
?>

<!-- API Keys Management Section -->
<div class="bg-white rounded-2xl p-6 mb-6 shadow-lg border border-gray-200/50">
    <div class="flex items-center justify-between mb-6">
        <h2 class="text-xl font-bold text-gray-900">
            <i class="fas fa-key mr-2"></i>API Keys Management
        </h2>
        <button onclick="toggleGenerateForm()" class="bg-blue-500 text-white px-4 py-2 rounded-lg text-sm font-medium hover:bg-blue-600 transition-colors">
            <i class="fas fa-plus mr-2"></i>Generate New Key
        </button>
    </div>

    <!-- Success/Error Messages -->
    <?php if ($message): ?>
    <div class="mb-6 p-4 rounded-lg <?php echo $message_type === 'success' ? 'bg-green-50 border border-green-200 text-green-800' : 'bg-red-50 border border-red-200 text-red-800'; ?>">
        <div class="flex items-center">
            <i class="fas <?php echo $message_type === 'success' ? 'fa-check-circle' : 'fa-exclamation-circle'; ?> mr-2"></i>
            <span><?php echo htmlspecialchars($message); ?></span>
        </div>
    </div>
    <?php endif; ?>

    <!-- New API Key Display (if just generated) -->
    <?php if (isset($new_api_key) && isset($new_api_secret)): ?>
    <div class="mb-6 p-6 bg-gradient-to-r from-green-50 to-blue-50 border border-green-200 rounded-xl">
        <div class="flex items-center mb-4">
            <i class="fas fa-exclamation-triangle text-yellow-600 mr-2"></i>
            <h3 class="text-lg font-semibold text-gray-900">Important: Save Your API Credentials</h3>
        </div>
        <p class="text-sm text-gray-600 mb-4">Please copy and save these credentials now. The secret will not be shown again.</p>
        
        <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">API Key</label>
                <div class="flex">
                    <input type="text" value="<?php echo htmlspecialchars($new_api_key); ?>" 
                           class="flex-1 border border-gray-300 rounded-l-lg px-3 py-2 bg-gray-50 text-sm font-mono" 
                           readonly>
                    <button onclick="copyToClipboard('<?php echo htmlspecialchars($new_api_key); ?>')" 
                            class="px-3 py-2 bg-gray-200 border border-l-0 border-gray-300 rounded-r-lg hover:bg-gray-300 transition-colors">
                        <i class="fas fa-copy"></i>
                    </button>
                </div>
            </div>
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">API Secret</label>
                <div class="flex">
                    <input type="text" value="<?php echo htmlspecialchars($new_api_secret); ?>" 
                           class="flex-1 border border-gray-300 rounded-l-lg px-3 py-2 bg-gray-50 text-sm font-mono" 
                           readonly>
                    <button onclick="copyToClipboard('<?php echo htmlspecialchars($new_api_secret); ?>')" 
                            class="px-3 py-2 bg-gray-200 border border-l-0 border-gray-300 rounded-r-lg hover:bg-gray-300 transition-colors">
                        <i class="fas fa-copy"></i>
                    </button>
                </div>
            </div>
        </div>
    </div>
    <?php endif; ?>

    <!-- Generate New Key Form -->
    <div id="generateForm" class="hidden mb-6 p-6 bg-gray-50 rounded-xl border border-gray-200">
        <h3 class="text-lg font-semibold text-gray-900 mb-4">
            <i class="fas fa-plus-circle mr-2"></i>Generate New API Key
        </h3>
        <form method="POST" class="space-y-4" id="generateKeyForm">
            <input type="hidden" name="action" value="generate_key">
            
            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                    <label for="key_name" class="block text-sm font-medium text-gray-700 mb-2">Key Name *</label>
                    <input type="text" id="key_name" name="key_name" 
                           class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500 focus:border-transparent" 
                           placeholder="e.g., My App Integration" required>
                </div>
                <div>
                    <label for="rate_limit" class="block text-sm font-medium text-gray-700 mb-2">Rate Limit (requests/hour)</label>
                    <input type="number" id="rate_limit" name="rate_limit" 
                           class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500 focus:border-transparent" 
                           value="1000" min="1" max="10000">
                </div>
            </div>
            
            <div>
                <label for="key_description" class="block text-sm font-medium text-gray-700 mb-2">Description</label>
                <textarea id="key_description" name="key_description" rows="3"
                          class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                          placeholder="Describe what this API key will be used for..."></textarea>
            </div>
            
            <div class="flex space-x-3">
                <button type="submit" class="bg-blue-500 text-white px-6 py-2 rounded-lg font-medium hover:bg-blue-600 transition-colors">
                    <i class="fas fa-key mr-2"></i>Generate API Key
                </button>
                <button type="button" onclick="toggleGenerateForm()" class="bg-gray-500 text-white px-6 py-2 rounded-lg font-medium hover:bg-gray-600 transition-colors">
                    Cancel
                </button>
            </div>
        </form>
    </div>

    <!-- API Keys List -->
    <div class="space-y-4">
        <h3 class="text-lg font-semibold text-gray-900">
            <i class="fas fa-list mr-2"></i>Your API Keys
        </h3>
        
        <?php if (empty($api_keys)): ?>
        <div class="text-center py-8 text-gray-500">
            <i class="fas fa-key text-4xl mb-4"></i>
            <p class="text-lg">No API keys found</p>
            <p class="text-sm">Generate your first API key to start integrating with D-Bundles Stores</p>
        </div>
        <?php else: ?>
            <?php foreach ($api_keys as $key): ?>
            <div class="bg-white border border-gray-200 rounded-lg p-4">
                <div class="flex items-center justify-between">
                    <div class="flex-1">
                        <div class="flex items-center space-x-3 mb-2">
                            <h4 class="text-lg font-semibold text-gray-900"><?php echo htmlspecialchars($key['name']); ?></h4>
                            <span class="px-2 py-1 text-xs font-medium rounded-full <?php echo $key['is_active'] ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'; ?>">
                                <?php echo $key['is_active'] ? 'Active' : 'Inactive'; ?>
                            </span>
                        </div>
                        
                        <?php if ($key['description']): ?>
                        <p class="text-sm text-gray-600 mb-2"><?php echo htmlspecialchars($key['description']); ?></p>
                        <?php endif; ?>
                        
                        <div class="flex items-center space-x-4 text-sm text-gray-500">
                            <span><i class="fas fa-key mr-1"></i><?php echo htmlspecialchars($key['api_key']); ?></span>
                            <span><i class="fas fa-clock mr-1"></i>Created <?php echo date('M j, Y', strtotime($key['created_at'])); ?></span>
                            <?php if ($key['rate_limit']): ?>
                            <span><i class="fas fa-tachometer-alt mr-1"></i><?php echo number_format($key['rate_limit']); ?> req/hour</span>
                            <?php endif; ?>
                        </div>
                    </div>
                    
                    <div class="flex items-center space-x-2">
                        <form method="POST" class="inline">
                            <input type="hidden" name="action" value="toggle_key">
                            <input type="hidden" name="key_id" value="<?php echo $key['id']; ?>">
                            <input type="hidden" name="is_active" value="<?php echo $key['is_active'] ? '0' : '1'; ?>">
                            <button type="submit" class="px-3 py-1 text-xs font-medium rounded <?php echo $key['is_active'] ? 'bg-red-100 text-red-700 hover:bg-red-200' : 'bg-green-100 text-green-700 hover:bg-green-200'; ?> transition-colors">
                                <?php echo $key['is_active'] ? 'Deactivate' : 'Activate'; ?>
                            </button>
                        </form>
                        
                        <form method="POST" class="inline" onsubmit="return confirm('Are you sure you want to delete this API key? This action cannot be undone.');">
                            <input type="hidden" name="action" value="delete_key">
                            <input type="hidden" name="key_id" value="<?php echo $key['id']; ?>">
                            <button type="submit" class="px-3 py-1 text-xs font-medium rounded bg-red-100 text-red-700 hover:bg-red-200 transition-colors">
                                <i class="fas fa-trash mr-1"></i>Delete
                            </button>
                        </form>
                    </div>
                </div>
            </div>
            <?php endforeach; ?>
        <?php endif; ?>
    </div>
</div>

<!-- Comprehensive API Documentation -->
<div class="bg-white rounded-2xl p-6 shadow-lg border border-gray-200/50">
    <div class="flex items-center justify-between mb-6">
        <h3 class="text-lg font-bold text-gray-900">
            <i class="fas fa-book mr-2"></i>API Documentation
        </h3>
        <button onclick="toggleDocumentation()" class="bg-blue-500 text-white px-4 py-2 rounded-lg text-sm font-medium hover:bg-blue-600 transition-colors">
            <i class="fas fa-eye mr-2"></i>View Full Documentation
        </button>
    </div>
    
    <!-- Quick Reference -->
    <div class="space-y-4">
        <div class="bg-blue-50 border border-blue-200 rounded-lg p-4">
            <h4 class="font-semibold text-blue-900 mb-2">
                <i class="fas fa-info-circle mr-2"></i>Base URL
            </h4>
            <code class="text-sm bg-white px-2 py-1 rounded border"><?php echo $_SERVER['HTTP_HOST']; ?>/api/</code>
        </div>
        
        <div class="bg-green-50 border border-green-200 rounded-lg p-4">
            <h4 class="font-semibold text-green-900 mb-2">
                <i class="fas fa-shield-alt mr-2"></i>Authentication
            </h4>
            <p class="text-sm text-green-800 mb-2">Include your API key and secret in the request:</p>
            <code class="text-sm bg-white px-2 py-1 rounded border block">
                Authorization: Bearer YOUR_API_KEY<br>
                Content-Type: application/json
            </code>
        </div>
        
        <div class="bg-yellow-50 border border-yellow-200 rounded-lg p-4">
            <h4 class="font-semibold text-yellow-900 mb-2">
                <i class="fas fa-exclamation-triangle mr-2"></i>Rate Limits
            </h4>
            <p class="text-sm text-yellow-800">Each API key has a rate limit to prevent abuse. Default: 100 requests/hour.</p>
        </div>
        
        <div class="bg-purple-50 border border-purple-200 rounded-lg p-4">
            <h4 class="font-semibold text-purple-900 mb-2">
                <i class="fas fa-code mr-2"></i>Quick Example
            </h4>
            <pre class="text-sm bg-white p-3 rounded border overflow-x-auto"><code>curl -X POST "<?php echo $_SERVER['HTTP_HOST']; ?>/api/create_order.php" \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "api_key": "YOUR_API_KEY",
    "api_secret": "YOUR_API_SECRET",
    "beneficiary": "0247965501",
    "package_size": "1GB"
  }'</code></pre>
        </div>
    </div>
    
    <!-- Full Documentation (Hidden by default) -->
    <div id="fullDocumentation" class="hidden mt-8 space-y-8">
        
        <!-- Table of Contents -->
        <div class="bg-gray-50 border border-gray-200 rounded-lg p-4">
            <h4 class="font-semibold text-gray-900 mb-3">
                <i class="fas fa-list mr-2"></i>Table of Contents
            </h4>
            <div class="grid grid-cols-1 md:grid-cols-2 gap-2 text-sm">
                <a href="#endpoints" class="text-blue-600 hover:text-blue-800">1. API Endpoints</a>
                <a href="#authentication" class="text-blue-600 hover:text-blue-800">2. Authentication</a>
                <a href="#pricing" class="text-blue-600 hover:text-blue-800">3. Role-Based Pricing</a>
                <a href="#networks" class="text-blue-600 hover:text-blue-800">4. Supported Networks</a>
                <a href="#examples" class="text-blue-600 hover:text-blue-800">5. Code Examples</a>
                <a href="#order-tracking" class="text-blue-600 hover:text-blue-800">6. Order Status Tracking</a>
                <a href="#errors" class="text-blue-600 hover:text-blue-800">7. Error Handling</a>
            </div>
        </div>
        
        <!-- API Endpoints -->
        <div id="endpoints" class="space-y-4">
            <h4 class="text-lg font-semibold text-gray-900">
                <i class="fas fa-link mr-2"></i>API Endpoints
            </h4>
            
            <div class="bg-white border border-gray-200 rounded-lg p-4">
                <h5 class="font-semibold text-gray-800 mb-2">Create Order</h5>
                <p class="text-sm text-gray-600 mb-3">Creates a single data bundle order</p>
                <div class="space-y-3">
                    <div>
                        <span class="inline-block bg-green-100 text-green-800 text-xs px-2 py-1 rounded">POST</span>
                        <code class="ml-2 text-sm">/api/create_order.php</code>
                    </div>
                    <div>
                        <h6 class="font-medium text-gray-700 mb-1">Request Body:</h6>
                        <pre class="text-xs bg-gray-100 p-2 rounded overflow-x-auto"><code>{
  "api_key": "YOUR_API_KEY",
  "api_secret": "YOUR_API_SECRET",
  "beneficiary": "0247965501",
  "package_size": "1GB"
}</code></pre>
                    </div>
                    <div>
                        <h6 class="font-medium text-gray-700 mb-1">Response:</h6>
                        <pre class="text-xs bg-gray-100 p-2 rounded overflow-x-auto"><code>{
  "status": "success",
  "processed": 1,
  "total_cost": 4.00,
  "new_balance": 4769.00,
  "order_ids": [74],
  "api_results": [...]
}</code></pre>
                    </div>
                </div>
            </div>
            
            <div class="bg-white border border-gray-200 rounded-lg p-4">
                <h5 class="font-semibold text-gray-800 mb-2">Bulk Orders</h5>
                <p class="text-sm text-gray-600 mb-3">Creates multiple orders in a single request</p>
                <div class="space-y-3">
                    <div>
                        <span class="inline-block bg-green-100 text-green-800 text-xs px-2 py-1 rounded">POST</span>
                        <code class="ml-2 text-sm">/api/create_order.php</code>
                    </div>
                    <div>
                        <h6 class="font-medium text-gray-700 mb-1">Request Body:</h6>
                        <pre class="text-xs bg-gray-100 p-2 rounded overflow-x-auto"><code>{
  "api_key": "YOUR_API_KEY",
  "api_secret": "YOUR_API_SECRET",
  "orders": [
    {"beneficiary": "0247965501", "package_size": "1GB"},
    {"beneficiary": "0246145475", "package_size": "2GB"}
  ]
}</code></pre>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- Authentication -->
        <div id="authentication" class="space-y-4">
            <h4 class="text-lg font-semibold text-gray-900">
                <i class="fas fa-shield-alt mr-2"></i>Authentication Methods
            </h4>
            
            <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                <div class="bg-blue-50 border border-blue-200 rounded-lg p-4">
                    <h5 class="font-semibold text-blue-900 mb-2">Method 1: Authorization Header</h5>
                    <pre class="text-xs bg-white p-2 rounded border overflow-x-auto"><code>Authorization: Bearer YOUR_API_KEY
Content-Type: application/json</code></pre>
                </div>
                
                <div class="bg-green-50 border border-green-200 rounded-lg p-4">
                    <h5 class="font-semibold text-green-900 mb-2">Method 2: X-API-Key Header</h5>
                    <pre class="text-xs bg-white p-2 rounded border overflow-x-auto"><code>X-API-Key: YOUR_API_KEY
Content-Type: application/json</code></pre>
                </div>
                
                <div class="bg-purple-50 border border-purple-200 rounded-lg p-4">
                    <h5 class="font-semibold text-purple-900 mb-2">Method 3: Request Body</h5>
                    <pre class="text-xs bg-white p-2 rounded border overflow-x-auto"><code>{
  "api_key": "YOUR_API_KEY",
  "api_secret": "YOUR_API_SECRET",
  ...
}</code></pre>
                </div>
            </div>
        </div>
        
        <!-- Role-Based Pricing -->
        <div id="pricing" class="space-y-4">
            <div class="flex items-center justify-between">
                <h4 class="text-lg font-semibold text-gray-900">
                    <i class="fas fa-tags mr-2"></i>Role-Based Pricing
                </h4>
                <div class="flex items-center text-xs text-gray-500">
                    <i class="fas fa-sync-alt mr-1"></i>
                    <span>Live pricing from database</span>
                </div>
            </div>
            
            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div class="bg-blue-50 border border-blue-200 rounded-lg p-4">
                    <h5 class="font-semibold text-blue-900 mb-3">Agent Role</h5>
                    <div class="space-y-2 text-sm">
                        <?php if (!empty($pricingData['agent'])): ?>
                            <?php foreach ($pricingData['agent'] as $package => $price): ?>
                                <div class="flex justify-between">
                                    <span><?php echo htmlspecialchars($package); ?>:</span>
                                    <span class="font-medium"><?php echo number_format($price, 2); ?> GHS</span>
                                </div>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <div class="text-gray-500 italic">No pricing configured for agent role</div>
                        <?php endif; ?>
                    </div>
                </div>
                
                <div class="bg-green-50 border border-green-200 rounded-lg p-4">
                    <h5 class="font-semibold text-green-900 mb-3">Super Agent Role</h5>
                    <div class="space-y-2 text-sm">
                        <?php if (!empty($pricingData['super_agent'])): ?>
                            <?php foreach ($pricingData['super_agent'] as $package => $price): ?>
                                <div class="flex justify-between">
                                    <span><?php echo htmlspecialchars($package); ?>:</span>
                                    <span class="font-medium"><?php echo number_format($price, 2); ?> GHS</span>
                                </div>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <div class="text-gray-500 italic">No pricing configured for super agent role</div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
            
            <?php if (empty($pricingData['agent']) && empty($pricingData['super_agent'])): ?>
            <div class="bg-yellow-50 border border-yellow-200 rounded-lg p-4">
                <div class="flex items-center">
                    <i class="fas fa-exclamation-triangle text-yellow-600 mr-2"></i>
                    <div>
                        <h5 class="font-semibold text-yellow-900">No Pricing Configured</h5>
                        <p class="text-sm text-yellow-800 mt-1">Please contact your administrator to configure pricing rules for your account.</p>
                    </div>
                </div>
            </div>
            <?php else: ?>
            <div class="bg-blue-50 border border-blue-200 rounded-lg p-3">
                <div class="flex items-center justify-between text-xs text-blue-800">
                    <div class="flex items-center">
                        <i class="fas fa-info-circle mr-1"></i>
                        <span>Pricing is subject to change. Always check current rates before processing orders.</span>
                    </div>
                    <div class="text-blue-600">
                        <i class="fas fa-clock mr-1"></i>
                        <span>Updated: <?php echo date('M j, Y H:i'); ?></span>
                    </div>
                </div>
            </div>
            <?php endif; ?>
        </div>
        
        <!-- Supported Networks -->
        <div id="networks" class="space-y-4">
            <h4 class="text-lg font-semibold text-gray-900">
                <i class="fas fa-mobile-alt mr-2"></i>Supported Networks
            </h4>
            
            <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                <div class="bg-yellow-50 border border-yellow-200 rounded-lg p-4">
                    <h5 class="font-semibold text-yellow-900 mb-2">MTN Ghana</h5>
                    <p class="text-sm text-yellow-800 mb-2">Prefixes:</p>
                    <code class="text-xs bg-white px-2 py-1 rounded border">024, 025, 053, 054, 055, 059</code>
                    <p class="text-xs text-yellow-700 mt-2">Example: 0247965501</p>
                </div>
                
                <div class="bg-blue-50 border border-blue-200 rounded-lg p-4">
                    <h5 class="font-semibold text-blue-900 mb-2">Telecel Ghana</h5>
                    <p class="text-sm text-blue-800 mb-2">Prefixes:</p>
                    <code class="text-xs bg-white px-2 py-1 rounded border">020, 050</code>
                    <p class="text-xs text-blue-700 mt-2">Example: 0246145475</p>
                </div>
                
                <div class="bg-red-50 border border-red-200 rounded-lg p-4">
                    <h5 class="font-semibold text-red-900 mb-2">AirtelTigo Ghana</h5>
                    <p class="text-sm text-red-800 mb-2">Prefixes:</p>
                    <code class="text-xs bg-white px-2 py-1 rounded border">027, 057, 026, 056, 023</code>
                    <p class="text-xs text-red-700 mt-2">Example: 0598544791</p>
                </div>
            </div>
        </div>
        
        <!-- Code Examples -->
        <div id="examples" class="space-y-4">
            <h4 class="text-lg font-semibold text-gray-900">
                <i class="fas fa-code mr-2"></i>Code Examples
            </h4>
            
            <div class="space-y-4">
                <div class="bg-gray-50 border border-gray-200 rounded-lg p-4">
                    <h5 class="font-semibold text-gray-800 mb-2">PHP Example</h5>
                    <pre class="text-xs bg-white p-3 rounded border overflow-x-auto"><code>$data = [
    'api_key' => 'YOUR_API_KEY',
    'api_secret' => 'YOUR_API_SECRET',
    'beneficiary' => '0247965501',
    'package_size' => '1GB'
];

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, '<?php echo $_SERVER['HTTP_HOST']; ?>/api/create_order.php');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Content-Type: application/json',
    'Authorization: Bearer YOUR_API_KEY'
]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$response = curl_exec($ch);
$result = json_decode($response, true);
curl_close($ch);

if ($result['status'] === 'success') {
    echo "Order created: " . $result['order_ids'][0];
}</code></pre>
                </div>
                
                <div class="bg-gray-50 border border-gray-200 rounded-lg p-4">
                    <h5 class="font-semibold text-gray-800 mb-2">JavaScript Example</h5>
                    <pre class="text-xs bg-white p-3 rounded border overflow-x-auto"><code>const data = {
    api_key: 'YOUR_API_KEY',
    api_secret: 'YOUR_API_SECRET',
    beneficiary: '0247965501',
    package_size: '1GB'
};

const response = await fetch('<?php echo $_SERVER['HTTP_HOST']; ?>/api/create_order.php', {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json',
        'Authorization': 'Bearer YOUR_API_KEY'
    },
    body: JSON.stringify(data)
});

const result = await response.json();
if (result.status === 'success') {
    console.log('Order created:', result.order_ids[0]);
}</code></pre>
                </div>
            </div>
        </div>
        
        <!-- Error Handling -->
        <div id="errors" class="space-y-4">
            <h4 class="text-lg font-semibold text-gray-900">
                <i class="fas fa-exclamation-triangle mr-2"></i>Error Handling
            </h4>
            
            <div class="space-y-3">
                <div class="bg-red-50 border border-red-200 rounded-lg p-4">
                    <h5 class="font-semibold text-red-900 mb-2">Common Error Codes</h5>
                    <div class="space-y-2 text-sm">
                        <div class="flex justify-between">
                            <span><strong>201:</strong> Success</span>
                        </div>
                        <div class="flex justify-between">
                            <span><strong>400:</strong> Bad request (invalid input)</span>
                        </div>
                        <div class="flex justify-between">
                            <span><strong>401:</strong> Unauthorized (invalid API key)</span>
                        </div>
                        <div class="flex justify-between">
                            <span><strong>402:</strong> Insufficient balance</span>
                        </div>
                        <div class="flex justify-between">
                            <span><strong>429:</strong> Rate limit exceeded</span>
                        </div>
                    </div>
                </div>
                
                <div class="bg-yellow-50 border border-yellow-200 rounded-lg p-4">
                    <h5 class="font-semibold text-yellow-900 mb-2">Common Error Messages</h5>
                    <ul class="text-sm text-yellow-800 space-y-1">
                        <li>• "API key required" - Include API key in request</li>
                        <li>• "Invalid beneficiary number" - Use valid Ghana phone numbers</li>
                        <li>• "Unrecognized network prefix" - Use supported network prefixes</li>
                        <li>• "No custom pricing set" - Contact admin to configure pricing</li>
                        <li>• "Insufficient balance" - Add funds to your account</li>
                    </ul>
                </div>
            </div>
        </div>
        
        <!-- Order Status Tracking -->
        <div id="order-tracking" class="space-y-4">
            <h4 class="text-lg font-semibold text-gray-900">
                <i class="fas fa-search mr-2"></i>Order Status Tracking
            </h4>
            
            <div class="bg-green-50 border border-green-200 rounded-lg p-4">
                <h5 class="font-semibold text-green-900 mb-3">
                    <i class="fas fa-clock mr-2"></i>Automated Order Status Monitoring
                </h5>
                <p class="text-sm text-green-800 mb-3">
                    Track your order statuses automatically using cron jobs with our Check Order Status API. 
                    This allows you to monitor order progress without manual intervention.
                </p>
                
                <div class="space-y-4">
                    <div class="bg-white border border-green-200 rounded-lg p-4">
                        <h6 class="font-semibold text-gray-900 mb-2">API Endpoint</h6>
                        <code class="text-sm bg-gray-100 px-2 py-1 rounded">GET /api/check_order_status.php</code>
                    </div>
                    
                    <div class="bg-white border border-green-200 rounded-lg p-4">
                        <h6 class="font-semibold text-gray-900 mb-2">Required Parameters</h6>
                        <ul class="text-sm text-gray-700 space-y-1">
                            <li>• <strong>order_id</strong> - The order ID to check (or comma-separated list)</li>
                            <li>• <strong>api_key</strong> - Your API key for authentication</li>
                        </ul>
                    </div>
                    
                    <div class="bg-white border border-green-200 rounded-lg p-4">
                        <h6 class="font-semibold text-gray-900 mb-2">Example Request</h6>
                        <pre class="text-xs bg-gray-100 p-2 rounded overflow-x-auto"><code>GET /api/check_order_status.php?order_id=123&api_key=YOUR_API_KEY

# Or for multiple orders:
GET /api/check_order_status.php?order_ids=123,124,125&api_key=YOUR_API_KEY</code></pre>
                    </div>
                    
                    <div class="bg-white border border-green-200 rounded-lg p-4">
                        <h6 class="font-semibold text-gray-900 mb-2">Example Response</h6>
                        <pre class="text-xs bg-gray-100 p-2 rounded overflow-x-auto"><code>{
  "success": true,
  "processed": 1,
  "orders": [
    {
      "order_id": 123,
      "status": "delivered",
      "package_size": "1GB",
      "amount": 5.50,
      "beneficiary_number": "0247965501",
      "network_type": "MTN",
      "status_description": "Order has been successfully delivered",
      "is_completed": true,
      "created_at": "2024-01-15 10:30:00"
    }
  ],
  "api_info": {
    "user_id": 4,
    "username": "john",
    "role": "agent"
  }
}</code></pre>
                    </div>
                </div>
            </div>
            
            <!-- Cron Job Examples -->
            <div class="bg-blue-50 border border-blue-200 rounded-lg p-4">
                <h5 class="font-semibold text-blue-900 mb-3">
                    <i class="fas fa-tasks mr-2"></i>Cron Job Implementation
                </h5>
                <p class="text-sm text-blue-800 mb-3">
                    Set up automated monitoring using cron jobs. Here are examples for different scenarios:
                </p>
                
                <div class="space-y-4">
                    <!-- Bash Script Example -->
                    <div class="bg-white border border-blue-200 rounded-lg p-4">
                        <h6 class="font-semibold text-gray-900 mb-2">Bash Script Example</h6>
                        <pre class="text-xs bg-gray-100 p-2 rounded overflow-x-auto"><code>#!/bin/bash

# Configuration
API_KEY="YOUR_API_KEY"
BASE_URL="https://yourdomain.com/api"
LOG_FILE="/var/log/order_status_check.log"

# Function to check order status
check_order_status() {
    local order_id=$1
    local response=$(curl -s "${BASE_URL}/check_order_status.php?order_id=${order_id}&api_key=${API_KEY}")
    
    # Parse response and log results
    echo "$(date): Checking order $order_id" >> "$LOG_FILE"
    echo "$response" >> "$LOG_FILE"
    
    # Check if response is valid JSON and contains success
    if echo "$response" | grep -q '"success": true'; then
        # Check if order is completed
        if echo "$response" | grep -q '"is_completed": true'; then
            echo "$(date): Order $order_id completed successfully" >> "$LOG_FILE"
            # Add your completion logic here (send notification, update database, etc.)
        else
            echo "$(date): Order $order_id still processing" >> "$LOG_FILE"
        fi
    else
        echo "$(date): Failed to check order $order_id - Invalid response" >> "$LOG_FILE"
    fi
}

# Check specific orders
check_order_status 123
check_order_status 124
check_order_status 125</code></pre>
                    </div>
                    
                    
                    <!-- Cron Job Schedule -->
                    <div class="bg-white border border-blue-200 rounded-lg p-4">
                        <h6 class="font-semibold text-gray-900 mb-2">Cron Job Schedule Examples</h6>
                        <div class="space-y-2 text-sm">
                            <div class="flex justify-between">
                                <span><strong>Every 5 minutes:</strong></span>
                                <code class="bg-gray-100 px-2 py-1 rounded">*/5 * * * * /path/to/check_orders.sh</code>
                            </div>
                            <div class="flex justify-between">
                                <span><strong>Every 15 minutes:</strong></span>
                                <code class="bg-gray-100 px-2 py-1 rounded">*/15 * * * * /path/to/check_orders.sh</code>
                            </div>
                            <div class="flex justify-between">
                                <span><strong>Every hour:</strong></span>
                                <code class="bg-gray-100 px-2 py-1 rounded">0 * * * * /path/to/check_orders.sh</code>
                            </div>
                            <div class="flex justify-between">
                                <span><strong>Every 6 hours:</strong></span>
                                <code class="bg-gray-100 px-2 py-1 rounded">0 */6 * * * /path/to/check_orders.sh</code>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- Status Meanings -->
            <div class="bg-yellow-50 border border-yellow-200 rounded-lg p-4">
                <h5 class="font-semibold text-yellow-900 mb-3">
                    <i class="fas fa-info-circle mr-2"></i>Order Status Meanings
                </h5>
                <div class="grid grid-cols-1 md:grid-cols-2 gap-4 text-sm">
                    <div>
                        <h6 class="font-semibold text-gray-900 mb-2">Success Statuses</h6>
                        <ul class="space-y-1 text-yellow-800">
                            <li>• <strong>delivered</strong> - Order completed successfully</li>
                            <li>• <strong>completed</strong> - Order finished processing</li>
                        </ul>
                    </div>
                    <div>
                        <h6 class="font-semibold text-gray-900 mb-2">Processing Statuses</h6>
                        <ul class="space-y-1 text-yellow-800">
                            <li>• <strong>pending</strong> - Order received, processing</li>
                            <li>• <strong>verified</strong> - Order verified, in progress</li>
                        </ul>
                    </div>
                    <div>
                        <h6 class="font-semibold text-gray-900 mb-2">Failed Statuses</h6>
                        <ul class="space-y-1 text-yellow-800">
                            <li>• <strong>failed</strong> - Order processing failed</li>
                            <li>• <strong>api_failed</strong> - External API error</li>
                        </ul>
                    </div>
                    <div>
                        <h6 class="font-semibold text-gray-900 mb-2">Response Fields</h6>
                        <ul class="space-y-1 text-yellow-800">
                            <li>• <strong>is_completed</strong> - true/false completion flag</li>
                            <li>• <strong>status_description</strong> - Human readable status</li>
                        </ul>
                    </div>
                </div>
            </div>
            
            <!-- Best Practices -->
            <div class="bg-purple-50 border border-purple-200 rounded-lg p-4">
                <h5 class="font-semibold text-purple-900 mb-3">
                    <i class="fas fa-star mr-2"></i>Best Practices
                </h5>
                <ul class="text-sm text-purple-800 space-y-2">
                    <li>✅ <strong>Check orders every 5-15 minutes</strong> for real-time monitoring</li>
                    <li>✅ <strong>Log all responses</strong> for debugging and analysis</li>
                    <li>✅ <strong>Handle API errors gracefully</strong> with retry logic</li>
                    <li>✅ <strong>Use bulk checking</strong> for multiple orders (comma-separated IDs)</li>
                    <li>✅ <strong>Set up notifications</strong> for completed or failed orders</li>
                    <li>✅ <strong>Monitor rate limits</strong> (100 requests/hour default)</li>
                    <li>✅ <strong>Store order IDs</strong> in your database for tracking</li>
                </ul>
            </div>
        </div>

        <!-- Important Notes -->
        <div class="bg-blue-50 border border-blue-200 rounded-lg p-4">
            <h4 class="font-semibold text-blue-900 mb-3">
                <i class="fas fa-info-circle mr-2"></i>Important Notes
            </h4>
            <ul class="text-sm text-blue-800 space-y-2">
                <li>✅ <strong>Use agent or super_agent roles</strong> (admin role has no pricing configured)</li>
                <li>✅ <strong>Include API key and secret</strong> in all requests</li>
                <li>✅ <strong>Use valid Ghana phone numbers</strong> with supported prefixes</li>
                <li>✅ <strong>Check your balance</strong> before making orders</li>
                <li>✅ <strong>Handle rate limits</strong> (100 requests/hour default)</li>
                <li>✅ <strong>Orders are saved to database first</strong>, then forwarded to external APIs</li>
                <li>✅ <strong>Balance is deducted immediately</strong> when order is created</li>
            </ul>
        </div>
    </div>
</div>

<script>
    function toggleGenerateForm() {
        const form = document.getElementById('generateForm');
        form.classList.toggle('hidden');
    }
    
    
    function toggleDocumentation() {
        const doc = document.getElementById('fullDocumentation');
        const button = event.target.closest('button');
        const icon = button.querySelector('i');
        const text = button.querySelector('span') || button.childNodes[button.childNodes.length - 1];
        
        if (doc.classList.contains('hidden')) {
            doc.classList.remove('hidden');
            icon.className = 'fas fa-eye-slash mr-2';
            if (text && text.textContent) {
                text.textContent = 'Hide Full Documentation';
            } else {
                button.innerHTML = '<i class="fas fa-eye-slash mr-2"></i>Hide Full Documentation';
            }
        } else {
            doc.classList.add('hidden');
            icon.className = 'fas fa-eye mr-2';
            if (text && text.textContent) {
                text.textContent = 'View Full Documentation';
            } else {
                button.innerHTML = '<i class="fas fa-eye mr-2"></i>View Full Documentation';
            }
        }
    }
    
    function copyToClipboard(text) {
        navigator.clipboard.writeText(text).then(function() {
            // Show success message
            const button = event.target.closest('button');
            const originalHTML = button.innerHTML;
            button.innerHTML = '<i class="fas fa-check"></i>';
            button.classList.add('bg-green-200', 'text-green-800');
            
            setTimeout(() => {
                button.innerHTML = originalHTML;
                button.classList.remove('bg-green-200', 'text-green-800');
            }, 2000);
        }).catch(function(err) {
            console.error('Could not copy text: ', err);
            alert('Failed to copy to clipboard');
        });
    }
    
    // Smooth scrolling for documentation links
    document.addEventListener('DOMContentLoaded', function() {
        const links = document.querySelectorAll('a[href^="#"]');
        links.forEach(link => {
            link.addEventListener('click', function(e) {
                e.preventDefault();
                const targetId = this.getAttribute('href').substring(1);
                const targetElement = document.getElementById(targetId);
                if (targetElement) {
                    targetElement.scrollIntoView({
                        behavior: 'smooth',
                        block: 'start'
                    });
                }
            });
        });
    });
</script>
