<?php
session_start();
require_once 'config.php';

// Check if user is logged in
if (!isset($_SESSION['user_id']) || !isset($_SESSION['username'])) {
    header('Location: login.php');
    exit();
}

$user_id = $_SESSION['user_id'];
$username = $_SESSION['username'];
$user_role = $_SESSION['role'] ?? 'agent';
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>API Documentation | D-Bundles Stores</title>
    <meta name="description" content="Complete API documentation for D-Bundles Stores data bundle integration - Learn how to integrate with our API.">
    
    <!-- Tailwind CSS -->
    <script src="https://cdn.tailwindcss.com"></script>
    
    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    
    <!-- Google Fonts -->
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
    
    <!-- Prism.js for syntax highlighting -->
    <link href="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/themes/prism-tomorrow.min.css" rel="stylesheet">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/components/prism-core.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/plugins/autoloader/prism-autoloader.min.js"></script>
    
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: {
                            50: '#f8fafc',
                            100: '#f1f5f9',
                            200: '#e2e8f0',
                            300: '#cbd5e1',
                            400: '#94a3b8',
                            500: '#64748b',
                            600: '#475569',
                            700: '#334155',
                            800: '#1e293b',
                            900: '#0f172a',
                        },
                        accent: {
                            50: '#eff6ff',
                            100: '#dbeafe',
                            200: '#bfdbfe',
                            300: '#93c5fd',
                            400: '#60a5fa',
                            500: '#3b82f6',
                            600: '#2563eb',
                            700: '#1d4ed8',
                            800: '#1e40af',
                            900: '#1e3a8a',
                        }
                    }
                }
            }
        }
    </script>
