<?php
/**
 * admin/api-documentation.php - Interactive API Documentation
 */

require_once __DIR__ . '/includes/base.php';

$breadcrumbs = [['title' => 'API Documentation', 'url' => '']];

renderAdminHeader('API Documentation', $breadcrumbs);
?>

<style>
.endpoint-card {
    border-left: 4px solid;
    transition: all 0.2s;
}
.endpoint-card:hover { box-shadow: 0 5px 15px rgba(0,0,0,0.1); }
.endpoint-card.get { border-left-color: #22c55e; }
.endpoint-card.post { border-left-color: #3b82f6; }
.endpoint-card.put { border-left-color: #f59e0b; }
.endpoint-card.delete { border-left-color: #ef4444; }
.code-block {
    background: #1e293b;
    color: #e2e8f0;
    padding: 1rem;
    border-radius: 8px;
    font-family: 'Courier New', monospace;
    font-size: 0.875rem;
}
</style>

<div class="d-flex justify-content-between align-items-center mb-4">
    <div>
        <h2 class="mb-1 fw-bold"><i class="bi bi-code-square me-2"></i>API Documentation</h2>
        <p class="text-muted mb-0">Interactive documentation for AIMS REST API</p>
    </div>
    <div class="d-flex gap-2">
        <button class="btn btn-outline-primary" onclick="downloadPostmanCollection()">
            <i class="bi bi-download me-2"></i>Postman Collection
        </button>
        <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#testApiModal">
            <i class="bi bi-play-circle me-2"></i>Test API
        </button>
    </div>
</div>

<!-- API Base Info -->
<div class="card border-0 shadow-sm mb-4">
    <div class="card-body">
        <div class="row">
            <div class="col-md-6">
                <h6 class="fw-bold mb-3">Base URL</h6>
                <div class="code-block mb-3">
                    <?php echo APP_URL; ?>/api/
                </div>
            </div>
            <div class="col-md-6">
                <h6 class="fw-bold mb-3">Authentication</h6>
                <div class="code-block mb-3">
                    Bearer Token (JWT) or Session Cookie
                </div>
            </div>
        </div>
    </div>
</div>

<!-- API Categories -->
<ul class="nav nav-tabs mb-4">
    <li class="nav-item">
        <a class="nav-link active" data-bs-toggle="tab" href="#auth">Authentication</a>
    </li>
    <li class="nav-item">
        <a class="nav-link" data-bs-toggle="tab" href="#users">Users</a>
    </li>
    <li class="nav-item">
        <a class="nav-link" data-bs-toggle="tab" href="#products">Products</a>
    </li>
    <li class="nav-item">
        <a class="nav-link" data-bs-toggle="tab" href="#orders">Orders</a>
    </li>
    <li class="nav-item">
        <a class="nav-link" data-bs-toggle="tab" href="#admin">Admin</a>
    </li>
</ul>

<div class="tab-content">
    <!-- Authentication Endpoints -->
    <div class="tab-pane fade show active" id="auth">
        <?php renderEndpoint('POST', '/api/auth.php?action=login', 'User Login', 
            ['phone_number' => 'string', 'password' => 'string'],
            ['success' => 'boolean', 'token' => 'string', 'user' => 'object']); ?>
        
        <?php renderEndpoint('POST', '/api/auth.php?action=register', 'User Registration',
            ['phone_number' => 'string', 'password' => 'string', 'full_name' => 'string', 'user_type' => 'enum'],
            ['success' => 'boolean', 'message' => 'string', 'user_id' => 'integer']); ?>
        
        <?php renderEndpoint('POST', '/api/auth.php?action=logout', 'User Logout',
            [],
            ['success' => 'boolean', 'message' => 'string']); ?>
        
        <?php renderEndpoint('POST', '/api/auth.php?action=forgot_password', 'Forgot Password',
            ['phone_number' => 'string'],
            ['success' => 'boolean', 'message' => 'string']); ?>
    </div>
    
    <!-- Users Endpoints -->
    <div class="tab-pane fade" id="users">
        <?php renderEndpoint('GET', '/api/users.php?action=get_profile&user_id={id}', 'Get User Profile',
            [],
            ['success' => 'boolean', 'data' => 'object']); ?>
        
        <?php renderEndpoint('PUT', '/api/users.php?action=update_profile', 'Update Profile',
            ['full_name' => 'string', 'email' => 'string', 'region_id' => 'integer'],
            ['success' => 'boolean', 'message' => 'string']); ?>
        
        <?php renderEndpoint('POST', '/api/users.php?action=upload_avatar', 'Upload Avatar',
            ['avatar' => 'file'],
            ['success' => 'boolean', 'avatar_url' => 'string']); ?>
        
        <?php renderEndpoint('GET', '/api/users.php?action=get_farmers', 'Get Farmers List',
            ['region_id' => 'integer (optional)', 'limit' => 'integer (optional)'],
            ['success' => 'boolean', 'data' => 'array']); ?>
    </div>
    
    <!-- Products Endpoints -->
    <div class="tab-pane fade" id="products">
        <?php renderEndpoint('GET', '/api/products.php?action=list', 'List Products',
            ['category' => 'string (optional)', 'search' => 'string (optional)', 'page' => 'integer'],
            ['success' => 'boolean', 'data' => 'array', 'total' => 'integer']); ?>
        
        <?php renderEndpoint('POST', '/api/products.php?action=create', 'Create Product',
            ['name' => 'string', 'description' => 'string', 'price' => 'decimal', 'quantity' => 'integer'],
            ['success' => 'boolean', 'product_id' => 'integer']); ?>
        
        <?php renderEndpoint('PUT', '/api/products.php?action=update&product_id={id}', 'Update Product',
            ['name' => 'string', 'price' => 'decimal', 'quantity' => 'integer'],
            ['success' => 'boolean', 'message' => 'string']); ?>
        
        <?php renderEndpoint('DELETE', '/api/products.php?action=delete&product_id={id}', 'Delete Product',
            [],
            ['success' => 'boolean', 'message' => 'string']); ?>
    </div>
    
    <!-- Orders Endpoints -->
    <div class="tab-pane fade" id="orders">
        <?php renderEndpoint('POST', '/api/orders.php?action=create', 'Create Order',
            ['product_id' => 'integer', 'quantity' => 'integer', 'delivery_address' => 'string'],
            ['success' => 'boolean', 'order_id' => 'integer']); ?>
        
        <?php renderEndpoint('GET', '/api/orders.php?action=list', 'Get Orders',
            ['status' => 'string (optional)', 'user_id' => 'integer (optional)'],
            ['success' => 'boolean', 'data' => 'array']); ?>
        
        <?php renderEndpoint('PUT', '/api/orders.php?action=update_status', 'Update Order Status',
            ['order_id' => 'integer', 'status' => 'enum(pending,processing,delivered)'],
            ['success' => 'boolean', 'message' => 'string']); ?>
    </div>
    
    <!-- Admin Endpoints -->
    <div class="tab-pane fade" id="admin">
        <?php renderEndpoint('POST', '/api/admin.php?action=approve_user', 'Approve User',
            ['user_id' => 'integer'],
            ['success' => 'boolean', 'message' => 'string']); ?>
        
        <?php renderEndpoint('GET', '/api/admin.php?action=get_analytics', 'Get Analytics',
            ['period' => 'string (daily|weekly|monthly)'],
            ['success' => 'boolean', 'data' => 'object']); ?>
        
        <?php renderEndpoint('POST', '/api/admin.php?action=block_ip', 'Block IP Address',
            ['ip_address' => 'string', 'reason' => 'string'],
            ['success' => 'boolean', 'message' => 'string']); ?>
    </div>
</div>

<!-- Test API Modal -->
<div class="modal fade" id="testApiModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Test API Endpoint</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div class="mb-3">
                    <label class="form-label">HTTP Method</label>
                    <select class="form-select" id="test_method">
                        <option value="GET">GET</option>
                        <option value="POST">POST</option>
                        <option value="PUT">PUT</option>
                        <option value="DELETE">DELETE</option>
                    </select>
                </div>
                
                <div class="mb-3">
                    <label class="form-label">Endpoint URL</label>
                    <input type="text" class="form-control" id="test_url" placeholder="/api/users.php?action=get_profile">
                </div>
                
                <div class="mb-3">
                    <label class="form-label">Request Body (JSON)</label>
                    <textarea class="form-control" id="test_body" rows="6" placeholder='{"key": "value"}'></textarea>
                </div>
                
                <button class="btn btn-primary w-100" onclick="testEndpoint()">
                    <i class="bi bi-play-fill me-2"></i>Send Request
                </button>
                
                <div id="test_response" class="mt-4" style="display: none;">
                    <h6 class="fw-bold">Response:</h6>
                    <div class="code-block" id="response_content"></div>
                </div>
            </div>
        </div>
    </div>
</div>

<?php
function renderEndpoint($method, $endpoint, $title, $params, $response) {
    $methodClass = strtolower($method);
    ?>
    <div class="card border-0 shadow-sm mb-3 endpoint-card <?php echo $methodClass; ?>">
        <div class="card-body">
            <div class="d-flex justify-content-between align-items-start mb-3">
                <div class="flex-grow-1">
                    <div class="d-flex align-items-center mb-2">
                        <span class="badge bg-<?php 
                            echo $method === 'GET' ? 'success' : 
                                ($method === 'POST' ? 'primary' : 
                                ($method === 'PUT' ? 'warning' : 'danger')); 
                        ?> me-2"><?php echo $method; ?></span>
                        <code class="text-dark"><?php echo $endpoint; ?></code>
                    </div>
                    <h6 class="mb-0"><?php echo $title; ?></h6>
                </div>
                <button class="btn btn-sm btn-outline-primary" onclick="copyEndpoint('<?php echo addslashes($endpoint); ?>')">
                    <i class="bi bi-clipboard"></i>
                </button>
            </div>
            
            <div class="row">
                <div class="col-md-6">
                    <h6 class="small fw-bold text-muted mb-2">REQUEST PARAMETERS</h6>
                    <div class="code-block">
<?php if (empty($params)): ?>
No parameters required
<?php else: ?>
{
<?php foreach ($params as $key => $type): ?>
  "<?php echo $key; ?>": <?php echo $type; ?><?php echo array_key_last($params) !== $key ? ',' : ''; ?>

<?php endforeach; ?>
}
<?php endif; ?>
                    </div>
                </div>
                <div class="col-md-6">
                    <h6 class="small fw-bold text-muted mb-2">RESPONSE FORMAT</h6>
                    <div class="code-block">
{
<?php foreach ($response as $key => $type): ?>
  "<?php echo $key; ?>": <?php echo $type; ?><?php echo array_key_last($response) !== $key ? ',' : ''; ?>

<?php endforeach; ?>
}
                    </div>
                </div>
            </div>
            
            <div class="mt-3">
                <button class="btn btn-sm btn-outline-secondary" onclick="tryEndpoint('<?php echo $method; ?>', '<?php echo addslashes($endpoint); ?>')">
                    <i class="bi bi-play-circle me-1"></i>Try it
                </button>
            </div>
        </div>
    </div>
    <?php
}
?>

<script>
function copyEndpoint(endpoint) {
    navigator.clipboard.writeText('<?php echo APP_URL; ?>' + endpoint);
    showToast('Endpoint copied to clipboard', 'success');
}

function tryEndpoint(method, endpoint) {
    $('#test_method').val(method);
    $('#test_url').val(endpoint);
    $('#testApiModal').modal('show');
}

function testEndpoint() {
    const method = $('#test_method').val();
    const url = '<?php echo APP_URL; ?>' + $('#test_url').val();
    let body = null;
    
    if (method !== 'GET') {
        try {
            body = JSON.parse($('#test_body').val() || '{}');
        } catch (e) {
            showToast('Invalid JSON in request body', 'error');
            return;
        }
    }
    
    $('#test_response').show();
    $('#response_content').html('<div class="spinner-border spinner-border-sm"></div> Sending request...');
    
    $.ajax({
        url: url,
        method: method,
        data: method === 'GET' ? null : JSON.stringify(body),
        contentType: 'application/json',
        success: function(response) {
            $('#response_content').html(JSON.stringify(response, null, 2));
        },
        error: function(xhr) {
            $('#response_content').html('Error: ' + xhr.status + '\n' + JSON.stringify(xhr.responseJSON || xhr.responseText, null, 2));
        }
    });
}

function downloadPostmanCollection() {
    const collection = {
        info: {
            name: 'AIMS API Collection',
            schema: 'https://schema.getpostman.com/json/collection/v2.1.0/collection.json'
        },
        item: [
            {
                name: 'Authentication',
                item: [
                    {
                        name: 'Login',
                        request: {
                            method: 'POST',
                            url: '<?php echo APP_URL; ?>/api/auth.php?action=login',
                            body: {
                                mode: 'raw',
                                raw: JSON.stringify({phone_number: '', password: ''})
                            }
                        }
                    }
                ]
            }
        ]
    };
    
    const blob = new Blob([JSON.stringify(collection, null, 2)], {type: 'application/json'});
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = 'AIMS_API_Collection.json';
    a.click();
}
</script>

<?php renderAdminFooter(); ?>