<?php
$isAdmin = isset($_SESSION['admin_logged_in']) && $_SESSION['admin_logged_in'] === true;

if ($isAdmin) {
    include __DIR__ . '/../../layouts/header.php';
    include __DIR__ . '/../../layouts/sidebar.php';
} else {
    ?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Developer API Documentation | HelperLink</title>
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
    <!-- FontAwesome -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        :root {
            --primary: #2F6BFF;
            --primary-light: #DCE8FF;
            --primary-hover: #2555CC;
            --bg-main: #F5F7FB;
            --card-bg: #FFFFFF;
            --text-primary: #111827;
            --text-secondary: #6B7280;
            --shadow-soft: 0 8px 24px rgba(0,0,0,0.05);
            --font-main: 'Inter', sans-serif;
        }
        body {
            background-color: var(--bg-main);
            font-family: var(--font-main);
            color: var(--text-primary);
        }
        .navbar-brand-custom {
            font-size: 22px;
            font-weight: 800;
            color: var(--primary);
            text-decoration: none;
            display: flex;
            align-items: center;
            gap: 10px;
        }
    </style>
</head>
<body>
    <!-- Public Header Navbar -->
    <nav class="navbar navbar-expand-lg bg-white border-bottom py-3 mb-4 sticky-top shadow-sm">
        <div class="container">
            <a class="navbar-brand-custom" href="#">
                <i class="fas fa-link"></i> HelperLink <span class="badge bg-primary-light text-primary font-monospace fw-semibold rounded-pill" style="font-size: 11px; padding: 5px 12px;">API DEV CENTER</span>
            </a>
            <div class="d-flex align-items-center gap-2">
                <a href="<?= defined('BASE_PATH') ? BASE_PATH : '' ?>/admin?page=login" class="btn btn-outline-primary rounded-pill px-4">
                    <i class="fas fa-sign-in-alt me-2"></i> Admin Portal
                </a>
            </div>
        </div>
    </nav>
    <div class="container py-2">
    <?php
}

// Dynamically load the API Collection
$apiCollectionPath = __DIR__ . '/../../../resources/docs/API_COLLECTION.json';
$apiData = [];
if (file_exists($apiCollectionPath)) {
    $apiData = json_decode(file_get_contents($apiCollectionPath), true);
}
?>

<div class="d-flex justify-content-between align-items-center mb-4">
    <div>
        <h2 class="mb-1">Developer API Docs</h2>
        <p class="text-secondary mb-0">Dynamic interactive API references parsed directly from the system Postman collection.</p>
    </div>
    <div>
        <a href="/helperlink/resources/docs/API_COLLECTION.json" download class="btn btn-primary rounded-4 px-4 py-2 shadow-sm">
            <i class="fas fa-file-download me-2"></i> Download Postman Collection
        </a>
    </div>
</div>

