{
  "kitonga_wifi_api_endpoints": {
    "base_url": "https://api.kitonga.klikcell.com",
    "local_dev_url": "http://127.0.0.1:8000",
    "authentication": {
      "description": "Most endpoints require admin authentication token",
      "header": "Authorization: Bearer YOUR_ADMIN_TOKEN",
      "token_from_env": "SIMPLE_ADMIN_TOKEN"
    },
    "endpoints": {
      "health_check": {
        "method": "GET",
        "url": "/health/",
        "description": "System health check",
        "authentication": "None",
        "request_example": {
          "javascript": "fetch('/health/')",
          "curl": "curl -X GET https://api.kitonga.klikcell.com/health/"
        },
        "response_example": {
          "status": "healthy",
          "timestamp": "2025-10-27T16:13:04Z",
          "database": "connected",
          "version": "1.0.0"
        }
      },
      "admin_authentication": {
        "login": {
          "method": "POST",
          "url": "/auth/login/",
          "description": "Admin login to get authentication token",
          "authentication": "None",
          "request_example": {
            "javascript": `fetch('/auth/login/', {
              method: 'POST',
              headers: {
                'Content-Type': 'application/json'
              },
              body: JSON.stringify({
                "username": "admin",
                "password": "your_admin_password"
              })
            })`,
            "body": {
              "username": "admin",
              "password": "your_admin_password"
            }
          },
          "response_example": {
            "success": true,
            "token": "your-admin-token-here",
            "user": {
              "id": 1,
              "username": "admin",
              "email": "admin@kitonga.com"
            },
            "message": "Login successful"
          }
        },
        "logout": {
          "method": "POST",
          "url": "/auth/logout/",
          "description": "Admin logout",
          "authentication": "Required",
          "request_example": {
            "javascript": `fetch('/auth/logout/', {
              method: 'POST',
              headers: {
                'Authorization': 'Bearer YOUR_ADMIN_TOKEN',
                'Content-Type': 'application/json'
              }
            })`
          },
          "response_example": {
            "success": true,
            "message": "Logout successful"
          }
        },
        "profile": {
          "method": "GET",
          "url": "/auth/profile/",
          "description": "Get admin profile information",
          "authentication": "Required",
          "request_example": {
            "javascript": `fetch('/auth/profile/', {
              method: 'GET',
              headers: {
                'Authorization': 'Bearer YOUR_ADMIN_TOKEN'
              }
            })`
          },
          "response_example": {
            "id": 1,
            "username": "admin",
            "email": "admin@kitonga.com",
            "first_name": "Admin",
            "last_name": "User",
            "is_staff": true,
            "date_joined": "2025-01-01T00:00:00Z"
          }
        }
      },
      "wifi_access": {
        "verify_access": {
          "method": "POST",
          "url": "/verify/",
          "description": "Verify user access to Wi-Fi",
          "authentication": "None",
          "request_example": {
            "javascript": `fetch('/verify/', {
              method: 'POST',
              headers: {
                'Content-Type': 'application/json'
              },
              body: JSON.stringify({
                "phone_number": "255700000000",
                "mac_address": "AA:BB:CC:DD:EE:FF",
                "ip_address": "192.168.88.100"
              })
            })`,
            "body": {
              "phone_number": "255700000000",
              "mac_address": "AA:BB:CC:DD:EE:FF",
              "ip_address": "192.168.88.100"
            }
          },
          "response_example": {
            "has_access": true,
            "user": {
              "phone_number": "255700000000",
              "subscription_end": "2025-10-28T16:00:00Z",
              "devices_count": 1,
              "max_devices": 1
            },
            "message": "Access granted"
          }
        },
        "user_status": {
          "method": "GET",
          "url": "/user-status/{phone_number}/",
          "description": "Get user status information",
          "authentication": "None",
          "request_example": {
            "javascript": `fetch('/user-status/255700000000/')`,
            "url": "/user-status/255700000000/"
          },
          "response_example": {
            "user": {
              "phone_number": "255700000000",
              "subscription_end": "2025-10-28T16:00:00Z",
              "is_active": true,
              "devices_count": 1,
              "max_devices": 1,
              "total_payments": 5000
            },
            "has_access": true,
            "time_remaining": "23 hours, 45 minutes"
          }
        }
      },
      "payments": {
        "list_bundles": {
          "method": "GET",
          "url": "/bundles/",
          "description": "Get available Wi-Fi bundles",
          "authentication": "None",
          "request_example": {
            "javascript": "fetch('/bundles/')"
          },
          "response_example": [
            {
              "id": 1,
              "name": "Daily Access",
              "price": 1000,
              "duration_hours": 24,
              "description": "24-hour Wi-Fi access",
              "is_active": true
            }
          ]
        },
        "initiate_payment": {
          "method": "POST",
          "url": "/initiate-payment/",
          "description": "Initiate ClickPesa payment",
          "authentication": "None",
          "request_example": {
            "javascript": `fetch('/initiate-payment/', {
              method: 'POST',
              headers: {
                'Content-Type': 'application/json'
              },
              body: JSON.stringify({
                "phone_number": "255700000000",
                "bundle_id": 1,
                "mac_address": "AA:BB:CC:DD:EE:FF"
              })
            })`,
            "body": {
              "phone_number": "255700000000",
              "bundle_id": 1,
              "mac_address": "AA:BB:CC:DD:EE:FF"
            }
          },
          "response_example": {
            "success": true,
            "payment_reference": "PAY-12345-67890",
            "order_reference": "ORD-12345-67890",
            "amount": 1000,
            "phone_number": "255700000000",
            "redirect_url": "https://checkout.clickpesa.com/...",
            "message": "Payment initiated successfully"
          }
        },
        "payment_status": {
          "method": "GET",
          "url": "/payment-status/{order_reference}/",
          "description": "Check payment status",
          "authentication": "None",
          "request_example": {
            "javascript": `fetch('/payment-status/ORD-12345-67890/')`,
            "url": "/payment-status/ORD-12345-67890/"
          },
          "response_example": {
            "payment_status": "COMPLETED",
            "order_reference": "ORD-12345-67890",
            "amount": 1000,
            "phone_number": "255700000000",
            "payment_date": "2025-10-27T16:00:00Z",
            "access_granted": true,
            "subscription_end": "2025-10-28T16:00:00Z"
          }
        }
      },
      "device_management": {
        "list_devices": {
          "method": "GET",
          "url": "/devices/{phone_number}/",
          "description": "List user's registered devices",
          "authentication": "None",
          "request_example": {
            "javascript": `fetch('/devices/255700000000/')`,
            "url": "/devices/255700000000/"
          },
          "response_example": [
            {
              "id": 1,
              "mac_address": "AA:BB:CC:DD:EE:FF",
              "device_name": "iPhone",
              "ip_address": "192.168.88.100",
              "first_connected": "2025-10-27T10:00:00Z",
              "last_seen": "2025-10-27T16:00:00Z",
              "is_active": true
            }
          ]
        },
        "remove_device": {
          "method": "POST",
          "url": "/devices/remove/",
          "description": "Remove a device from user's account",
          "authentication": "None",
          "request_example": {
            "javascript": `fetch('/devices/remove/', {
              method: 'POST',
              headers: {
                'Content-Type': 'application/json'
              },
              body: JSON.stringify({
                "phone_number": "255700000000",
                "mac_address": "AA:BB:CC:DD:EE:FF"
              })
            })`,
            "body": {
              "phone_number": "255700000000",
              "mac_address": "AA:BB:CC:DD:EE:FF"
            }
          },
          "response_example": {
            "success": true,
            "message": "Device removed successfully",
            "devices_remaining": 0
          }
        }
      },
      "voucher_system": {
        "generate_vouchers": {
          "method": "POST",
          "url": "/vouchers/generate/",
          "description": "Generate vouchers (Admin only)",
          "authentication": "Required",
          "request_example": {
            "javascript": `fetch('/vouchers/generate/', {
              method: 'POST',
              headers: {
                'Authorization': 'Bearer YOUR_ADMIN_TOKEN',
                'Content-Type': 'application/json'
              },
              body: JSON.stringify({
                "bundle_id": 1,
                "quantity": 10,
                "expiry_days": 30
              })
            })`,
            "body": {
              "bundle_id": 1,
              "quantity": 10,
              "expiry_days": 30
            }
          },
          "response_example": {
            "success": true,
            "vouchers_generated": 10,
            "vouchers": [
              {
                "code": "KITONGA-12345",
                "bundle": "Daily Access",
                "expires_at": "2025-11-26T16:00:00Z"
              }
            ]
          }
        },
        "redeem_voucher": {
          "method": "POST",
          "url": "/vouchers/redeem/",
          "description": "Redeem a voucher code",
          "authentication": "None",
          "request_example": {
            "javascript": `fetch('/vouchers/redeem/', {
              method: 'POST',
              headers: {
                'Content-Type': 'application/json'
              },
              body: JSON.stringify({
                "phone_number": "255700000000",
                "voucher_code": "KITONGA-12345",
                "mac_address": "AA:BB:CC:DD:EE:FF"
              })
            })`,
            "body": {
              "phone_number": "255700000000",
              "voucher_code": "KITONGA-12345",
              "mac_address": "AA:BB:CC:DD:EE:FF"
            }
          },
          "response_example": {
            "success": true,
            "message": "Voucher redeemed successfully",
            "access_granted": true,
            "subscription_end": "2025-10-28T16:00:00Z",
            "bundle": {
              "name": "Daily Access",
              "duration_hours": 24
            }
          }
        },
        "list_vouchers": {
          "method": "GET",
          "url": "/vouchers/list/",
          "description": "List all vouchers (Admin only)",
          "authentication": "Required",
          "request_example": {
            "javascript": `fetch('/vouchers/list/', {
              method: 'GET',
              headers: {
                'Authorization': 'Bearer YOUR_ADMIN_TOKEN'
              }
            })`
          },
          "response_example": [
            {
              "id": 1,
              "code": "KITONGA-12345",
              "bundle": "Daily Access",
              "is_used": false,
              "created_at": "2025-10-27T10:00:00Z",
              "expires_at": "2025-11-26T16:00:00Z",
              "used_by": null,
              "used_at": null
            }
          ]
        }
      },
      "mikrotik_integration": {
        "auth": {
          "method": "POST",
          "url": "/mikrotik/auth/",
          "description": "Authenticate user with MikroTik hotspot",
          "authentication": "None",
          "request_example": {
            "javascript": `fetch('/mikrotik/auth/', {
              method: 'POST',
              headers: {
                'Content-Type': 'application/json'
              },
              body: JSON.stringify({
                "phone_number": "255700000000",
                "mac_address": "AA:BB:CC:DD:EE:FF",
                "ip_address": "192.168.88.100"
              })
            })`,
            "body": {
              "phone_number": "255700000000",
              "mac_address": "AA:BB:CC:DD:EE:FF",
              "ip_address": "192.168.88.100"
            }
          },
          "response_example": {
            "success": true,
            "authenticated": true,
            "message": "User authenticated successfully",
            "mikrotik_response": "External authentication successful"
          }
        },
        "logout": {
          "method": "POST",
          "url": "/mikrotik/logout/",
          "description": "Logout user from MikroTik hotspot",
          "authentication": "None",
          "request_example": {
            "javascript": `fetch('/mikrotik/logout/', {
              method: 'POST',
              headers: {
                'Content-Type': 'application/json'
              },
              body: JSON.stringify({
                "phone_number": "255700000000",
                "ip_address": "192.168.88.100"
              })
            })`,
            "body": {
              "phone_number": "255700000000",
              "ip_address": "192.168.88.100"
            }
          },
          "response_example": {
            "success": true,
            "message": "User logged out successfully"
          }
        },
        "status": {
          "method": "GET",
          "url": "/mikrotik/status/",
          "description": "Check MikroTik router status",
          "authentication": "Required",
          "request_example": {
            "javascript": `fetch('/mikrotik/status/', {
              method: 'GET',
              headers: {
                'Authorization': 'Bearer YOUR_ADMIN_TOKEN'
              }
            })`
          },
          "response_example": {
            "success": true,
            "router_ip": "192.168.0.173",
            "connection_status": "connected",
            "hotspot_name": "kitonga-hotspot",
            "active_users": 5
          }
        }
      },
      "admin_management": {
        "dashboard_stats": {
          "method": "GET",
          "url": "/dashboard-stats/",
          "description": "Get dashboard statistics",
          "authentication": "Required",
          "request_example": {
            "javascript": `fetch('/dashboard-stats/', {
              method: 'GET',
              headers: {
                'Authorization': 'Bearer YOUR_ADMIN_TOKEN'
              }
            })`
          },
          "response_example": {
            "total_users": 150,
            "active_users": 25,
            "total_payments": 75000,
            "today_revenue": 15000,
            "pending_payments": 3,
            "vouchers_available": 20,
            "recent_payments": [
              {
                "phone_number": "255700000000",
                "amount": 1000,
                "date": "2025-10-27T15:30:00Z",
                "status": "COMPLETED"
              }
            ]
          }
        },
        "webhook_logs": {
          "method": "GET",
          "url": "/webhook-logs/",
          "description": "Get payment webhook logs",
          "authentication": "Required",
          "request_example": {
            "javascript": `fetch('/webhook-logs/', {
              method: 'GET',
              headers: {
                'Authorization': 'Bearer YOUR_ADMIN_TOKEN'
              }
            })`
          },
          "response_example": [
            {
              "id": 1,
              "payment_reference": "PAY-12345-67890",
              "payment_status": "COMPLETED",
              "amount": 1000,
              "phone_number": "255700000000",
              "webhook_data": {...},
              "processed_at": "2025-10-27T16:00:00Z"
            }
          ]
        },
        "force_logout": {
          "method": "POST",
          "url": "/force-logout/",
          "description": "Force logout a user (Admin only)",
          "authentication": "Required",
          "request_example": {
            "javascript": `fetch('/force-logout/', {
              method: 'POST',
              headers: {
                'Authorization': 'Bearer YOUR_ADMIN_TOKEN',
                'Content-Type': 'application/json'
              },
              body: JSON.stringify({
                "phone_number": "255700000000"
              })
            })`,
            "body": {
              "phone_number": "255700000000"
            }
          },
          "response_example": {
            "success": true,
            "message": "User logged out successfully",
            "mikrotik_response": "Logout successful"
          }
        }
      }
    },
    "error_responses": {
      "description": "Common error response formats",
      "examples": {
        "validation_error": {
          "error": "Validation failed",
          "details": {
            "phone_number": ["This field is required."]
          }
        },
        "authentication_error": {
          "error": "Authentication required",
          "message": "Invalid or missing authentication token"
        },
        "not_found": {
          "error": "Not found",
          "message": "The requested resource was not found"
        },
        "payment_error": {
          "error": "Payment failed",
          "message": "Payment could not be processed",
          "code": "PAYMENT_FAILED"
        }
      }
    },
    "frontend_integration_examples": {
      "vanilla_javascript": {
        "description": "Example implementations using vanilla JavaScript",
        "user_login_flow": `
// Complete user Wi-Fi access flow
async function requestWiFiAccess(phoneNumber, macAddress) {
  try {
    // 1. Check user status
    const statusResponse = await fetch(\`/user-status/\${phoneNumber}/\`);
    const status = await statusResponse.json();
    
    if (status.has_access) {
      // User already has access
      return { success: true, message: 'Access already granted' };
    }
    
    // 2. Get available bundles
    const bundlesResponse = await fetch('/bundles/');
    const bundles = await bundlesResponse.json();
    
    // 3. Initiate payment for default bundle
    const paymentResponse = await fetch('/initiate-payment/', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        phone_number: phoneNumber,
        bundle_id: bundles[0].id,
        mac_address: macAddress
      })
    });
    
    const payment = await paymentResponse.json();
    
    if (payment.success) {
      // Redirect to payment or show payment reference
      window.location.href = payment.redirect_url;
    }
    
    return payment;
  } catch (error) {
    console.error('Wi-Fi access request failed:', error);
    return { success: false, error: error.message };
  }
}`,
        "admin_dashboard": `
// Admin dashboard data fetching
async function loadDashboard() {
  try {
    const response = await fetch('/dashboard-stats/', {
      headers: {
        'Authorization': 'Bearer ' + localStorage.getItem('admin_token')
      }
    });
    
    if (!response.ok) {
      throw new Error('Failed to load dashboard');
    }
    
    const stats = await response.json();
    
    // Update dashboard UI
    document.getElementById('total-users').textContent = stats.total_users;
    document.getElementById('active-users').textContent = stats.active_users;
    document.getElementById('today-revenue').textContent = stats.today_revenue;
    
    return stats;
  } catch (error) {
    console.error('Dashboard load failed:', error);
  }
}`
      },
      "react_examples": {
        "description": "Example React hooks and components",
        "user_status_hook": `
// Custom React hook for user status
import { useState, useEffect } from 'react';

export const useUserStatus = (phoneNumber) => {
  const [status, setStatus] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  
  useEffect(() => {
    const fetchStatus = async () => {
      try {
        const response = await fetch(\`/user-status/\${phoneNumber}/\`);
        const data = await response.json();
        setStatus(data);
      } catch (err) {
        setError(err.message);
      } finally {
        setLoading(false);
      }
    };
    
    if (phoneNumber) {
      fetchStatus();
    }
  }, [phoneNumber]);
  
  return { status, loading, error };
};`,
        "payment_component": `
// React payment component
import React, { useState } from 'react';

export const PaymentForm = ({ phoneNumber, macAddress }) => {
  const [bundles, setBundles] = useState([]);
  const [loading, setLoading] = useState(false);
  
  const handlePayment = async (bundleId) => {
    setLoading(true);
    try {
      const response = await fetch('/initiate-payment/', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          phone_number: phoneNumber,
          bundle_id: bundleId,
          mac_address: macAddress
        })
      });
      
      const result = await response.json();
      if (result.success) {
        window.location.href = result.redirect_url;
      }
    } catch (error) {
      console.error('Payment failed:', error);
    } finally {
      setLoading(false);
    }
  };
  
  return (
    <div className="payment-form">
      {bundles.map(bundle => (
        <button 
          key={bundle.id}
          onClick={() => handlePayment(bundle.id)}
          disabled={loading}
        >
          {bundle.name} - TSh {bundle.price}
        </button>
      ))}
    </div>
  );
};`
      }
    },
    "common_patterns": {
      "error_handling": `
// Robust error handling pattern
async function apiRequest(url, options = {}) {
  try {
    const response = await fetch(url, {
      headers: {
        'Content-Type': 'application/json',
        ...options.headers
      },
      ...options
    });
    
    if (!response.ok) {
      const errorData = await response.json();
      throw new Error(errorData.message || 'Request failed');
    }
    
    return await response.json();
  } catch (error) {
    console.error('API request failed:', error);
    throw error;
  }
}`,
      "authentication": `
// Authentication helper
class AuthManager {
  static setToken(token) {
    localStorage.setItem('admin_token', token);
  }
  
  static getToken() {
    return localStorage.getItem('admin_token');
  }
  
  static clearToken() {
    localStorage.removeItem('admin_token');
  }
  
  static isAuthenticated() {
    return !!this.getToken();
  }
  
  static getAuthHeaders() {
    const token = this.getToken();
    return token ? { 'Authorization': \`Bearer \${token}\` } : {};
  }
}`,
      "polling_payment_status": `
// Poll payment status until completion
async function pollPaymentStatus(orderReference, maxAttempts = 30) {
  for (let attempt = 0; attempt < maxAttempts; attempt++) {
    try {
      const response = await fetch(\`/payment-status/\${orderReference}/\`);
      const status = await response.json();
      
      if (status.payment_status === 'COMPLETED') {
        return { success: true, ...status };
      }
      
      if (status.payment_status === 'FAILED') {
        return { success: false, ...status };
      }
      
      // Wait 10 seconds before next check
      await new Promise(resolve => setTimeout(resolve, 10000));
    } catch (error) {
      console.error('Payment status check failed:', error);
    }
  }
  
  return { success: false, error: 'Payment status check timeout' };
}`
    }
  }
}
