<?php
/**
 * ============================================
 * PAINEL DE GATEWAYS - ADMINISTRAÇÃO
 * ============================================
 */

session_start();

// Configurações do painel
define('ADMIN_USER', 'maia');
define('ADMIN_PASS', 'carlinhos@2026'); // ALTERE ESTA SENHA!
define('GATEWAYS_FILE', __DIR__ . '/gateways.json');

// Verifica autenticação
$loggedIn = isset($_SESSION['admin_logged']) && $_SESSION['admin_logged'] === true;

// Processa login
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    header('Content-Type: application/json');
    
    if ($_POST['action'] === 'login') {
        $user = $_POST['user'] ?? '';
        $pass = $_POST['pass'] ?? '';
        
        if ($user === ADMIN_USER && $pass === ADMIN_PASS) {
            $_SESSION['admin_logged'] = true;
            echo json_encode(['success' => true]);
        } else {
            echo json_encode(['success' => false, 'error' => 'Credenciais inválidas']);
        }
        exit;
    }
    
    if ($_POST['action'] === 'logout') {
        session_destroy();
        echo json_encode(['success' => true]);
        exit;
    }
    
    // Ações que requerem login
    if (!$loggedIn) {
        echo json_encode(['success' => false, 'error' => 'Não autenticado']);
        exit;
    }
    
    if ($_POST['action'] === 'get_config') {
        $config = json_decode(file_get_contents(GATEWAYS_FILE), true);
        echo json_encode(['success' => true, 'config' => $config]);
        exit;
    }
    
    if ($_POST['action'] === 'save_config') {
        $config = json_decode($_POST['config'], true);
        if (!$config) {
            echo json_encode(['success' => false, 'error' => 'JSON inválido']);
            exit;
        }
        
        $config['updated_at'] = date('Y-m-d H:i:s');
        
        // Backup antes de salvar
        $backupFile = __DIR__ . '/backups/gateways_' . date('Y-m-d_H-i-s') . '.json';
        if (!is_dir(__DIR__ . '/backups')) {
            mkdir(__DIR__ . '/backups', 0755, true);
        }
        if (file_exists(GATEWAYS_FILE)) {
            copy(GATEWAYS_FILE, $backupFile);
        }
        
        $saved = file_put_contents(GATEWAYS_FILE, json_encode($config, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
        
        if ($saved) {
            echo json_encode(['success' => true, 'message' => 'Configuração salva com sucesso!']);
        } else {
            echo json_encode(['success' => false, 'error' => 'Erro ao salvar arquivo']);
        }
        exit;
    }
    
    if ($_POST['action'] === 'set_active') {
        $gateway = $_POST['gateway'] ?? '';
        $config = json_decode(file_get_contents(GATEWAYS_FILE), true);
        
        if (!isset($config['gateways'][$gateway])) {
            echo json_encode(['success' => false, 'error' => 'Gateway não encontrado']);
            exit;
        }
        
        $config['gateway_ativo'] = $gateway;
        $config['updated_at'] = date('Y-m-d H:i:s');
        
        file_put_contents(GATEWAYS_FILE, json_encode($config, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
        echo json_encode(['success' => true, 'message' => "Gateway '$gateway' ativado!"]);
        exit;
    }
    
    if ($_POST['action'] === 'test_gateway') {
        $gateway = $_POST['gateway'] ?? '';
        $config = json_decode(file_get_contents(GATEWAYS_FILE), true);
        
        if (!isset($config['gateways'][$gateway])) {
            echo json_encode(['success' => false, 'error' => 'Gateway não encontrado']);
            exit;
        }
        
        $gw = $config['gateways'][$gateway];
        
        // Testa conexão com a API
        $url = $gw['api_url'] . ($gw['endpoints']['pix_status'] ?: '/api/user/transactions');
        
        $ch = curl_init($url);
        curl_setopt_array($ch, [
            CURLOPT_HTTPHEADER => [
                'Content-Type: application/json',
                'User-Agent: ' . $gw['user_agent'],
                $gw['auth_header'] . ': ' . $gw['api_key']
            ],
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT => 10
        ]);
        
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $error = curl_error($ch);
        curl_close($ch);
        
        if ($error) {
            echo json_encode(['success' => false, 'error' => "Erro de conexão: $error"]);
        } elseif ($httpCode >= 200 && $httpCode < 500) {
            echo json_encode([
                'success' => true, 
                'message' => "Conexão OK! HTTP $httpCode",
                'http_code' => $httpCode
            ]);
        } else {
            echo json_encode(['success' => false, 'error' => "Erro HTTP: $httpCode"]);
        }
        exit;
    }
    
    if ($_POST['action'] === 'add_gateway') {
        $id = preg_replace('/[^a-z0-9_]/', '', strtolower($_POST['id'] ?? ''));
        $name = $_POST['name'] ?? '';
        
        if (!$id || !$name) {
            echo json_encode(['success' => false, 'error' => 'ID e Nome são obrigatórios']);
            exit;
        }
        
        $config = json_decode(file_get_contents(GATEWAYS_FILE), true);
        
        if (isset($config['gateways'][$id])) {
            echo json_encode(['success' => false, 'error' => 'Gateway já existe']);
            exit;
        }
        
        $config['gateways'][$id] = [
            'enabled' => false,
            'name' => $name,
            'api_url' => '',
            'api_key' => '',
            'webhook_secret' => '',
            'user_agent' => 'SmartCheckout/2.0',
            'auth_header' => 'x-api-key',
            'endpoints' => [
                'pix_create' => '/api/user/transactions',
                'pix_status' => '/api/user/transactions'
            ],
            'status_field' => 'data.status',
            'qrcode_field' => 'data.qrCode',
            'txid_field' => 'data.id'
        ];
        
        $config['updated_at'] = date('Y-m-d H:i:s');
        file_put_contents(GATEWAYS_FILE, json_encode($config, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
        
        echo json_encode(['success' => true, 'message' => "Gateway '$name' adicionado!"]);
        exit;
    }
    
    if ($_POST['action'] === 'delete_gateway') {
        $id = $_POST['id'] ?? '';
        $config = json_decode(file_get_contents(GATEWAYS_FILE), true);
        
        if (!isset($config['gateways'][$id])) {
            echo json_encode(['success' => false, 'error' => 'Gateway não encontrado']);
            exit;
        }
        
        if ($config['gateway_ativo'] === $id) {
            echo json_encode(['success' => false, 'error' => 'Não é possível excluir o gateway ativo']);
            exit;
        }
        
        unset($config['gateways'][$id]);
        $config['updated_at'] = date('Y-m-d H:i:s');
        file_put_contents(GATEWAYS_FILE, json_encode($config, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
        
        echo json_encode(['success' => true, 'message' => 'Gateway excluído!']);
        exit;
    }
    
    echo json_encode(['success' => false, 'error' => 'Ação inválida']);
    exit;
}

// Carrega config para exibição
$config = [];
if (file_exists(GATEWAYS_FILE)) {
    $config = json_decode(file_get_contents(GATEWAYS_FILE), true);
}
?>
<!DOCTYPE html>
<html lang="pt-BR">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Painel de Gateways</title>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
    <style>
        * { box-sizing: border-box; margin: 0; padding: 0; }
        body { font-family: 'Inter', sans-serif; background: #0f172a; color: #e2e8f0; min-height: 100vh; }
        
        .login-container {
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 20px;
        }
        
        .login-box {
            background: #1e293b;
            border-radius: 16px;
            padding: 40px;
            width: 100%;
            max-width: 400px;
            box-shadow: 0 25px 50px rgba(0,0,0,0.3);
        }
        
        .login-box h1 {
            font-size: 24px;
            margin-bottom: 8px;
            color: #f8fafc;
        }
        
        .login-box p {
            color: #94a3b8;
            margin-bottom: 24px;
        }
        
        .form-group {
            margin-bottom: 16px;
        }
        
        .form-group label {
            display: block;
            margin-bottom: 6px;
            font-weight: 500;
            color: #cbd5e1;
        }
        
        .form-group input, .form-group select, .form-group textarea {
            width: 100%;
            padding: 12px 16px;
            border: 2px solid #334155;
            border-radius: 8px;
            background: #0f172a;
            color: #f8fafc;
            font-size: 14px;
            transition: border-color 0.2s;
        }
        
        .form-group input:focus, .form-group select:focus, .form-group textarea:focus {
            outline: none;
            border-color: #3b82f6;
        }
        
        .btn {
            padding: 12px 24px;
            border: none;
            border-radius: 8px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.2s;
            font-size: 14px;
        }
        
        .btn-primary {
            background: #3b82f6;
            color: white;
            width: 100%;
        }
        
        .btn-primary:hover {
            background: #2563eb;
        }
        
        .btn-success {
            background: #22c55e;
            color: white;
        }
        
        .btn-success:hover {
            background: #16a34a;
        }
        
        .btn-danger {
            background: #ef4444;
            color: white;
        }
        
        .btn-danger:hover {
            background: #dc2626;
        }
        
        .btn-secondary {
            background: #475569;
            color: white;
        }
        
        .btn-secondary:hover {
            background: #64748b;
        }
        
        .btn-sm {
            padding: 8px 16px;
            font-size: 12px;
        }
        
        /* Dashboard */
        .dashboard { display: none; }
        .dashboard.active { display: block; }
        .login-container.hidden { display: none; }
        
        .header {
            background: #1e293b;
            padding: 16px 24px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            border-bottom: 1px solid #334155;
        }
        
        .header h1 {
            font-size: 20px;
            display: flex;
            align-items: center;
            gap: 10px;
        }
        
        .header h1 span {
            font-size: 24px;
        }
        
        .container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 24px;
        }
        
        .card {
            background: #1e293b;
            border-radius: 12px;
            padding: 24px;
            margin-bottom: 24px;
            border: 1px solid #334155;
        }
        
        .card-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            padding-bottom: 16px;
            border-bottom: 1px solid #334155;
        }
        
        .card-title {
            font-size: 18px;
            font-weight: 600;
        }
        
        .gateway-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
            gap: 20px;
        }
        
        .gateway-card {
            background: #0f172a;
            border-radius: 12px;
            padding: 20px;
            border: 2px solid #334155;
            transition: all 0.2s;
        }
        
        .gateway-card.active {
            border-color: #22c55e;
            box-shadow: 0 0 20px rgba(34, 197, 94, 0.2);
        }
        
        .gateway-card.disabled {
            opacity: 0.6;
        }
        
        .gateway-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 16px;
        }
        
        .gateway-name {
            font-size: 18px;
            font-weight: 700;
        }
        
        .gateway-badge {
            padding: 4px 10px;
            border-radius: 20px;
            font-size: 11px;
            font-weight: 600;
            text-transform: uppercase;
        }
        
        .badge-active {
            background: #22c55e;
            color: white;
        }
        
        .badge-inactive {
            background: #64748b;
            color: white;
        }
        
        .gateway-info {
            margin-bottom: 16px;
        }
        
        .gateway-info p {
            color: #94a3b8;
            font-size: 13px;
            margin-bottom: 8px;
            display: flex;
            align-items: center;
            gap: 8px;
        }
        
        .gateway-info strong {
            color: #cbd5e1;
        }
        
        .gateway-actions {
            display: flex;
            gap: 8px;
            flex-wrap: wrap;
        }
        
        .api-key-display {
            font-family: monospace;
            font-size: 12px;
            color: #94a3b8;
            word-break: break-all;
        }
        
        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0,0,0,0.8);
            align-items: center;
            justify-content: center;
            z-index: 1000;
            padding: 20px;
        }
        
        .modal.active {
            display: flex;
        }
        
        .modal-content {
            background: #1e293b;
            border-radius: 16px;
            padding: 32px;
            width: 100%;
            max-width: 600px;
            max-height: 90vh;
            overflow-y: auto;
        }
        
        .modal-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 24px;
        }
        
        .modal-title {
            font-size: 20px;
            font-weight: 600;
        }
        
        .modal-close {
            background: none;
            border: none;
            color: #94a3b8;
            font-size: 24px;
            cursor: pointer;
        }
        
        .modal-close:hover {
            color: #f8fafc;
        }
        
        .alert {
            padding: 12px 16px;
            border-radius: 8px;
            margin-bottom: 16px;
            font-size: 14px;
        }
        
        .alert-success {
            background: rgba(34, 197, 94, 0.2);
            border: 1px solid #22c55e;
            color: #22c55e;
        }
        
        .alert-error {
            background: rgba(239, 68, 68, 0.2);
            border: 1px solid #ef4444;
            color: #ef4444;
        }
        
        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 16px;
            margin-bottom: 24px;
        }
        
        .stat-card {
            background: #0f172a;
            border-radius: 12px;
            padding: 20px;
            border: 1px solid #334155;
        }
        
        .stat-label {
            color: #94a3b8;
            font-size: 13px;
            margin-bottom: 8px;
        }
        
        .stat-value {
            font-size: 28px;
            font-weight: 700;
            color: #f8fafc;
        }
        
        .stat-value.success { color: #22c55e; }
        .stat-value.warning { color: #f59e0b; }
        
        .two-cols {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 16px;
        }
        
        @media (max-width: 768px) {
            .two-cols { grid-template-columns: 1fr; }
            .gateway-grid { grid-template-columns: 1fr; }
        }
    </style>
</head>
<body>

<!-- Login -->
<div class="login-container <?php echo $loggedIn ? 'hidden' : ''; ?>" id="loginContainer">
    <div class="login-box">
        <h1>🔐 Painel Admin</h1>
        <p>Gerenciamento de Gateways de Pagamento</p>
        
        <div id="loginAlert"></div>
        
        <form id="loginForm">
            <div class="form-group">
                <label>Usuário</label>
                <input type="text" id="loginUser" required autocomplete="username">
            </div>
            <div class="form-group">
                <label>Senha</label>
                <input type="password" id="loginPass" required autocomplete="current-password">
            </div>
            <button type="submit" class="btn btn-primary">Entrar</button>
        </form>
    </div>
</div>

<!-- Dashboard -->
<div class="dashboard <?php echo $loggedIn ? 'active' : ''; ?>" id="dashboard">
    <header class="header">
        <h1><span>⚡</span> Painel de Gateways</h1>
        <button class="btn btn-secondary btn-sm" onclick="logout()">Sair</button>
    </header>
    
    <div class="container">
        <div id="alertContainer"></div>
        
        <!-- Stats -->
        <div class="stats-grid">
            <div class="stat-card">
                <div class="stat-label">Gateway Ativo</div>
                <div class="stat-value success" id="statGatewayAtivo">-</div>
            </div>
            <div class="stat-card">
                <div class="stat-label">Total de Gateways</div>
                <div class="stat-value" id="statTotalGateways">0</div>
            </div>
            <div class="stat-card">
                <div class="stat-label">Última Atualização</div>
                <div class="stat-value warning" id="statUpdatedAt" style="font-size: 16px;">-</div>
            </div>
        </div>
        
        <!-- Gateways -->
        <div class="card">
            <div class="card-header">
                <h2 class="card-title">🏦 Gateways Configurados</h2>
                <button class="btn btn-primary btn-sm" onclick="openAddModal()">+ Adicionar Gateway</button>
            </div>
            
            <div class="gateway-grid" id="gatewayGrid">
                <!-- Gateways serão inseridos aqui -->
            </div>
        </div>
        
        <!-- Status Map -->
        <div class="card">
            <div class="card-header">
                <h2 class="card-title">📊 Mapeamento de Status</h2>
                <button class="btn btn-secondary btn-sm" onclick="openStatusMapModal()">Editar</button>
            </div>
            <p style="color: #94a3b8; font-size: 14px;">
                Define como os status da API são convertidos para o sistema interno (paid, pending, expired, cancelled, refunded).
            </p>
        </div>
    </div>
</div>

<!-- Modal: Adicionar Gateway -->
<div class="modal" id="addModal">
    <div class="modal-content">
        <div class="modal-header">
            <h3 class="modal-title">➕ Adicionar Gateway</h3>
            <button class="modal-close" onclick="closeModal('addModal')">&times;</button>
        </div>
        
        <form id="addGatewayForm">
            <div class="two-cols">
                <div class="form-group">
                    <label>ID (slug)</label>
                    <input type="text" id="newGatewayId" placeholder="ex: novopay" required pattern="[a-z0-9_]+">
                </div>
                <div class="form-group">
                    <label>Nome</label>
                    <input type="text" id="newGatewayName" placeholder="ex: NovoPay" required>
                </div>
            </div>
            <button type="submit" class="btn btn-success">Adicionar</button>
        </form>
    </div>
</div>

<!-- Modal: Editar Gateway -->
<div class="modal" id="editModal">
    <div class="modal-content">
        <div class="modal-header">
            <h3 class="modal-title">✏️ Editar Gateway</h3>
            <button class="modal-close" onclick="closeModal('editModal')">&times;</button>
        </div>
        
        <form id="editGatewayForm">
            <input type="hidden" id="editGatewayId">
            
            <div class="two-cols">
                <div class="form-group">
                    <label>Nome</label>
                    <input type="text" id="editName" required>
                </div>
                <div class="form-group">
                    <label>Habilitado</label>
                    <select id="editEnabled">
                        <option value="true">Sim</option>
                        <option value="false">Não</option>
                    </select>
                </div>
            </div>
            
            <div class="form-group">
                <label>URL da API</label>
                <input type="url" id="editApiUrl" placeholder="https://api.gateway.com" required>
            </div>
            
            <div class="form-group">
                <label>API Key / Token</label>
                <input type="text" id="editApiKey" placeholder="sua-api-key-aqui" required>
            </div>
            
            <div class="two-cols">
                <div class="form-group">
                    <label>User-Agent</label>
                    <input type="text" id="editUserAgent" placeholder="SmartCheckout/2.0">
                </div>
                <div class="form-group">
                    <label>Tipo de Autenticação</label>
                    <select id="editAuthType">
                        <option value="apikey">API Key (Header)</option>
                        <option value="basic">Basic Auth (user:pass)</option>
                    </select>
                </div>
            </div>
            
            <div class="two-cols">
                <div class="form-group">
                    <label>Header de Auth</label>
                    <input type="text" id="editAuthHeader" placeholder="x-api-key ou Authorization">
                </div>
                <div class="form-group">
                    <label>Prefixo de Auth (opcional)</label>
                    <input type="text" id="editAuthPrefix" placeholder="Bearer (com espaço no final)">
                </div>
            </div>
            
            <div class="two-cols">
                <div class="form-group">
                    <label>Company ID (para Basic Auth)</label>
                    <input type="text" id="editCompanyId" placeholder="UUID do company">
                </div>
                <div class="form-group">
                    <label>Webhook Secret (opcional)</label>
                    <input type="text" id="editWebhookSecret" placeholder="secret-key">
                </div>
            </div>
            
            <div class="two-cols">
                <div class="form-group">
                    <label>Endpoint Criar PIX</label>
                    <input type="text" id="editEndpointCreate" placeholder="/api/user/transactions">
                </div>
                <div class="form-group">
                    <label>Endpoint Status PIX</label>
                    <input type="text" id="editEndpointStatus" placeholder="/api/user/transactions">
                </div>
            </div>
            
            <div class="form-group">
                <label>Campo do Status na Resposta</label>
                <input type="text" id="editStatusField" placeholder="data.status ou data.data[0].status">
            </div>
            
            <div class="two-cols">
                <div class="form-group">
                    <label>Campo do QR Code</label>
                    <input type="text" id="editQrcodeField" placeholder="data.qrCode">
                </div>
                <div class="form-group">
                    <label>Campo do ID da Transação</label>
                    <input type="text" id="editTxidField" placeholder="data.id">
                </div>
            </div>
            
            <div style="display: flex; gap: 12px; margin-top: 24px;">
                <button type="submit" class="btn btn-success">Salvar</button>
                <button type="button" class="btn btn-secondary" onclick="closeModal('editModal')">Cancelar</button>
            </div>
        </form>
    </div>
</div>

<!-- Modal: Status Map -->
<div class="modal" id="statusMapModal">
    <div class="modal-content">
        <div class="modal-header">
            <h3 class="modal-title">📊 Mapeamento de Status</h3>
            <button class="modal-close" onclick="closeModal('statusMapModal')">&times;</button>
        </div>
        
        <p style="color: #94a3b8; margin-bottom: 16px; font-size: 14px;">
            Edite o JSON abaixo para adicionar ou modificar mapeamentos de status.
        </p>
        
        <div class="form-group">
            <textarea id="statusMapJson" rows="15" style="font-family: monospace; font-size: 13px;"></textarea>
        </div>
        
        <div style="display: flex; gap: 12px;">
            <button class="btn btn-success" onclick="saveStatusMap()">Salvar</button>
            <button class="btn btn-secondary" onclick="closeModal('statusMapModal')">Cancelar</button>
        </div>
    </div>
</div>

<script>
let config = {};

// Login
document.getElementById('loginForm').addEventListener('submit', async (e) => {
    e.preventDefault();
    
    const formData = new FormData();
    formData.append('action', 'login');
    formData.append('user', document.getElementById('loginUser').value);
    formData.append('pass', document.getElementById('loginPass').value);
    
    const res = await fetch('', { method: 'POST', body: formData });
    const data = await res.json();
    
    if (data.success) {
        document.getElementById('loginContainer').classList.add('hidden');
        document.getElementById('dashboard').classList.add('active');
        loadConfig();
    } else {
        document.getElementById('loginAlert').innerHTML = 
            '<div class="alert alert-error">' + data.error + '</div>';
    }
});

async function logout() {
    const formData = new FormData();
    formData.append('action', 'logout');
    await fetch('', { method: 'POST', body: formData });
    location.reload();
}

// Carregar configuração
async function loadConfig() {
    const formData = new FormData();
    formData.append('action', 'get_config');
    
    const res = await fetch('', { method: 'POST', body: formData });
    const data = await res.json();
    
    if (data.success) {
        config = data.config;
        renderGateways();
        updateStats();
    }
}

function updateStats() {
    document.getElementById('statGatewayAtivo').textContent = 
        config.gateways[config.gateway_ativo]?.name || config.gateway_ativo;
    document.getElementById('statTotalGateways').textContent = 
        Object.keys(config.gateways || {}).length;
    document.getElementById('statUpdatedAt').textContent = 
        config.updated_at || '-';
}

function renderGateways() {
    const grid = document.getElementById('gatewayGrid');
    grid.innerHTML = '';
    
    for (const [id, gw] of Object.entries(config.gateways || {})) {
        const isActive = config.gateway_ativo === id;
        const isEnabled = gw.enabled !== false;
        
        const card = document.createElement('div');
        card.className = 'gateway-card' + (isActive ? ' active' : '') + (!isEnabled ? ' disabled' : '');
        
        card.innerHTML = `
            <div class="gateway-header">
                <span class="gateway-name">${gw.name}</span>
                <span class="gateway-badge ${isActive ? 'badge-active' : 'badge-inactive'}">
                    ${isActive ? 'ATIVO' : (isEnabled ? 'Disponível' : 'Desativado')}
                </span>
            </div>
            <div class="gateway-info">
                <p><strong>URL:</strong> ${gw.api_url || 'Não configurado'}</p>
                <p><strong>API Key:</strong> <span class="api-key-display">${maskApiKey(gw.api_key)}</span></p>
                <p><strong>User-Agent:</strong> ${gw.user_agent || '-'}</p>
            </div>
            <div class="gateway-actions">
                ${!isActive ? `<button class="btn btn-success btn-sm" onclick="setActive('${id}')">Ativar</button>` : ''}
                <button class="btn btn-primary btn-sm" onclick="editGateway('${id}')">Editar</button>
                <button class="btn btn-secondary btn-sm" onclick="testGateway('${id}')">Testar</button>
                ${!isActive ? `<button class="btn btn-danger btn-sm" onclick="deleteGateway('${id}')">Excluir</button>` : ''}
            </div>
        `;
        
        grid.appendChild(card);
    }
}

function maskApiKey(key) {
    if (!key) return 'Não configurado';
    if (key.length <= 10) return '****';
    return key.substring(0, 6) + '...' + key.substring(key.length - 4);
}

async function setActive(id) {
    const formData = new FormData();
    formData.append('action', 'set_active');
    formData.append('gateway', id);
    
    const res = await fetch('', { method: 'POST', body: formData });
    const data = await res.json();
    
    showAlert(data.success ? 'success' : 'error', data.message || data.error);
    if (data.success) loadConfig();
}

async function testGateway(id) {
    showAlert('success', 'Testando conexão...');
    
    const formData = new FormData();
    formData.append('action', 'test_gateway');
    formData.append('gateway', id);
    
    const res = await fetch('', { method: 'POST', body: formData });
    const data = await res.json();
    
    showAlert(data.success ? 'success' : 'error', data.message || data.error);
}

function editGateway(id) {
    const gw = config.gateways[id];
    if (!gw) return;
    
    document.getElementById('editGatewayId').value = id;
    document.getElementById('editName').value = gw.name || '';
    document.getElementById('editEnabled').value = gw.enabled !== false ? 'true' : 'false';
    document.getElementById('editApiUrl').value = gw.api_url || '';
    document.getElementById('editApiKey').value = gw.api_key || '';
    document.getElementById('editUserAgent').value = gw.user_agent || '';
    document.getElementById('editAuthType').value = gw.auth_type || 'apikey';
    document.getElementById('editAuthHeader').value = gw.auth_header || 'x-api-key';
    document.getElementById('editAuthPrefix').value = gw.auth_prefix || '';
    document.getElementById('editCompanyId').value = gw.company_id || '';
    document.getElementById('editEndpointCreate').value = gw.endpoints?.pix_create || '';
    document.getElementById('editEndpointStatus').value = gw.endpoints?.pix_status || '';
    document.getElementById('editStatusField').value = gw.status_field || '';
    document.getElementById('editQrcodeField').value = gw.qrcode_field || '';
    document.getElementById('editTxidField').value = gw.txid_field || '';
    document.getElementById('editWebhookSecret').value = gw.webhook_secret || '';
    
    openModal('editModal');
}

document.getElementById('editGatewayForm').addEventListener('submit', async (e) => {
    e.preventDefault();
    
    const id = document.getElementById('editGatewayId').value;
    
    config.gateways[id] = {
        ...config.gateways[id],
        name: document.getElementById('editName').value,
        enabled: document.getElementById('editEnabled').value === 'true',
        api_url: document.getElementById('editApiUrl').value,
        api_key: document.getElementById('editApiKey').value,
        user_agent: document.getElementById('editUserAgent').value,
        auth_type: document.getElementById('editAuthType').value,
        auth_header: document.getElementById('editAuthHeader').value,
        auth_prefix: document.getElementById('editAuthPrefix').value,
        company_id: document.getElementById('editCompanyId').value,
        endpoints: {
            pix_create: document.getElementById('editEndpointCreate').value,
            pix_status: document.getElementById('editEndpointStatus').value
        },
        status_field: document.getElementById('editStatusField').value,
        qrcode_field: document.getElementById('editQrcodeField').value,
        txid_field: document.getElementById('editTxidField').value,
        webhook_secret: document.getElementById('editWebhookSecret').value
    };
    
    await saveConfig();
    closeModal('editModal');
});

async function deleteGateway(id) {
    if (!confirm('Tem certeza que deseja excluir este gateway?')) return;
    
    const formData = new FormData();
    formData.append('action', 'delete_gateway');
    formData.append('id', id);
    
    const res = await fetch('', { method: 'POST', body: formData });
    const data = await res.json();
    
    showAlert(data.success ? 'success' : 'error', data.message || data.error);
    if (data.success) loadConfig();
}

function openAddModal() {
    document.getElementById('newGatewayId').value = '';
    document.getElementById('newGatewayName').value = '';
    openModal('addModal');
}

document.getElementById('addGatewayForm').addEventListener('submit', async (e) => {
    e.preventDefault();
    
    const formData = new FormData();
    formData.append('action', 'add_gateway');
    formData.append('id', document.getElementById('newGatewayId').value);
    formData.append('name', document.getElementById('newGatewayName').value);
    
    const res = await fetch('', { method: 'POST', body: formData });
    const data = await res.json();
    
    showAlert(data.success ? 'success' : 'error', data.message || data.error);
    
    if (data.success) {
        closeModal('addModal');
        loadConfig();
    }
});

function openStatusMapModal() {
    document.getElementById('statusMapJson').value = JSON.stringify(config.status_map || {}, null, 2);
    openModal('statusMapModal');
}

async function saveStatusMap() {
    try {
        config.status_map = JSON.parse(document.getElementById('statusMapJson').value);
        await saveConfig();
        closeModal('statusMapModal');
    } catch (e) {
        showAlert('error', 'JSON inválido!');
    }
}

async function saveConfig() {
    const formData = new FormData();
    formData.append('action', 'save_config');
    formData.append('config', JSON.stringify(config));
    
    const res = await fetch('', { method: 'POST', body: formData });
    const data = await res.json();
    
    showAlert(data.success ? 'success' : 'error', data.message || data.error);
    if (data.success) loadConfig();
}

function openModal(id) {
    document.getElementById(id).classList.add('active');
}

function closeModal(id) {
    document.getElementById(id).classList.remove('active');
}

function showAlert(type, message) {
    const container = document.getElementById('alertContainer');
    container.innerHTML = `<div class="alert alert-${type}">${message}</div>`;
    
    setTimeout(() => {
        container.innerHTML = '';
    }, 5000);
}

// Inicializa se já estiver logado
<?php if ($loggedIn): ?>
loadConfig();
<?php endif; ?>
</script>

</body>
</html>