<?php
require_once __DIR__ . '/../includes/header.php';
$pdo = db();

$success = $error = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!csrf_check($_POST['csrf_token'] ?? null)) {
        $error = 'Token inválido.';
    } else {
        $action = $_POST['action'] ?? '';
        if ($action === 'create') {
            $name = trim($_POST['name'] ?? '');
            if (!$name || mb_strlen($name) > 100) {
                $error = 'Nome inválido.';
            } else {
                $token = bin2hex(random_bytes(32));
                $pdo->prepare("INSERT INTO api_tokens (user_id, name, token) VALUES (?, ?, ?)")
                    ->execute([$user['id'], $name, $token]);
                $success = "Token criado com sucesso! Guarde-o agora — ele não será exibido novamente:";
                $newToken = $token;
            }
        } elseif ($action === 'revoke') {
            $tokenId = (int)($_POST['token_id'] ?? 0);
            if ($tokenId) {
                $pdo->prepare("UPDATE api_tokens SET active = FALSE WHERE id = ? AND user_id = ?")->execute([$tokenId, $user['id']]);
                $success = 'Token revogado.';
                redirect('index.php?page=user_api_tokens&ok=1');
            }
        } elseif ($action === 'delete') {
            $tokenId = (int)($_POST['token_id'] ?? 0);
            if ($tokenId) {
                $pdo->prepare("DELETE FROM api_tokens WHERE id = ? AND user_id = ?")->execute([$tokenId, $user['id']]);
                $success = 'Token removido.';
                redirect('index.php?page=user_api_tokens&ok=1');
            }
        }
    }
}
if (isset($_GET['ok'])) $success = 'Operação realizada!';

