<?php
// documentacao_api.php
session_start();

if (!isset($_SESSION['logado'], $_SESSION['usuario_id'], $_SESSION['tenant_id']) || $_SESSION['logado'] !== true) {
    header('Location: login.php');
    exit;
}
?>
<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Documentação da API - SON</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, sans-serif;
            background: #f7fafc;
            line-height: 1.6;
        }
        .container {
            max-width: 1400px;
            margin: 0 auto;
            padding: 20px;
        }
        .header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 40px;
            border-radius: 20px;
            margin-bottom: 30px;
            box-shadow: 0 10px 40px rgba(0,0,0,0.1);
        }
        .header h1 {
            font-size: 2.5em;
            margin-bottom: 10px;
        }
        .header p {
            font-size: 1.2em;
            opacity: 0.95;
        }
        .menu {
            background: white;
            border-radius: 10px;
            padding: 15px;
            margin-bottom: 30px;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
            display: flex;
            gap: 20px;
        }
        .menu a {
            text-decoration: none;
            color: #4a5568;
            font-weight: 500;
            padding: 8px 15px;
            border-radius: 6px;
            transition: all 0.3s;
        }
        .menu a:hover {
            background: #f7fafc;
            color: #667eea;
        }
        .menu a.active {
            background: #667eea;
            color: white;
        }
        .doc-grid {
            display: grid;
            grid-template-columns: 280px 1fr;
            gap: 30px;
        }
        .sidebar {
            background: white;
            border-radius: 15px;
            padding: 25px;
            height: fit-content;
            position: sticky;
            top: 20px;
            box-shadow: 0 5px 20px rgba(0,0,0,0.05);
        }
        .sidebar h3 {
            color: #2d3748;
            margin-bottom: 20px;
            padding-bottom: 10px;
            border-bottom: 2px solid #e2e8f0;
        }
        .sidebar ul {
            list-style: none;
        }
        .sidebar li {
            margin-bottom: 10px;
        }
        .sidebar a {
            text-decoration: none;
            color: #4a5568;
            display: block;
            padding: 10px;
            border-radius: 8px;
            transition: all 0.3s;
        }
        .sidebar a:hover {
            background: #f7fafc;
            color: #667eea;
            padding-left: 15px;
        }
        .content {
            background: white;
            border-radius: 15px;
            padding: 40px;
            box-shadow: 0 5px 20px rgba(0,0,0,0.05);
        }
        .endpoint {
            margin-bottom: 50px;
            padding-bottom: 30px;
            border-bottom: 1px solid #e2e8f0;
        }
        .endpoint:last-child {
            border-bottom: none;
        }
        .endpoint h2 {
            color: #2d3748;
            margin-bottom: 20px;
            font-size: 1.8em;
        }
        .method {
            display: inline-block;
            padding: 5px 15px;
            border-radius: 20px;
            font-weight: 600;
            font-size: 14px;
            margin-right: 10px;
        }
        .method.get { background: #c6f6d5; color: #22543d; }
        .method.post { background: #bee3f8; color: #2c5282; }
        .method.put { background: #feebc8; color: #744210; }
        .method.delete { background: #fed7d7; color: #742a2a; }
        .path {
            font-family: monospace;
            font-size: 18px;
            color: #4a5568;
        }
        .description {
            margin: 15px 0;
            padding: 15px;
            background: #f7fafc;
            border-radius: 8px;
            border-left: 4px solid #667eea;
        }
        .code-block {
            background: #2d3748;
            color: #e2e8f0;
            padding: 20px;
            border-radius: 8px;
            overflow-x: auto;
            margin: 20px 0;
            font-family: 'Fira Code', monospace;
            font-size: 14px;
            position: relative;
        }
        .code-block pre {
            margin: 0;
        }
        .copy-btn {
            position: absolute;
            top: 10px;
            right: 10px;
            background: #4a5568;
            color: white;
            border: none;
            padding: 5px 10px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 12px;
        }
        .copy-btn:hover {
            background: #718096;
        }
        table {
            width: 100%;
            border-collapse: collapse;
            margin: 20px 0;
        }
        th {
            background: #f7fafc;
            padding: 12px;
            text-align: left;
            font-weight: 600;
            color: #2d3748;
            border-bottom: 2px solid #e2e8f0;
        }
        td {
            padding: 12px;
            border-bottom: 1px solid #e2e8f0;
        }
        .param-required {
            color: #e53e3e;
            font-size: 12px;
            margin-left: 5px;
        }
        .badge {
            display: inline-block;
            padding: 3px 8px;
            border-radius: 12px;
            font-size: 12px;
            font-weight: 600;
            margin-right: 5px;
        }
        .badge-blue { background: #bee3f8; color: #2c5282; }
        .badge-green { background: #c6f6d5; color: #22543d; }
        .badge-orange { background: #feebc8; color: #744210; }
        .badge-red { background: #fed7d7; color: #742a2a; }
        .response-example {
            margin-top: 20px;
        }
        .tab-container {
            margin: 20px 0;
        }
        .tab-buttons {
            display: flex;
            gap: 10px;
            border-bottom: 2px solid #e2e8f0;
            padding-bottom: 10px;
        }
        .tab-button {
            padding: 10px 20px;
            background: none;
            border: none;
            cursor: pointer;
            font-weight: 500;
            color: #718096;
            border-radius: 6px 6px 0 0;
        }
        .tab-button.active {
            color: #667eea;
            border-bottom: 2px solid #667eea;
        }
        .tab-content {
            display: none;
            padding: 20px 0;
        }
        .tab-content.active {
            display: block;
        }
        .info-box {
            background: #ebf8ff;
            border-left: 4px solid #4299e1;
            padding: 20px;
            border-radius: 8px;
            margin: 20px 0;
        }
        .info-box h4 {
            color: #2c5282;
            margin-bottom: 10px;
        }
        .info-box ul {
            margin-left: 20px;
        }
        .footer {
            text-align: center;
            padding: 40px;
            color: #718096;
            border-top: 1px solid #e2e8f0;
            margin-top: 40px;
        }
        @media (max-width: 1024px) {
            .doc-grid {
                grid-template-columns: 1fr;
            }
            .sidebar {
                position: static;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="menu">
            <a href="dashboard.php"><i class="fas fa-home"></i> Dashboard</a>
            <a href="lista_clientes.php"><i class="fas fa-users"></i> Clientes</a>
            <a href="gerenciar_api_keys.php"><i class="fas fa-key"></i> API Keys</a>
            <a href="documentacao_api.php" class="active"><i class="fas fa-book"></i> Documentação da API</a>
        </div>

        <div class="header">
            <h1><i class="fas fa-code"></i> API RESTful - Documentação Oficial</h1>
            <p>Integre seu sistema com nossa plataforma usando nossa API RESTful completa e segura.</p>
            <p>Versão: 1.0.0 | Base URL: <code style="background: rgba(255,255,255,0.2); padding: 5px 10px; border-radius: 4px;">https://seudominio.com/api/</code></p>
        </div>

        <div class="doc-grid">
            <div class="sidebar">
                <h3><i class="fas fa-list"></i> Conteúdo</h3>
                <ul>
                    <li><a href="#autenticacao">🔐 Autenticação</a></li>
                    <li><a href="#headers">📋 Headers</a></li>
                    <li><a href="#erros">⚠️ Tratamento de Erros</a></li>
                    <li><a href="#clientes">👥 Clientes</a>
                        <ul style="margin-left: 20px; margin-top: 5px;">
                            <li><a href="#listar-clientes">Listar Clientes</a></li>
                            <li><a href="#buscar-cliente">Buscar Cliente</a></li>
                            <li><a href="#criar-cliente">Criar Cliente</a></li>
                            <li><a href="#atualizar-cliente">Atualizar Cliente</a></li>
                            <li><a href="#excluir-cliente">Excluir Cliente</a></li>
                        </ul>
                    </li>
                    <li><a href="#exemplos">💻 Exemplos Práticos</a></li>
                    <li><a href="#limites">📊 Limites e Planos</a></li>
                </ul>
            </div>

            <div class="content">
                <section id="autenticacao" class="endpoint">
                    <h2>🔐 Autenticação</h2>
                    <div class="info-box">
                        <h4><i class="fas fa-shield-alt"></i> Sistema de Autenticação</h4>
                        <p>Todas as requisições à API devem incluir dois headers obrigatórios:</p>
                        <ul>
                            <li><code>X-API-Key</code> - Sua chave de API única (gerada no painel)</li>
                            <li><code>X-Tenant-ID</code> - ID do seu tenant (empresa/organização)</li>
                        </ul>
                    </div>

                    <div class="code-block">
                        <button class="copy-btn" onclick="copiarTexto(this)">Copiar</button>
                        <pre># Exemplo de headers
X-API-Key: a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6q7r8s9t0
X-Tenant-ID: 123</pre>
                    </div>

                    <table>
                        <tr>
                            <th>Código</th>
                            <th>Resposta</th>
                            <th>Descrição</th>
                        </tr>
                        <tr>
                            <td><span class="badge badge-red">401</span></td>
                            <td><code>{"erro": "API Key não fornecida"}</code></td>
                            <td>Header X-API-Key ausente</td>
                        </tr>
                        <tr>
                            <td><span class="badge badge-red">401</span></td>
                            <td><code>{"erro": "API Key inválida ou expirada"}</code></td>
                            <td>Chave inválida ou expirada</td>
                        </tr>
                        <tr>
                            <td><span class="badge badge-red">403</span></td>
                            <td><code>{"erro": "Tenant ID não corresponde"}</code></td>
                            <td>Tenant ID não bate com a chave</td>
                        </tr>
                    </table>
                </section>

                <section id="headers" class="endpoint">
                    <h2>📋 Headers da Requisição</h2>
                    <table>
                        <tr>
                            <th>Header</th>
                            <th>Obrigatório</th>
                            <th>Descrição</th>
                        </tr>
                        <tr>
                            <td><code>X-API-Key</code></td>
                            <td><span class="badge badge-red">Sim</span></td>
                            <td>Sua chave de API única</td>
                        </tr>
                        <tr>
                            <td><code>X-Tenant-ID</code></td>
                            <td><span class="badge badge-red">Sim</span></td>
                            <td>ID do seu tenant</td>
                        </tr>
                        <tr>
                            <td><code>Content-Type</code></td>
                            <td><span class="badge badge-red">Sim</span> (para POST/PUT)</td>
                            <td><code>application/json</code></td>
                        </tr>
                    </table>
                </section>

                <section id="erros" class="endpoint">
                    <h2>⚠️ Tratamento de Erros</h2>
                    <p>A API utiliza códigos HTTP padrão para indicar o resultado da operação:</p>
                    
                    <table>
                        <tr>
                            <th>Código</th>
                            <th>Significado</th>
                            <th>Descrição</th>
                        </tr>
                        <tr>
                            <td><span class="badge badge-green">200</span></td>
                            <td>OK</td>
                            <td>Requisição bem-sucedida</td>
                        </tr>
                        <tr>
                            <td><span class="badge badge-green">201</span></td>
                            <td>Created</td>
                            <td>Recurso criado com sucesso</td>
                        </tr>
                        <tr>
                            <td><span class="badge badge-orange">400</span></td>
                            <td>Bad Request</td>
                            <td>Dados inválidos ou campos obrigatórios ausentes</td>
                        </tr>
                        <tr>
                            <td><span class="badge badge-red">401</span></td>
                            <td>Unauthorized</td>
                            <td>Autenticação falhou</td>
                        </tr>
                        <tr>
                            <td><span class="badge badge-red">403</span></td>
                            <td>Forbidden</td>
                            <td>Sem permissão para o recurso</td>
                        </tr>
                        <tr>
                            <td><span class="badge badge-red">404</span></td>
                            <td>Not Found</td>
                            <td>Recurso não encontrado</td>
                        </tr>
                        <tr>
                            <td><span class="badge badge-red">409</span></td>
                            <td>Conflict</td>
                            <td>Conflito (ex: CPF duplicado)</td>
                        </tr>
                        <tr>
                            <td><span class="badge badge-red">500</span></td>
                            <td>Internal Server Error</td>
                            <td>Erro interno do servidor</td>
                        </tr>
                    </table>
                </section>

                <section id="clientes" class="endpoint">
                    <h2>👥 Endpoints de Clientes</h2>
                    
                    <div id="listar-clientes" style="margin-top: 30px;">
                        <h3>
                            <span class="method get">GET</span>
                            <span class="path">/clientes</span>
                        </h3>
                        <div class="description">
                            <i class="fas fa-info-circle"></i> Lista todos os clientes do tenant com paginação e filtros.
                        </div>

                        <h4>Parâmetros de Query (opcionais):</h4>
                        <table>
                            <tr>
                                <th>Parâmetro</th>
                                <th>Tipo</th>
                                <th>Descrição</th>
                            </tr>
                            <tr>
                                <td><code>page</code></td>
                                <td>integer</td>
                                <td>Número da página (padrão: 1)</td>
                            </tr>
                            <tr>
                                <td><code>limit</code></td>
                                <td>integer</td>
                                <td>Itens por página (padrão: 20, máximo: 100)</td>
                            </tr>
                            <tr>
                                <td><code>nome</code></td>
                                <td>string</td>
                                <td>Filtrar por nome (LIKE)</td>
                            </tr>
                            <tr>
                                <td><code>email</code></td>
                                <td>string</td>
                                <td>Filtrar por email exato</td>
                            </tr>
                            <tr>
                                <td><code>cpf_cnpj</code></td>
                                <td>string</td>
                                <td>Filtrar por CPF/CNPJ</td>
                            </tr>
                            <tr>
                                <td><code>funil_id</code></td>
                                <td>integer</td>
                                <td>Filtrar por funil</td>
                            </tr>
                            <tr>
                                <td><code>etapa_id</code></td>
                                <td>integer</td>
                                <td>Filtrar por etapa do funil</td>
                            </tr>
                            <tr>
                                <td><code>responsavel_id</code></td>
                                <td>integer</td>
                                <td>Filtrar por responsável</td>
                            </tr>
                        </table>

                        <div class="tab-container">
                            <div class="tab-buttons">
                                <button class="tab-button active" onclick="openTab(event, 'listar-curl')">cURL</button>
                                <button class="tab-button" onclick="openTab(event, 'listar-js')">JavaScript</button>
                                <button class="tab-button" onclick="openTab(event, 'listar-python')">Python</button>
                                <button class="tab-button" onclick="openTab(event, 'listar-php')">PHP</button>
                            </div>
                            
                            <div id="listar-curl" class="tab-content active">
                                <div class="code-block">
                                    <button class="copy-btn" onclick="copiarTexto(this)">Copiar</button>
                                    <pre>curl -X GET "https://seudominio.com/api/clientes?page=1&limit=20" \
  -H "X-API-Key: sua_api_key_aqui" \
  -H "X-Tenant-ID: 123"</pre>
                                </div>
                            </div>
                            
                            <div id="listar-js" class="tab-content">
                                <div class="code-block">
                                    <button class="copy-btn" onclick="copiarTexto(this)">Copiar</button>
                                    <pre>fetch('https://seudominio.com/api/clientes?page=1&limit=20', {
    headers: {
        'X-API-Key': 'sua_api_key_aqui',
        'X-Tenant-ID': '123'
    }
})
.then(response => response.json())
.then(data => console.log(data));</pre>
                                </div>
                            </div>
                            
                            <div id="listar-python" class="tab-content">
                                <div class="code-block">
                                    <button class="copy-btn" onclick="copiarTexto(this)">Copiar</button>
                                    <pre>import requests

headers = {
    'X-API-Key': 'sua_api_key_aqui',
    'X-Tenant-ID': '123'
}

response = requests.get(
    'https://seudominio.com/api/clientes',
    headers=headers,
    params={'page': 1, 'limit': 20}
)

print(response.json())</pre>
                                </div>
                            </div>
                            
                            <div id="listar-php" class="tab-content">
                                <div class="code-block">
                                    <button class="copy-btn" onclick="copiarTexto(this)">Copiar</button>
                                    <pre>$ch = curl_init('https://seudominio.com/api/clientes?page=1&limit=20');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'X-API-Key: sua_api_key_aqui',
    'X-Tenant-ID: 123'
]);

$response = curl_exec($ch);
curl_close($ch);

$data = json_decode($response, true);
print_r($data);</pre>
                                </div>
                            </div>
                        </div>

                        <h