</head>
<body class="bg-gray-50 font-inter">
    <!-- Header -->
    <header class="bg-white shadow-sm border-b border-gray-200">
        <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
            <div class="flex justify-between items-center py-4">
                <div class="flex items-center">
                    <a href="user_index.php?page=api_keys" class="text-gray-600 hover:text-gray-800">
                        <i class="fas fa-arrow-left mr-2"></i>Back to API Keys
                    </a>
                </div>
                <div class="flex items-center space-x-4">
                    <span class="text-sm text-gray-600">Welcome, <?= htmlspecialchars($username) ?></span>
                    <a href="logout.php" class="text-red-600 hover:text-red-800">
                        <i class="fas fa-sign-out-alt"></i> Logout
                    </a>
                </div>
            </div>
        </div>
    </header>

    <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        <!-- Page Header -->
        <div class="mb-8">
            <h1 class="text-3xl font-bold text-gray-900">API Documentation</h1>
            <p class="text-gray-600 mt-2">Complete guide to integrating with D-Bundles Stores API</p>
        </div>

        <!-- Table of Contents -->
        <div class="bg-white rounded-lg shadow-sm border border-gray-200 mb-8">
            <div class="px-6 py-4 border-b border-gray-200">
                <h2 class="text-lg font-semibold text-gray-900">
                    <i class="fas fa-list mr-2"></i>Table of Contents
                </h2>
            </div>
            <div class="p-6">
                <nav class="space-y-2">
                    <a href="#overview" class="block text-accent-600 hover:text-accent-700">1. Overview</a>
                    <a href="#authentication" class="block text-accent-600 hover:text-accent-700">2. Authentication</a>
                    <a href="#endpoints" class="block text-accent-600 hover:text-accent-700">3. API Endpoints</a>
                    <a href="#request-format" class="block text-accent-600 hover:text-accent-700">4. Request Format</a>
                    <a href="#response-format" class="block text-accent-600 hover:text-accent-700">5. Response Format</a>
                    <a href="#error-handling" class="block text-accent-600 hover:text-accent-700">6. Error Handling</a>
                    <a href="#rate-limits" class="block text-accent-600 hover:text-accent-700">7. Rate Limits</a>
                    <a href="#examples" class="block text-accent-600 hover:text-accent-700">8. Code Examples</a>
                    <a href="#webhooks" class="block text-accent-600 hover:text-accent-700">9. Webhooks</a>
                </nav>
            </div>
        </div>

        <!-- Overview -->
        <div id="overview" class="bg-white rounded-lg shadow-sm border border-gray-200 mb-8">
            <div class="px-6 py-4 border-b border-gray-200">
                <h2 class="text-lg font-semibold text-gray-900">
                    <i class="fas fa-info-circle mr-2"></i>1. Overview
                </h2>
            </div>
            <div class="p-6">
                <div class="space-y-4">
                    <p class="text-gray-700">The D-Bundles Stores API allows you to integrate data bundle purchasing functionality into your applications. With our API, you can:</p>
                    <ul class="list-disc list-inside space-y-2 text-gray-700 ml-4">
                        <li>Purchase data bundles for multiple phone numbers</li>
                        <li>Support all major Ghana networks (MTN, Telecel, AirtelTigo)</li>
                        <li>Process bulk orders efficiently</li>
                        <li>Receive real-time order status updates</li>
                        <li>Track order history and usage statistics</li>
                    </ul>
                    <div class="bg-blue-50 border border-blue-200 rounded-lg p-4">
                        <h3 class="font-semibold text-blue-900 mb-2">Base URL</h3>
                        <code class="text-blue-800">https://yourdomain.com/api/</code>
                    </div>
                </div>
            </div>
        </div>

        <!-- Authentication -->
        <div id="authentication" class="bg-white rounded-lg shadow-sm border border-gray-200 mb-8">
            <div class="px-6 py-4 border-b border-gray-200">
                <h2 class="text-lg font-semibold text-gray-900">
                    <i class="fas fa-shield-alt mr-2"></i>2. Authentication
                </h2>
            </div>
            <div class="p-6">
                <div class="space-y-6">
                    <p class="text-gray-700">All API requests require authentication using your API key. You can provide your API key in three ways:</p>
                    
                    <div class="space-y-4">
                        <div class="border border-gray-200 rounded-lg p-4">
                            <h3 class="font-semibold text-gray-900 mb-2">Method 1: Authorization Header (Recommended)</h3>
                            <pre class="bg-gray-900 text-green-400 p-4 rounded text-sm overflow-x-auto"><code>Authorization: Bearer YOUR_API_KEY</code></pre>
                        </div>
                        
                        <div class="border border-gray-200 rounded-lg p-4">
                            <h3 class="font-semibold text-gray-900 mb-2">Method 2: X-API-Key Header</h3>
                            <pre class="bg-gray-900 text-green-400 p-4 rounded text-sm overflow-x-auto"><code>X-API-Key: YOUR_API_KEY</code></pre>
                        </div>
                        
                        <div class="border border-gray-200 rounded-lg p-4">
                            <h3 class="font-semibold text-gray-900 mb-2">Method 3: Request Body</h3>
                            <pre class="bg-gray-900 text-green-400 p-4 rounded text-sm overflow-x-auto"><code>{
  "api_key": "YOUR_API_KEY",
  "api_secret": "YOUR_API_SECRET",
  "orders": [...]
}</code></pre>
                        </div>
                    </div>
                    
                    <div class="bg-yellow-50 border border-yellow-200 rounded-lg p-4">
                        <h3 class="font-semibold text-yellow-900 mb-2">
                            <i class="fas fa-exclamation-triangle mr-2"></i>Security Note
                        </h3>
                        <p class="text-yellow-800 text-sm">For enhanced security, use the Authorization header method. The request body method should only be used when headers cannot be set.</p>
                    </div>
                </div>
            </div>
        </div>

        <!-- API Endpoints -->
        <div id="endpoints" class="bg-white rounded-lg shadow-sm border border-gray-200 mb-8">
            <div class="px-6 py-4 border-b border-gray-200">
                <h2 class="text-lg font-semibold text-gray-900">
                    <i class="fas fa-link mr-2"></i>3. API Endpoints
                </h2>
            </div>
            <div class="p-6">
                <div class="space-y-6">
                    <div class="border border-gray-200 rounded-lg p-6">
                        <div class="flex items-center justify-between mb-4">
                            <h3 class="text-lg font-semibold text-gray-900">Create Order</h3>
                            <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-green-100 text-green-800">
                                POST
                            </span>
                        </div>
                        <div class="space-y-4">
                            <div>
                                <strong>Endpoint:</strong> <code>/api/create_order.php</code>
                            </div>
                            <div>
                                <strong>Description:</strong> Create one or more data bundle orders
                            </div>
                            <div>
                                <strong>Content-Type:</strong> <code>application/json</code>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Request Format -->
        <div id="request-format" class="bg-white rounded-lg shadow-sm border border-gray-200 mb-8">
            <div class="px-6 py-4 border-b border-gray-200">
                <h2 class="text-lg font-semibold text-gray-900">
                    <i class="fas fa-paper-plane mr-2"></i>4. Request Format
                </h2>
            </div>
            <div class="p-6">
                <div class="space-y-6">
                    <h3 class="text-md font-semibold text-gray-900">Single Order Request</h3>
                    <pre class="bg-gray-900 text-green-400 p-4 rounded text-sm overflow-x-auto"><code>{
  "api_key": "your_api_key_here",
  "api_secret": "your_api_secret_here",
  "beneficiary": "0247965501",
  "package_size": "1GB"
}</code></pre>
                    
                    <h3 class="text-md font-semibold text-gray-900">Bulk Orders Request</h3>
                    <pre class="bg-gray-900 text-green-400 p-4 rounded text-sm overflow-x-auto"><code>{
  "api_key": "your_api_key_here",
  "api_secret": "your_api_secret_here",
  "orders": [
    {
      "beneficiary": "0247965501",
      "package_size": "1GB"
    },
    {
      "beneficiary": "0598544791",
      "package_size": "2GB"
    },
    {
      "beneficiary": "0275556785",
      "package_size": "500MB"
    }
  ]
}</code></pre>
                    
                    <div class="bg-gray-50 border border-gray-200 rounded-lg p-4">
                        <h4 class="font-semibold text-gray-900 mb-2">Field Descriptions</h4>
                        <div class="space-y-2 text-sm">
                            <div><strong>api_key:</strong> Your API key (required)</div>
                            <div><strong>api_secret:</strong> Your API secret (required for body authentication)</div>
                            <div><strong>beneficiary:</strong> Phone number to receive data bundle (required)</div>
                            <div><strong>package_size:</strong> Data bundle size (e.g., "1GB", "500MB", "2.5GB")</div>
                            <div><strong>orders:</strong> Array of orders for bulk processing</div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Response Format -->
        <div id="response-format" class="bg-white rounded-lg shadow-sm border border-gray-200 mb-8">
            <div class="px-6 py-4 border-b border-gray-200">
                <h2 class="text-lg font-semibold text-gray-900">
                    <i class="fas fa-reply mr-2"></i>5. Response Format
                </h2>
            </div>
            <div class="p-6">
                <div class="space-y-6">
                    <h3 class="text-md font-semibold text-gray-900">Success Response</h3>
                    <pre class="bg-gray-900 text-green-400 p-4 rounded text-sm overflow-x-auto"><code>{
  "status": "success",
  "processed": 2,
  "failed": 0,
  "errors": [],
  "total_cost": 8.00,
  "new_balance": 92.00,
  "order_ids": [123, 124],
  "api_results": [
    {
      "order_id": 123,
      "beneficiary": "0247965501",
      "status": "pending",
      "transaction_reference": "TXN123456",
      "message": "Order submitted to external API successfully"
    },
    {
      "order_id": 124,
      "beneficiary": "0598544791",
      "status": "pending",
      "transaction_reference": "TXN123457",
      "message": "Order submitted to external API successfully"
    }
  ],
  "message": "Orders successfully saved to database and processed",
  "rate_limit": {
    "allowed": true,
    "current_usage": 5,
    "rate_limit": 1000,
    "remaining": 995
  }
}</code></pre>
                    
                    <h3 class="text-md font-semibold text-gray-900">Error Response</h3>
                    <pre class="bg-gray-900 text-red-400 p-4 rounded text-sm overflow-x-auto"><code>{
  "status": "error",
  "message": "API key required. Provide via Authorization header, X-API-Key header, or request body"
}</code></pre>
                </div>
            </div>
        </div>

        <!-- Error Handling -->
        <div id="error-handling" class="bg-white rounded-lg shadow-sm border border-gray-200 mb-8">
            <div class="px-6 py-4 border-b border-gray-200">
                <h2 class="text-lg font-semibold text-gray-900">
                    <i class="fas fa-exclamation-circle mr-2"></i>6. Error Handling
                </h2>
            </div>
            <div class="p-6">
                <div class="space-y-4">
                    <p class="text-gray-700">The API uses standard HTTP status codes to indicate success or failure:</p>
                    
                    <div class="space-y-3">
                        <div class="flex items-center space-x-3">
                            <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-green-100 text-green-800">200</span>
                            <span class="text-sm text-gray-700">Success</span>
                        </div>
                        <div class="flex items-center space-x-3">
                            <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-green-100 text-green-800">201</span>
                            <span class="text-sm text-gray-700">Created (Order created successfully)</span>
                        </div>
                        <div class="flex items-center space-x-3">
                            <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-red-100 text-red-800">400</span>
                            <span class="text-sm text-gray-700">Bad Request (Invalid input)</span>
                        </div>
                        <div class="flex items-center space-x-3">
                            <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-red-100 text-red-800">401</span>
                            <span class="text-sm text-gray-700">Unauthorized (Invalid API key)</span>
                        </div>
                        <div class="flex items-center space-x-3">
                            <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-yellow-100 text-yellow-800">429</span>
                            <span class="text-sm text-gray-700">Too Many Requests (Rate limit exceeded)</span>
                        </div>
                        <div class="flex items-center space-x-3">
                            <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-red-100 text-red-800">500</span>
                            <span class="text-sm text-gray-700">Internal Server Error</span>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Rate Limits -->
        <div id="rate-limits" class="bg-white rounded-lg shadow-sm border border-gray-200 mb-8">
            <div class="px-6 py-4 border-b border-gray-200">
                <h2 class="text-lg font-semibold text-gray-900">
                    <i class="fas fa-tachometer-alt mr-2"></i>7. Rate Limits
                </h2>
            </div>
            <div class="p-6">
                <div class="space-y-4">
                    <p class="text-gray-700">To prevent abuse and ensure fair usage, the API implements rate limiting:</p>
                    
                    <div class="bg-blue-50 border border-blue-200 rounded-lg p-4">
                        <h3 class="font-semibold text-blue-900 mb-2">Default Rate Limits</h3>
                        <ul class="text-blue-800 space-y-1">
                            <li>• <strong>Default:</strong> 1000 requests per hour</li>
                            <li>• <strong>Customizable:</strong> Can be adjusted per API key</li>
                            <li>• <strong>Window:</strong> Rolling 1-hour window</li>
                        </ul>
                    </div>
                    
                    <div class="bg-yellow-50 border border-yellow-200 rounded-lg p-4">
                        <h3 class="font-semibold text-yellow-900 mb-2">Rate Limit Headers</h3>
                        <p class="text-yellow-800 text-sm">When you approach your rate limit, the API includes helpful headers in the response:</p>
                        <pre class="bg-yellow-100 p-2 rounded text-xs mt-2"><code>X-RateLimit-Limit: 1000
