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

if (!isset($_SESSION['logado'], $_SESSION['usuario_id'], $_SESSION['tenant_id']) || $_SESSION['logado'] !== true) {
    header('Location: login.php');
    exit;
}

$tenantId = (int) $_SESSION['tenant_id'];
require_once 'conexao.php';

// Processar formulários
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['gerar_key'])) {
        $nome = $_POST['nome'] ?? 'API Key';
        $diasExpiracao = isset($_POST['dias_expiracao']) ? (int)$_POST['dias_expiracao'] : null;
        $permissoes = $_POST['permissoes'] ?? ['clientes' => ['GET', 'POST', 'PUT', 'DELETE']];
        
        // Gerar API Key única
        $apiKey = bin2hex(random_bytes(32));
        
        $dataExpiracao = null;
        if ($diasExpiracao > 0) {
            $dataExpiracao = date('Y-m-d H:i:s', strtotime("+$diasExpiracao days"));
        }
        
        $stmt = $conn->prepare("
            INSERT INTO api_keys (tenant_id, nome, api_key, permissoes, data_expiracao)
            VALUES (?, ?, ?, ?, ?)
        ");
        $permissoesJson = json_encode($permissoes);
        $stmt->bind_param("issss", $tenantId, $nome, $apiKey, $permissoesJson, $dataExpiracao);
        
        if ($stmt->execute()) {
            $_SESSION['mensagem'] = 'API Key gerada com sucesso!';
            $_SESSION['nova_api_key'] = $apiKey; // Mostrar apenas uma vez
        } else {
            $_SESSION['mensagem'] = 'Erro ao gerar API Key';
            $_SESSION['tipo_mensagem'] = 'erro';
        }
        $stmt->close();
    }
    
    if (isset($_POST['revogar'])) {
        $keyId = (int)$_POST['key_id'];
        $stmt = $conn->prepare("UPDATE api_keys SET ativo = 0 WHERE id = ? AND tenant_id = ?");
        $stmt->bind_param("ii", $keyId, $tenantId);
        $stmt->execute();
        $stmt->close();
        
        $_SESSION['mensagem'] = 'API Key revogada com sucesso';
    }
    
    header('Location: gerenciar_api_keys.php');
    exit;
}