<div class="row g-4">
    <!-- Left Navigation Menu -->
    <div class="col-md-3">
        <div class="card border-0 shadow-sm rounded-4 p-3 position-sticky" style="top: 90px; max-height: calc(100vh - 120px); overflow-y: auto;">
            <h6 class="text-uppercase text-secondary fw-bold small px-2 mb-3">API Sections</h6>
            
            <?php if (!empty($apiData['item'])): ?>
                <div class="accordion accordion-flush" id="apiNavAccordion">
                    <?php foreach ($apiData['item'] as $index => $group): ?>
                        <?php $groupId = 'group_' . $index; ?>
                        <div class="accordion-item border-0 mb-2">
                            <h2 class="accordion-header" id="heading_<?= $groupId ?>">
                                <button class="accordion-button bg-light rounded-3 fw-semibold text-dark collapsed px-3 py-2" type="button" data-bs-toggle="collapse" data-bs-target="#collapse_<?= $groupId ?>" aria-expanded="true" aria-controls="collapse_<?= $groupId ?>">
                                    <i class="fas <?= $group['name'] === 'Customer' ? 'fa-user' : 'fa-building' ?> me-2 text-primary"></i>
                                    <?= htmlspecialchars($group['name']) ?> Portal
                                </button>
                            </h2>
                            <div id="collapse_<?= $groupId ?>" class="accordion-collapse collapse show" aria-labelledby="heading_<?= $groupId ?>" data-bs-parent="#apiNavAccordion">
                                <div class="accordion-body p-0 pt-2">
                                    <ul class="nav flex-column gap-1">
                                        <?php if (!empty($group['item'])): ?>
                                            <?php foreach ($group['item'] as $subIndex => $subGroup): ?>
                                                <li class="nav-item">
                                                    <span class="text-muted small fw-bold d-block px-3 py-1 text-uppercase" style="font-size: 11px;">
                                                        <?= htmlspecialchars($subGroup['name']) ?>
                                                    </span>
                                                    <ul class="nav flex-column ps-2">
                                                        <?php if (!empty($subGroup['item'])): ?>
                                                            <?php foreach ($subGroup['item'] as $endIndex => $endpoint): ?>
                                                                <?php 
                                                                $endpointId = 'ep_' . $index . '_' . $subIndex . '_' . $endIndex; 
                                                                $method = $endpoint['request']['method'] ?? 'GET';
                                                                $badgeClass = 'bg-primary';
                                                                if ($method === 'POST') $badgeClass = 'bg-success';
                                                                elseif ($method === 'PUT') $badgeClass = 'bg-warning text-dark';
                                                                elseif ($method === 'DELETE') $badgeClass = 'bg-danger';
                                                                ?>
                                                                <li class="nav-item">
                                                                    <a class="nav-link px-3 py-1.5 rounded-2 d-flex align-items-center justify-content-between text-decoration-none small text-dark hover-bg-light" href="#<?= $endpointId ?>" style="font-size: 13px;">
                                                                        <span class="text-truncate" style="max-width: 140px;"><?= htmlspecialchars($endpoint['name']) ?></span>
                                                                        <span class="badge <?= $badgeClass ?> font-monospace p-1" style="font-size: 9px; min-width: 45px; text-align: center;"><?= $method ?></span>
                                                                    </a>
                                                                </li>
                                                            <?php endforeach; ?>
                                                        <?php endif; ?>
                                                    </ul>
                                                </li>
                                            <?php endforeach; ?>
                                        <?php endif; ?>
                                    </ul>
                                </div>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
            <?php else: ?>
                <p class="text-muted text-center py-4">No endpoints found in API Collection file.</p>
            <?php endif; ?>
        </div>
    </div>

    <!-- Right Detailed Reference -->
    <div class="col-md-9">
        <div class="d-flex flex-column gap-4">
            <?php if (!empty($apiData['item'])): ?>
                <?php foreach ($apiData['item'] as $index => $group): ?>
                    <?php if (!empty($group['item'])): ?>
                        <?php foreach ($group['item'] as $subIndex => $subGroup): ?>
                            <?php if (!empty($subGroup['item'])): ?>
                                <?php foreach ($subGroup['item'] as $endIndex => $endpoint): ?>
                                    <?php 
                                    $endpointId = 'ep_' . $index . '_' . $subIndex . '_' . $endIndex; 
                                    $req = $endpoint['request'];
                                    $method = $req['method'] ?? 'GET';
                                    $url = is_array($req['url']) ? ($req['url']['raw'] ?? '') : $req['url'];
                                    
                                    // Method styles
                                    $badgeStyle = 'background: rgba(13, 110, 253, 0.1); color: #0d6efd;';
                                    $cardBorder = 'border-left: 5px solid #0d6efd;';
                                    if ($method === 'POST') {
                                        $badgeStyle = 'background: rgba(25, 135, 84, 0.1); color: #198754;';
                                        $cardBorder = 'border-left: 5px solid #198754;';
                                    } elseif ($method === 'PUT') {
                                        $badgeStyle = 'background: rgba(255, 193, 7, 0.15); color: #b58100;';
                                        $cardBorder = 'border-left: 5px solid #ffc107;';
                                    } elseif ($method === 'DELETE') {
                                        $badgeStyle = 'background: rgba(220, 53, 69, 0.1); color: #dc3545;';
                                        $cardBorder = 'border-left: 5px solid #dc3545;';
                                    }
                                    ?>
                                    <div class="card border-0 shadow-sm rounded-4 overflow-hidden" id="<?= $endpointId ?>" style="<?= $cardBorder ?> transition: transform 0.2s;">
                                        <div class="card-body p-4">
                                            <!-- Title & Badge -->
                                            <div class="d-flex align-items-center justify-content-between mb-3">
                                                <div class="d-flex align-items-center gap-3">
                                                    <span class="badge fw-bold px-3 py-2 rounded-3 text-uppercase font-monospace" style="<?= $badgeStyle ?> font-size: 14px;">
                                                        <?= $method ?>
                                                    </span>
                                                    <h4 class="mb-0 fw-bold text-dark"><?= htmlspecialchars($endpoint['name']) ?></h4>
                                                </div>
                                                <span class="text-secondary small fw-semibold text-uppercase bg-light px-3 py-1 rounded-pill" style="font-size: 11px;">
                                                    <?= htmlspecialchars($group['name']) ?> • <?= htmlspecialchars($subGroup['name']) ?>
                                                </span>
                                            </div>

                                            <!-- Raw URL -->
                                            <div class="bg-light p-3 rounded-3 mb-3 font-monospace d-flex align-items-center justify-content-between" style="font-size: 13.5px; border: 1px solid #e2e8f0;">
                                                <span class="text-dark overflow-auto pe-3"><?= htmlspecialchars($url) ?></span>
                                                <button class="btn btn-sm btn-link text-primary p-0 text-decoration-none copy-btn" data-clipboard-text="<?= htmlspecialchars($url) ?>" title="Copy URL">
                                                    <i class="far fa-copy"></i> Copy
                                                </button>
                                            </div>

                                            <!-- Headers -->
                                            <h6 class="fw-bold text-dark mb-2"><i class="fas fa-list-ul me-2 text-secondary"></i> Headers</h6>
                                            <div class="table-responsive mb-4">
                                                <table class="table table-sm table-bordered align-middle text-dark" style="font-size: 13px;">
                                                    <thead class="bg-light">
                                                        <tr>
                                                            <th>Header Name</th>
                                                            <th>Required Value</th>
                                                            <th>Description</th>
                                                        </tr>
                                                    </thead>
                                                    <tbody>
                                                        <tr>
                                                            <td class="font-monospace fw-semibold text-primary">Content-Type</td>
                                                            <td class="font-monospace text-muted">application/json</td>
                                                            <td>Informs server that request payload uses JSON structure.</td>
                                                        </tr>
                                                        <?php 
                                                        $hasAuth = false;
                                                        if (!empty($req['header'])) {
                                                            foreach ($req['header'] as $h) {
                                                                if (strtolower($h['key']) === 'authorization') $hasAuth = true;
                                                            }
                                                        }
                                                        if ($hasAuth || strpos($url, '/auth/login') === false && strpos($url, '/auth/register') === false && strpos($url, '/forgot-password') === false && strpos($url, '/reset-password') === false):
                                                        ?>
                                                            <tr>
                                                                <td class="font-monospace fw-semibold text-primary">Authorization</td>
                                                                <td class="font-monospace text-muted">Bearer {jwt_token}</td>
                                                                <td><span class="badge bg-danger rounded-pill px-2 py-1" style="font-size: 9px;">JWT Required</span> Access Token generated from login endpoint.</td>
                                                            </tr>
                                                        <?php endif; ?>
                                                    </tbody>
                                                </table>
                                            </div>

                                            <!-- Payload Request Body -->
                                            <?php if (!empty($req['body']['raw'])): ?>
                                                <div class="d-flex align-items-center justify-content-between mb-2">
                                                    <h6 class="fw-bold text-dark mb-0"><i class="fas fa-terminal me-2 text-secondary"></i> JSON Request Body</h6>
                                                    <button class="btn btn-sm btn-link text-primary p-0 text-decoration-none copy-btn" data-clipboard-text="<?= htmlspecialchars($req['body']['raw']) ?>">
                                                        <i class="far fa-copy"></i> Copy Body
                                                    </button>
                                                </div>
                                                <pre class="bg-dark text-light p-3 rounded-3 mb-0 overflow-auto font-monospace" style="font-size: 13px; max-height: 250px;"><?= htmlspecialchars($req['body']['raw']) ?></pre>
                                            <?php elseif (!empty($req['body']['formdata'])): ?>
                                                <h6 class="fw-bold text-dark mb-2"><i class="fas fa-paperclip me-2 text-secondary"></i> Multipart Form Data Fields</h6>
                                                <div class="table-responsive">
                                                    <table class="table table-sm table-bordered align-middle text-dark mb-0" style="font-size: 13px;">
                                                        <thead class="bg-light">
                                                            <tr>
                                                                <th>Field Key</th>
                                                                <th>Type</th>
                                                                <th>Example / Src</th>
                                                            </tr>
                                                        </thead>
                                                        <tbody>
                                                            <?php foreach ($req['body']['formdata'] as $fd): ?>
                                                                <tr>
                                                                    <td class="font-monospace fw-semibold"><?= htmlspecialchars($fd['key']) ?></td>
                                                                    <td><span class="badge bg-secondary font-monospace"><?= htmlspecialchars($fd['type'] ?? 'text') ?></span></td>
                                                                    <td class="text-secondary font-monospace"><?= htmlspecialchars($fd['value'] ?? 'File Upload Stream') ?></td>
                                                                </tr>
                                                            <?php endforeach; ?>
                                                        </tbody>
                                                    </table>
                                                </div>
                                            <?php else: ?>
                                                <p class="text-muted small mb-0"><i class="fas fa-info-circle me-1"></i> No request payload needed for this endpoint.</p>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        <?php endforeach; ?>
                    <?php endif; ?>
                <?php endforeach; ?>
            <?php endif; ?>
        </div>
    </div>
</div>

<script>
document.querySelectorAll('.copy-btn').forEach(btn => {
    btn.addEventListener('click', function(e) {
        e.preventDefault();
        const text = this.getAttribute('data-clipboard-text');
        navigator.clipboard.writeText(text).then(() => {
            const originalHTML = this.innerHTML;
            this.innerHTML = '<i class="fas fa-check text-success"></i> Copied!';
            setTimeout(() => {
                this.innerHTML = originalHTML;
            }, 2000);
        });
    });
});
</script>

<?php if ($isAdmin): ?>
    <?php include __DIR__ . '/../../layouts/footer.php'; ?>
<?php else: ?>
    </div> <!-- end container -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    </body>
    </html>
<?php endif; ?>