X-RateLimit-Remaining: 995
X-RateLimit-Reset: 1640995200</code></pre>
                    </div>
                </div>
            </div>
        </div>

        <!-- Code Examples -->
        <div id="examples" class="bg-white rounded-lg shadow-sm border border-gray-200 mb-8">
            <div class="px-6 py-4 border-b border-gray-200">
                <h2 class="text-lg font-semibold text-gray-900">
                    <i class="fas fa-code mr-2"></i>8. Code Examples
                </h2>
            </div>
            <div class="p-6">
                <div class="space-y-8">
                    <!-- PHP Example -->
                    <div>
                        <h3 class="text-md font-semibold text-gray-900 mb-3">PHP Example</h3>
                        <pre class="bg-gray-900 text-green-400 p-4 rounded text-sm overflow-x-auto"><code>&lt;?php
$api_url = 'https://yourdomain.com/api/create_order.php';
$api_key = 'your_api_key_here';
$api_secret = 'your_api_secret_here';

$data = [
    'api_key' => $api_key,
    'api_secret' => $api_secret,
    'orders' => [
        [
            'beneficiary' => '0247965501',
            'package_size' => '1GB'
        ],
        [
            'beneficiary' => '0598544791',
            'package_size' => '2GB'
        ]
    ]
];

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $api_url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Content-Type: application/json'
]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

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