// Buscar API Keys do tenant
$stmt = $conn->prepare("
    SELECT id, nome, api_key, LEFT(api_key, 8) as key_prefix, 
           DATE_FORMAT(data_criacao, '%d/%m/%Y %H:%i') as data_criacao,
           DATE_FORMAT(data_expiracao, '%d/%m/%Y %H:%i') as data_expiracao,
           ultimo_uso, ativo, permissoes
    FROM api_keys 
    WHERE tenant_id = ? 
    ORDER BY ativo DESC, data_criacao DESC
");
$stmt->bind_param("i", $tenantId);
$stmt->execute();
$apiKeys = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
$stmt->close();

$conn->close();
?>
<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Gerenciar API Keys</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: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }
        .container {
            max-width: 1200px;
            margin: 0 auto;
        }
        .header {
            background: white;
            border-radius: 15px;
            padding: 25px;
            margin-bottom: 30px;
            box-shadow: 0 10px 40px rgba(0,0,0,0.1);
        }
        .header h1 {
            color: #333;
            font-size: 28px;
            margin-bottom: 10px;
        }
        .header p {
            color: #666;
            line-height: 1.6;
        }
        .card {
            background: white;
            border-radius: 15px;
            padding: 25px;
            margin-bottom: 30px;
            box-shadow: 0 5px 20px rgba(0,0,0,0.1);
        }
        .card h2 {
            color: #444;
            margin-bottom: 20px;
            display: flex;
            align-items: center;
            gap: 10px;
        }
        .form-group {
            margin-bottom: 20px;
        }
        .form-group label {
            display: block;
            margin-bottom: 8px;
            font-weight: 500;
            color: #555;
        }
        .form-group input, .form-group select {
            width: 100%;
            padding: 12px;
            border: 2px solid #e0e0e0;
            border-radius: 8px;
            font-size: 16px;
            transition: border-color 0.3s;
        }
        .form-group input:focus {
            border-color: #667eea;
            outline: none;
        }
        .btn {
            padding: 12px 24px;
            border: none;
            border-radius: 8px;
            font-size: 16px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s;
        }
        .btn-primary {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
        }
        .btn-primary:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(102, 126, 234, 0.4);
        }
        .btn-danger {
            background: #f56565;
            color: white;
        }
        .btn-danger:hover {
            background: #e53e3e;
        }
        .table {
            width: 100%;
            border-collapse: collapse;
        }
        .table th {
            background: #f7fafc;
            padding: 15px;
            text-align: left;
            font-weight: 600;
            color: #4a5568;
            border-bottom: 2px solid #e2e8f0;
        }
        .table td {
            padding: 15px;
            border-bottom: 1px solid #e2e8f0;
            color: #4a5568;
        }
        .badge {
            display: inline-block;
            padding: 5px 10px;
            border-radius: 20px;
            font-size: 12px;
            font-weight: 600;
        }
        .badge-success {
            background: #c6f6d5;
            color: #22543d;
        }
        .badge-danger {
            background: #fed7d7;
            color: #742a2a;
        }
        .api-key-display {
            background: #f7fafc;
            border: 2px dashed #667eea;
            border-radius: 10px;
            padding: 20px;
            margin: 20px 0;
            text-align: center;
        }
        .api-key-display .key {
            font-family: monospace;
            font-size: 24px;
            color: #667eea;
            background: white;
            padding: 15px;
            border-radius: 8px;
            border: 1px solid #e2e8f0;
            margin: 15px 0;
            word-break: break-all;
        }
        .alert {
            padding: 15px;
            border-radius: 8px;
            margin-bottom: 20px;
        }
        .alert-success {
            background: #c6f6d5;
            color: #22543d;
            border-left: 4px solid #48bb78;
        }
        .alert-warning {
            background: #feebc8;
            color: #744210;
            border-left: 4px solid #ed8936;
        }
        .copy-btn {
            background: #4299e1;
            color: white;
            border: none;
            padding: 8px 15px;
            border-radius: 6px;
            cursor: pointer;
            font-size: 14px;
            margin-left: 10px;
        }
        .copy-btn:hover {
            background: #3182ce;
        }
        .menu {
            background: white;
            border-radius: 10px;
            padding: 15px;
            margin-bottom: 20px;
            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;
        }
    </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" class="active"><i class="fas fa-key"></i> API Keys</a>
            <a href="documentacao_api.php"><i class="fas fa-book"></i> Documentação da API</a>
        </div>

        <div class="header">
            <h1><i class="fas fa-key" style="color: #667eea;"></i> Gerenciar API Keys</h1>
            <p>As API Keys permitem que sistemas externos se integrem com sua plataforma de forma segura. Cada chave é única por tenant e pode ter permissões específicas.</p>
        </div>

        <?php if (isset($_SESSION['mensagem'])): ?>
            <div class="alert alert-<?php echo $_SESSION['tipo_mensagem'] ?? 'success'; ?>">
                <i class="fas <?php echo $_SESSION['tipo_mensagem'] === 'erro' ? 'fa-exclamation-circle' : 'fa-check-circle'; ?>"></i>
                <?php echo $_SESSION['mensagem']; ?>
                <?php unset($_SESSION['mensagem'], $_SESSION['tipo_mensagem']); ?>
            </div>
        <?php endif; ?>

        <?php if (isset($_SESSION['nova_api_key'])): ?>
            <div class="api-key-display">
                <h3><i class="fas fa-exclamation-triangle" style="color: #ed8936;"></i> Guarde esta chave!</h3>
                <p>Esta é a única vez que a API Key será exibida. Copie e guarde em local seguro.</p>
                <div class="key" id="novaApiKey"><?php echo $_SESSION['nova_api_key']; ?></div>
                <button class="copy-btn" onclick="copiarChave()">
                    <i class="fas fa-copy"></i> Copiar Chave
                </button>
            </div>
            <?php unset($_SESSION['nova_api_key']); ?>
        <?php endif; ?>

        <div class="card">
            <h2><i class="fas fa-plus-circle" style="color: #48bb78;"></i> Gerar Nova API Key</h2>
            <form method="POST">
                <div class="form-group">
                    <label>Nome da Aplicação</label>
                    <input type="text" name="nome" placeholder="Ex: Sistema ERP, Aplicativo Mobile, Integração Shopify" required>
                </div>
                
                <div class="form-group">
                    <label>Expiração (dias) - Deixe em branco para não expirar</label>
                    <input type="number" name="dias_expiracao" placeholder="Ex: 30, 90, 365" min="1">
                </div>
                
                <div class="form-group">
                    <label>Permissões</label>
                    <select name="permissoes[clientes][]" multiple style="height: 120px;">
                        <option value="GET" selected>GET - Visualizar clientes</option>
                        <option value="POST" selected>POST - Criar clientes</option>
                        <option value="PUT" selected>PUT - Atualizar clientes</option>
                        <option value="DELETE" selected>DELETE - Excluir clientes</option>
                    </select>
                    <small style="color: #718096;">Segure Ctrl para selecionar múltiplas opções</small>
                </div>
                
                <button type="submit" name="gerar_key" class="btn btn-primary">
                    <i class="fas fa-key"></i> Gerar API Key
                </button>
            </form>
        </div>

        <div class="card">
            <h2><i class="fas fa-list"></i> Suas API Keys</h2>
            
            <?php if (empty($apiKeys)): ?>
                <p style="text-align: center; padding: 40px; color: #999;">
                    <i class="fas fa-info-circle" style="font-size: 48px; margin-bottom: 15px; display: block;"></i>
                    Nenhuma API Key gerada ainda.
                </p>
            <?php else: ?>
                <table class="table">
                    <thead>
                        <tr>
                            <th>Nome</th>
                            <th>API Key (prefixo)</th>
                            <th>Criada em</th>
                            <th>Expira em</th>
                            <th>Último uso</th>
                            <th>Status</th>
                            <th>Ações</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($apiKeys as $key): ?>
                            <tr>
                                <td><strong><?php echo htmlspecialchars($key['nome']); ?></strong></td>
                                <td>
                                    <code><?php echo $key['key_prefix']; ?>...XXXX</code>
                                </td>
                                <td><?php echo $key['data_criacao']; ?></td>
                                <td>
                                    <?php if ($key['data_expiracao']): ?>
                                        <?php echo $key['data_expiracao']; ?>
                                    <?php else: ?>
                                        <span style="color: #718096;">Não expira</span>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <?php if ($key['ultimo_uso']): ?>
                                        <?php echo date('d/m/Y H:i', strtotime($key['ultimo_uso'])); ?>
                                    <?php else: ?>
                                        <span style="color: #a0aec0;">Nunca usado</span>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <?php if ($key['ativo']): ?>
                                        <span class="badge badge-success">Ativa</span>
                                    <?php else: ?>
                                        <span class="badge badge-danger">Revogada</span>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <?php if ($key['ativo']): ?>
                                        <form method="POST" style="display: inline;" onsubmit="return confirm('Tem certeza que deseja revogar esta API Key?');">
                                            <input type="hidden" name="key_id" value="<?php echo $key['id']; ?>">
                                            <button type="submit" name="revogar" class="btn-danger" style="padding: 5px 10px; font-size: 12px;">
                                                <i class="fas fa-ban"></i> Revogar
                                            </button>
                                        </form>
                                    <?php endif; ?>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            <?php endif; ?>
        </div>

        <div class="card">
            <h2><i class="fas fa-rocket"></i> Como usar a API</h2>
            
            <h3 style="margin: 20px 0 10px;">Exemplo com cURL:</h3>
            <pre style="background: #2d3748; color: #e2e8f0; padding: 20px; border-radius: 8px; overflow-x: auto;">