$tokens = $pdo->prepare("
    SELECT * FROM api_tokens WHERE user_id = ? ORDER BY created_at DESC
");
$tokens->execute([$user['id']]);
$tokens = $tokens->fetchAll();

$baseUrl = rtrim(app_base_url(), '/');
?>

<div class="card">
    <div class="card-head">
        <div>
            <h2>🔑 Tokens de API</h2>
            <p>Gere tokens para acessar a API REST do MonitorPing programaticamente.</p>
        </div>
        <a href="<?php echo BASE_URL; ?>api_public.php" target="_blank" class="ghost-button">📖 Ver documentação da API</a>
    </div>

    <?php if (isset($newToken)): ?>
    <div style="background:#f0fdf4;border:2px solid #22c55e;border-radius:12px;padding:16px;margin-bottom:20px;">
        <div style="display:flex;align-items:center;gap:8px;margin-bottom:8px;color:#15803d;font-weight:600;">
            <span>✅</span> Token criado com sucesso! Copie agora:
        </div>
        <div style="display:flex;gap:8px;align-items:center;">
            <code id="newTokenVal" style="flex:1;background:#fff;border:1px solid #bbf7d0;border-radius:8px;padding:10px 14px;font-size:13px;word-break:break-all;"><?php echo h($newToken); ?></code>
            <button onclick="navigator.clipboard.writeText('<?php echo $newToken; ?>');this.textContent='✓ Copiado!';setTimeout(()=>this.textContent='Copiar',2000);"
                    class="primary-button" style="white-space:nowrap;">Copiar</button>
        </div>
        <p style="font-size:12px;color:#16a34a;margin:8px 0 0;">⚠️ Este token não será exibido novamente. Guarde-o em um local seguro.</p>
    </div>
    <?php endif; ?>

    <?php if ($success && !isset($newToken)): ?><div class="alert alert-success"><?php echo h($success); ?></div><?php endif; ?>
    <?php if ($error): ?><div class="alert alert-error"><?php echo h($error); ?></div><?php endif; ?>

    <!-- Criar novo token -->
    <form method="POST" style="display:flex;gap:10px;align-items:flex-end;margin-bottom:24px;flex-wrap:wrap;">
        <input type="hidden" name="csrf_token" value="<?php echo csrf_token(); ?>">
        <input type="hidden" name="action" value="create">
        <div style="flex:1;min-width:200px;">
            <label style="display:block;font-size:13px;font-weight:600;margin-bottom:4px;">Nome do token</label>
            <input type="text" name="name" maxlength="100" placeholder="Ex: Grafana, Script de backup, n8n..." required
                   style="width:100%;padding:9px 12px;border:1px solid var(--border);border-radius:8px;background:var(--bg-card);color:var(--text-primary);font-size:14px;">
        </div>
        <button type="submit" class="primary-button">+ Gerar token</button>
    </form>

    <!-- Lista de tokens -->
    <?php if (empty($tokens)): ?>
        <div style="text-align:center;padding:40px;color:var(--text-secondary);">
            <div style="font-size:48px;margin-bottom:12px;">🔑</div>
            <p>Nenhum token criado ainda.</p>
        </div>
    <?php else: ?>
        <table>
            <thead>
                <tr>
                    <th>Nome</th>
                    <th>Criado em</th>
                    <th>Último uso</th>
                    <th>Status</th>
                    <th>Ações</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($tokens as $tok): ?>
                <tr>
                    <td><strong><?php echo h($tok['name']); ?></strong></td>
                    <td><?php echo format_datetime_tz($tok['created_at'], $user['timezone'] ?? null, 'd/m/Y H:i'); ?></td>
                    <td><?php echo $tok['last_used_at'] ? format_datetime_tz($tok['last_used_at'], $user['timezone'] ?? null, 'd/m/Y H:i') : '—'; ?></td>
                    <td>
                        <?php if ($tok['active']): ?>
                            <span class="status-online">● Ativo</span>
                        <?php else: ?>
                            <span class="status-offline">✕ Revogado</span>
                        <?php endif; ?>
                    </td>
                    <td>
                        <div style="display:flex;gap:6px;flex-wrap:wrap;">
                            <?php if ($tok['active']): ?>
                            <form method="POST" onsubmit="return confirm('Revogar este token?');" style="display:inline;">
                                <input type="hidden" name="csrf_token" value="<?php echo csrf_token(); ?>">
                                <input type="hidden" name="action" value="revoke">
                                <input type="hidden" name="token_id" value="<?php echo $tok['id']; ?>">
                                <button type="submit" class="ghost-button" style="padding:4px 10px;font-size:12px;color:var(--warning);">Revogar</button>
                            </form>
                            <?php endif; ?>
                            <form method="POST" onsubmit="return confirm('Remover token permanentemente?');" style="display:inline;">
                                <input type="hidden" name="csrf_token" value="<?php echo csrf_token(); ?>">
                                <input type="hidden" name="action" value="delete">
                                <input type="hidden" name="token_id" value="<?php echo $tok['id']; ?>">
                                <button type="submit" class="ghost-button" style="padding:4px 10px;font-size:12px;color:var(--danger);">Remover</button>
                            </form>
                        </div>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    <?php endif; ?>
</div>

<!-- Documentação inline da API -->
<div class="card">
    <h3>Como usar a API</h3>
    <p style="margin-bottom:16px;">Use o token no header <code>Authorization: Bearer SEU_TOKEN</code></p>

    <div style="display:grid;gap:12px;">
        <?php $apiBase = $baseUrl . '/api_public.php'; ?>
        <?php foreach ([
            ['GET', '/hosts', 'Lista todos os hosts do usuário'],
            ['GET', '/hosts?status=offline', 'Filtra hosts offline'],
            ['GET', '/hosts?tag=servidores', 'Filtra por tag'],
            ['GET', '/hosts/{id}', 'Detalhe de um host com uptime 24h'],
            ['GET', '/hosts/{id}/logs?hours=24', 'Logs de ping das últimas 24h'],
            ['GET', '/stats', 'Estatísticas gerais (uptime, contagens)'],
            ['GET', '/tags', 'Lista de tags'],
        ] as [$method, $path, $desc]): ?>
        <div style="background:var(--bg-main);border:1px solid var(--border);border-radius:10px;padding:12px 16px;">
            <div style="display:flex;align-items:center;gap:10px;margin-bottom:4px;">
                <span style="background:#2563eb;color:#fff;padding:2px 8px;border-radius:4px;font-size:11px;font-weight:700;"><?php echo $method; ?></span>
                <code style="font-size:13px;"><?php echo h($apiBase . $path); ?></code>
            </div>
            <p style="margin:0;font-size:12px;color:var(--text-secondary);"><?php echo h($desc); ?></p>
        </div>
        <?php endforeach; ?>
    </div>

    <div style="margin-top:16px;padding:12px 16px;background:var(--bg-main);border-radius:10px;border:1px solid var(--border);">
        <p style="margin:0;font-size:13px;"><strong>Exemplo com curl:</strong></p>
        <code style="display:block;margin-top:8px;font-size:12px;white-space:pre-wrap;">curl -H "Authorization: Bearer SEU_TOKEN" \
     <?php echo h($baseUrl); ?>/api_public.php/stats</code>
    </div>
</div>

<?php require_once __DIR__ . '/../includes/footer.php'; ?>