if ($result['status'] === 'success') {
    echo "Orders placed successfully!\n";
    foreach ($result['api_results'] as $order) {
        echo "Order ID: " . $order['order_id'] . "\n";
        echo "Status: " . $order['status'] . "\n";
    }
} else {
    echo "Error: " . $result['message'] . "\n";
}
?&gt;</code></pre>
                    </div>
                    
                    <!-- JavaScript Example -->
                    <div>
                        <h3 class="text-md font-semibold text-gray-900 mb-3">JavaScript Example</h3>
                        <pre class="bg-gray-900 text-green-400 p-4 rounded text-sm overflow-x-auto"><code>async function placeOrder(apiKey, apiSecret, orders) {
    try {
        const response = await fetch('https://yourdomain.com/api/create_order.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${apiKey}`
            },
            body: JSON.stringify({
                api_key: apiKey,
                api_secret: apiSecret,
                orders: orders
            })
        });
        
        const result = await response.json();
        
        if (result.status === 'success') {
            console.log('Orders placed successfully:', result.api_results);
            return result;
        } else {
            console.error('Order failed:', result.message);
            throw new Error(result.message);
        }
    } catch (error) {
        console.error('API Error:', error);
        throw error;
    }
}

// Usage
const orders = [
    { beneficiary: '0247965501', package_size: '1GB' },
    { beneficiary: '0598544791', package_size: '2GB' }
];