# Listar clientes
curl -X GET "https://seudominio.com/api/clientes" \
  -H "X-API-Key: SUA_API_KEY_AQUI" \
  -H "X-Tenant-ID: SEU_TENANT_ID"

# Criar novo cliente
curl -X POST "https://seudominio.com/api/clientes" \
  -H "X-API-Key: SUA_API_KEY_AQUI" \
  -H "X-Tenant-ID: SEU_TENANT_ID" \
  -H "Content-Type: application/json" \
  -d '{
    "nome": "João Silva",
    "email": "joao@email.com",
    "telefone": "(11) 98765-4321",
    "cpf_cnpj": "123.456.789-09",
    "responsavel_id": 1
  }'

# Buscar cliente por ID
curl -X GET "https://seudominio.com/api/clientes/123" \
  -H "X-API-Key: SUA_API_KEY_AQUI" \
  -H "X-Tenant-ID: SEU_TENANT_ID"
            </pre>
        </div>
    </div>

    <script>
        function copiarChave() {
            var chave = document.getElementById('novaApiKey');
            var textarea = document.createElement('textarea');
            textarea.value = chave.innerText;
            document.body.appendChild(textarea);
            textarea.select();
            document.execCommand('copy');
            document.body.removeChild(textarea);
            
            alert('API Key copiada para a área de transferência!');
        }
    </script>
</body>
</html>