placeOrder('your_api_key', 'your_api_secret', orders)
    .then(result => {
        console.log('Order result:', result);
    })
    .catch(error => {
        console.error('Error:', error);
    });</code></pre>
                    </div>
                    
                    <!-- Python Example -->
                    <div>
                        <h3 class="text-md font-semibold text-gray-900 mb-3">Python Example</h3>
                        <pre class="bg-gray-900 text-green-400 p-4 rounded text-sm overflow-x-auto"><code>import requests
import json

def place_order(api_key, api_secret, orders):
    url = 'https://yourdomain.com/api/create_order.php'
    
    data = {
        'api_key': api_key,
        'api_secret': api_secret,
        'orders': orders
    }
    
    headers = {
        'Content-Type': 'application/json',
        'Authorization': f'Bearer {api_key}'
    }
    
    try:
        response = requests.post(url, json=data, headers=headers)
        result = response.json()
        
        if result['status'] == 'success':
            print("Orders placed successfully!")
            for order in result['api_results']:
                print(f"Order ID: {order['order_id']}")
                print(f"Status: {order['status']}")
            return result
        else:
            print(f"Error: {result['message']}")
            return None
            
    except requests.exceptions.RequestException as e:
        print(f"Request error: {e}")
        return None

# Usage
orders = [
    {'beneficiary': '0247965501', 'package_size': '1GB'},
    {'beneficiary': '0598544791', 'package_size': '2GB'}
]

result = place_order('your_api_key', 'your_api_secret', orders)</code></pre>
                    </div>
                </div>
            </div>
        </div>

        <!-- Webhooks -->
        <div id="webhooks" class="bg-white rounded-lg shadow-sm border border-gray-200 mb-8">
            <div class="px-6 py-4 border-b border-gray-200">
                <h2 class="text-lg font-semibold text-gray-900">
                    <i class="fas fa-webhook mr-2"></i>9. Webhooks
                </h2>
            </div>
            <div class="p-6">
                <div class="space-y-4">
                    <p class="text-gray-700">Webhooks allow you to receive real-time notifications about order status changes. This is useful for tracking order progress and updating your application accordingly.</p>
                    
                    <div class="bg-blue-50 border border-blue-200 rounded-lg p-4">
                        <h3 class="font-semibold text-blue-900 mb-2">Webhook Endpoint</h3>
                        <p class="text-blue-800 text-sm">Configure your webhook URL in your application settings to receive status updates:</p>
                        <code class="text-blue-800 text-sm">https://yourdomain.com/api/webhook/status_update.php</code>
                    </div>
                    
                    <div class="bg-gray-50 border border-gray-200 rounded-lg p-4">
                        <h3 class="font-semibold text-gray-900 mb-2">Webhook Payload</h3>
                        <pre class="bg-gray-900 text-green-400 p-4 rounded text-sm overflow-x-auto"><code>{
  "transaction_id": "123456789",
  "status": "delivered",
  "type": "status_update"
}</code></pre>
                    </div>
                </div>
            </div>
        </div>

        <!-- Support -->
        <div class="bg-white rounded-lg shadow-sm border border-gray-200">
            <div class="px-6 py-4 border-b border-gray-200">
                <h2 class="text-lg font-semibold text-gray-900">
                    <i class="fas fa-life-ring mr-2"></i>Support
                </h2>
            </div>
            <div class="p-6">
                <div class="space-y-4">
                    <p class="text-gray-700">Need help with API integration? Here are some resources:</p>
                    <ul class="list-disc list-inside space-y-2 text-gray-700 ml-4">
                        <li>Check your API key management page for usage statistics</li>
                        <li>Review the error messages for troubleshooting</li>
                        <li>Contact support for technical assistance</li>
                        <li>Monitor your rate limits to avoid throttling</li>
                    </ul>
                </div>
            </div>
        </div>
    </div>

    <script>
        // Smooth scrolling for table of contents links
        document.querySelectorAll('a[href^="#"]').forEach(anchor => {
            anchor.addEventListener('click', function (e) {
                e.preventDefault();
                const target = document.querySelector(this.getAttribute('href'));
                if (target) {
                    target.scrollIntoView({
                        behavior: 'smooth',
                        block: 'start'
                    });
                }
            });
        });
    </script>
</body>
</html>


