<?php
/**
 * Super Admin - Configurações WhatsApp
 * Gerenciar configurações globais do WhatsApp Evolution API
 */
require_once __DIR__ . '/../../../includes/config.php';
require_once __DIR__ . '/../../../includes/whatsapp/EvolutionAPI.php';
require_once __DIR__ . '/../../../includes/whatsapp/WhatsAppNotification.php';

// Verifica se é Super Admin
if (!isSuperAdmin()) {
    header('Location: /pages/login.php');
    exit;
}

$superAdmin = getSuperAdmin();
$pdo = getDB();

$success = '';
$error = '';

// Carregar configuração global do WhatsApp (store_id = 0 para config global)
$configStmt = $pdo->prepare("SELECT * FROM whatsapp_config WHERE store_id = 0");
$configStmt->execute();
$whatsappConfig = $configStmt->fetch(PDO::FETCH_ASSOC);

// Processar formulário
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';

    if ($action === 'save_config') {
        $integrationType = $_POST['integration_type'] ?? 'evolution';
        $apiUrl = trim($_POST['api_url'] ?? '');
        $apiKey = trim($_POST['api_key'] ?? '');
        $instanceName = trim($_POST['instance_name'] ?? '');
        $notifyNewOrder = isset($_POST['notify_new_order']) ? 1 : 0;
        $notifyStatusChange = isset($_POST['notify_status_change']) ? 1 : 0;
        $notifyPayment = isset($_POST['notify_payment']) ? 1 : 0;
        $notifyShipping = isset($_POST['notify_shipping']) ? 1 : 0;

        if ($integrationType === 'evolution' && (empty($apiUrl) || empty($apiKey) || empty($instanceName))) {
            $error = 'Preencha todos os campos obrigatórios para Evolution API.';
        } else {
            try {
                if ($whatsappConfig) {
                    $stmt = $pdo->prepare("
                        UPDATE whatsapp_config
                        SET integration_type = ?, api_url = ?, api_key = ?, instance_name = ?,
                            notify_new_order = ?, notify_status_change = ?,
                            notify_payment = ?, notify_shipping = ?, updated_at = NOW()
                        WHERE store_id = 0
                    ");
                    $stmt->execute([$integrationType, $apiUrl, $apiKey, $instanceName, $notifyNewOrder, $notifyStatusChange, $notifyPayment, $notifyShipping]);
                } else {
                    $stmt = $pdo->prepare("
                        INSERT INTO whatsapp_config
                        (store_id, integration_type, api_url, api_key, instance_name, notify_new_order, notify_status_change, notify_payment, notify_shipping)
                        VALUES (0, ?, ?, ?, ?, ?, ?, ?, ?)
                    ");
                    $stmt->execute([$integrationType, $apiUrl, $apiKey, $instanceName, $notifyNewOrder, $notifyStatusChange, $notifyPayment, $notifyShipping]);
                }

                $configStmt->execute();
                $whatsappConfig = $configStmt->fetch(PDO::FETCH_ASSOC);

                $success = 'Configurações salvas com sucesso!';
            } catch (Exception $e) {
                $error = 'Erro ao salvar: ' . $e->getMessage();
            }
        }
    }

    if ($action === 'test_connection') {
        $apiUrl = trim($_POST['api_url'] ?? '');
        $apiKey = trim($_POST['api_key'] ?? '');
        $instanceName = trim($_POST['instance_name'] ?? '');

        if (empty($apiUrl) || empty($apiKey) || empty($instanceName)) {
            $error = 'Preencha URL da API, Chave e Nome da Instância para testar.';
        } else {
            try {
                $evolution = new EvolutionAPI($apiUrl, $apiKey, $instanceName);
                $status = $evolution->getInstanceStatus();
                
                if ($status && isset($status['instance'])) {
                    $instanceState = $status['instance']['state'] ?? 'unknown';
                    $success = "Conexão OK! Status da instância: " . ucfirst($instanceState);
                } else {
                    $error = 'Não foi possível obter status da instância. Verifique as credenciais.';
                }
            } catch (Exception $e) {
                $error = 'Erro na conexão: ' . $e->getMessage();
            }
        }
    }

    if ($action === 'test_message') {
        $testPhone = trim($_POST['test_phone'] ?? '');
        $testMessage = trim($_POST['test_message'] ?? '');

        if (empty($testPhone) || empty($testMessage)) {
            $error = 'Preencha o número e a mensagem de teste.';
        } elseif (!$whatsappConfig) {
            $error = 'Configure primeiro a API do WhatsApp.';
        } else {
            try {
                $integrationType = $whatsappConfig['integration_type'] ?? 'evolution';
                if ($integrationType === 'api_send') {
                    $url = "https://api.whatsapp.com/send/?phone=" . urlencode($testPhone) . "&text=" . urlencode($testMessage);
                    $success = 'Link gerado com sucesso. <a href="' . htmlspecialchars($url) . '" target="_blank" style="color: inherit; text-decoration: underline;">Clique aqui para abrir o WhatsApp</a>';
                } else {
                    $evolution = new EvolutionAPI(
                        $whatsappConfig['api_url'],
                        $whatsappConfig['api_key'],
                        $whatsappConfig['instance_name']
                    );

                    $result = $evolution->sendText($testPhone, $testMessage);
                    
                    if ($result && isset($result['key'])) {
                        $success = 'Mensagem enviada com sucesso!';
                    } else {
                        $error = 'Falha ao enviar mensagem. Verifique se o número está correto.';
                    }
                }
            } catch (Exception $e) {
                $error = 'Erro ao enviar: ' . $e->getMessage();
            }
        }
    }
}

// Carregar histórico de notificações globais
$logsStmt = $pdo->query("
    SELECT wl.*, o.id as order_number, s.name as store_name
    FROM whatsapp_notifications_log wl
    LEFT JOIN orders o ON wl.order_id = o.id
    LEFT JOIN stores s ON wl.store_id = s.id
    ORDER BY wl.created_at DESC
    LIMIT 50
");
$notificationLogs = $logsStmt->fetchAll(PDO::FETCH_ASSOC);

// Carregar configurações de todas as lojas
$storeConfigsStmt = $pdo->query("
    SELECT wc.*, s.name as store_name, s.slug
    FROM whatsapp_config wc
    JOIN stores s ON wc.store_id = s.id
    WHERE wc.store_id > 0
    ORDER BY s.name
");
$storeConfigs = $storeConfigsStmt->fetchAll(PDO::FETCH_ASSOC);

$currentPage = 'whatsapp';
$pageTitle = 'WhatsApp - Configurações';

include __DIR__ . '/../includes/header.php';
include __DIR__ . '/../includes/sidebar.php';
?>

<div class="app-container">
    <main class="main-content">
        <div class="topbar">
            <div class="topbar-left">
                <button class="mobile-menu-btn" id="mobileMenuBtn">
                    <iconify-icon icon="solar:hamburger-menu-bold"></iconify-icon>
                </button>
                <h1 class="topbar-title">Configurações WhatsApp</h1>
            </div>
            <div class="topbar-right">
                <div class="theme-switcher">
                    <button class="theme-btn" data-theme="light" title="Tema Claro">
                        <iconify-icon icon="solar:sun-bold"></iconify-icon>
                    </button>
                    <button class="theme-btn" data-theme="dark" title="Tema Escuro">
                        <iconify-icon icon="solar:moon-bold"></iconify-icon>
                    </button>
                    <button class="theme-btn" data-theme="auto" title="Automático">
                        <iconify-icon icon="solar:monitor-bold"></iconify-icon>
                    </button>
                </div>
                <div class="user-menu">
                    <img src="https://ui-avatars.com/api/?name=<?= urlencode($superAdmin['name']) ?>&background=CCA43B&color=1A1A1A" alt="Avatar" class="user-avatar">
                    <div class="user-info">
                        <span class="user-name"><?= htmlspecialchars($superAdmin['name']) ?></span>
                        <span class="user-role">Super Admin</span>
                    </div>
                </div>
            </div>
        </div>

        <div class="content-area">
            <!-- Mensagens de Feedback -->
            <?php if ($success): ?>
                <div class="alert alert-success" style="background: rgba(34,197,94,0.1); border: 1px solid var(--success); color: var(--success); padding: 1rem; border-radius: var(--radius-md); margin-bottom: 1.5rem; display: flex; align-items: center; gap: 0.75rem;">
                    <iconify-icon icon="solar:check-circle-bold" style="font-size: 1.5rem;"></iconify-icon>
                    <span><?= htmlspecialchars($success) ?></span>
                </div>
            <?php endif; ?>

            <?php if ($error): ?>
                <div class="alert alert-error" style="background: rgba(239,68,68,0.1); border: 1px solid var(--danger); color: var(--danger); padding: 1rem; border-radius: var(--radius-md); margin-bottom: 1.5rem; display: flex; align-items: center; gap: 0.75rem;">
                    <iconify-icon icon="solar:close-circle-bold" style="font-size: 1.5rem;"></iconify-icon>
                    <span><?= htmlspecialchars($error) ?></span>
                </div>
            <?php endif; ?>

            <div class="grid-2">
                <!-- Configuração da API -->
                <div class="panel">
                    <div class="section-header">
                        <h3 class="section-title">
                            <iconify-icon icon="logos:whatsapp-icon" style="margin-right: 0.5rem;"></iconify-icon>
                            Evolution API - Configuração Global
                        </h3>
                    </div>

                    <form method="POST">
                        <input type="hidden" name="action" value="save_config">

                        <div class="form-group">
                            <label class="form-label">Tipo de Integração *</label>
                            <select name="integration_type" class="form-input" id="integration_type" onchange="toggleIntegrationFields()">
                                <option value="evolution" <?= ($whatsappConfig['integration_type'] ?? 'evolution') === 'evolution' ? 'selected' : '' ?>>Evolution API (Automático via Instância)</option>
                                <option value="api_send" <?= ($whatsappConfig['integration_type'] ?? '') === 'api_send' ? 'selected' : '' ?>>API Send (Link Direto WhatsApp Web/App)</option>
                            </select>
                        </div>

                        <div id="evolution_fields" style="display: <?= ($whatsappConfig['integration_type'] ?? 'evolution') === 'evolution' ? 'block' : 'none' ?>;">
                            <div class="form-group">
                                <label class="form-label">URL da API *</label>
                                <input type="url" name="api_url" class="form-input" 
                                       value="<?= htmlspecialchars($whatsappConfig['api_url'] ?? '') ?>"
                                       placeholder="https://evolution.seudominio.com">
                            </div>

                            <div class="form-group">
                                <label class="form-label">Chave da API (API Key) *</label>
                                <input type="text" name="api_key" class="form-input" 
                                       value="<?= htmlspecialchars($whatsappConfig['api_key'] ?? '') ?>"
                                       placeholder="Sua chave de API">
                            </div>

                            <div class="form-group">
                                <label class="form-label">Nome da Instância *</label>
                                <input type="text" name="instance_name" class="form-input" 
                                       value="<?= htmlspecialchars($whatsappConfig['instance_name'] ?? '') ?>"
                                       placeholder="Nome da instância no Evolution API">
                            </div>
                        </div>

                        <div id="apisend_fields" style="display: <?= ($whatsappConfig['integration_type'] ?? '') === 'api_send' ? 'block' : 'none' ?>;">
                            <div class="form-group">
                                <div style="background: rgba(var(--info-rgb, 37,99,235), 0.08); border: 1px solid rgba(37,99,235,0.2); border-radius: var(--radius-md); padding: 0.875rem 1rem; display: flex; gap: 0.75rem; align-items: flex-start;">
                                    <iconify-icon icon="solar:info-circle-bold" style="font-size: 1.25rem; color: var(--info); flex-shrink: 0; margin-top: 2px;"></iconify-icon>
                                    <div>
                                        <strong style="color: var(--text-primary); font-size: 0.875rem;">Número configurado pelo lojista</strong>
                                        <p style="margin: 0.25rem 0 0; color: var(--text-secondary); font-size: 0.8rem; line-height: 1.4;">No modo API Send, cada lojista configura seu próprio número de WhatsApp no painel <strong>Dashboard → WhatsApp → Alterar configuração</strong>.</p>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="form-group" id="auto_notify_group" style="display: <?= ($whatsappConfig['integration_type'] ?? 'evolution') === 'evolution' ? 'block' : 'none' ?>;">
                            <label class="form-label">Notificações Automáticas</label>
                            <div style="display: flex; flex-direction: column; gap: 0.75rem; margin-top: 0.5rem;">
                                <label style="display: flex; align-items: center; gap: 0.5rem; cursor: pointer;">
                                    <input type="checkbox" name="notify_new_order" value="1" 
                                           <?= ($whatsappConfig['notify_new_order'] ?? 0) ? 'checked' : '' ?>>
                                    <span>Novo Pedido</span>
                                </label>
                                <label style="display: flex; align-items: center; gap: 0.5rem; cursor: pointer;">
                                    <input type="checkbox" name="notify_status_change" value="1"
                                           <?= ($whatsappConfig['notify_status_change'] ?? 0) ? 'checked' : '' ?>>
                                    <span>Mudança de Status</span>
                                </label>
                                <label style="display: flex; align-items: center; gap: 0.5rem; cursor: pointer;">
                                    <input type="checkbox" name="notify_payment" value="1"
                                           <?= ($whatsappConfig['notify_payment'] ?? 0) ? 'checked' : '' ?>>
                                    <span>Confirmação de Pagamento</span>
                                </label>
                                <label style="display: flex; align-items: center; gap: 0.5rem; cursor: pointer;">
                                    <input type="checkbox" name="notify_shipping" value="1"
                                           <?= ($whatsappConfig['notify_shipping'] ?? 0) ? 'checked' : '' ?>>
                                    <span>Envio/Entrega</span>
                                </label>
                            </div>
                        </div>

                        <div class="action-buttons">
                            <button type="submit" class="btn btn-primary">
                                <iconify-icon icon="solar:diskette-bold"></iconify-icon>
                                Salvar Configurações
                            </button>
                        </div>
                    </form>

                    <!-- Teste de Conexão (Apenas Evolution) -->
                    <div id="test_connection_panel" style="margin-top: 2rem; padding-top: 1.5rem; border-top: 1px solid var(--border-light); display: <?= ($whatsappConfig['integration_type'] ?? 'evolution') === 'evolution' ? 'block' : 'none' ?>;">
                        <h4 style="margin-bottom: 1rem; color: var(--text-primary);">Testar Conexão</h4>
                        <form method="POST">
                            <input type="hidden" name="action" value="test_connection">
                            <input type="hidden" name="api_url" value="<?= htmlspecialchars($whatsappConfig['api_url'] ?? '') ?>">
                            <input type="hidden" name="api_key" value="<?= htmlspecialchars($whatsappConfig['api_key'] ?? '') ?>">
                            <input type="hidden" name="instance_name" value="<?= htmlspecialchars($whatsappConfig['instance_name'] ?? '') ?>">
                            <button type="submit" class="btn btn-secondary">
                                <iconify-icon icon="solar:plug-circle-bold"></iconify-icon>
                                Testar Conexão
                            </button>
                        </form>
                    </div>
                </div>

                <!-- Enviar Mensagem de Teste -->
                <div class="panel">
                    <div class="section-header">
                        <h3 class="section-title">
                            <iconify-icon icon="solar:chat-round-dots-bold" style="margin-right: 0.5rem;"></iconify-icon>
                            Enviar Mensagem de Teste
                        </h3>
                    </div>

                    <form method="POST">
                        <input type="hidden" name="action" value="test_message">

                        <div class="form-group">
                            <label class="form-label">Número WhatsApp *</label>
                            <input type="text" name="test_phone" class="form-input" 
                                   placeholder="5527999999999" required>
                            <small style="color: var(--text-muted); font-size: 0.8rem;">
                                Formato: código do país + DDD + número (sem espaços ou caracteres especiais)
                            </small>
                        </div>

                        <div class="form-group">
                            <label class="form-label">Mensagem *</label>
                            <textarea name="test_message" class="form-input" rows="4" 
                                      placeholder="Digite sua mensagem de teste..." required>🧪 Teste de integração WhatsApp - MontaLoja

Esta é uma mensagem de teste enviada pelo painel administrativo.</textarea>
                        </div>

                        <button type="submit" class="btn btn-primary" <?= !$whatsappConfig ? 'disabled' : '' ?>>
                            <iconify-icon icon="solar:plain-bold"></iconify-icon>
                            Enviar Mensagem
                        </button>
                    </form>

                    <!-- Status da Instância -->
                    <?php if ($whatsappConfig): ?>
                    <div id="status_panel" style="margin-top: 2rem; padding-top: 1.5rem; border-top: 1px solid var(--border-light); display: <?= ($whatsappConfig['integration_type'] ?? 'evolution') === 'evolution' ? 'block' : 'none' ?>;">
                        <h4 style="margin-bottom: 1rem; color: var(--text-primary);">Status da Configuração</h4>
                        <div style="display: grid; gap: 0.5rem;">
                            <div style="display: flex; justify-content: space-between;">
                                <span style="color: var(--text-muted);">URL:</span>
                                <span style="color: var(--text-primary);"><?= htmlspecialchars($whatsappConfig['api_url']) ?></span>
                            </div>
                            <div style="display: flex; justify-content: space-between;">
                                <span style="color: var(--text-muted);">Instância:</span>
                                <span style="color: var(--text-primary);"><?= htmlspecialchars($whatsappConfig['instance_name']) ?></span>
                            </div>
                            <div style="display: flex; justify-content: space-between;">
                                <span style="color: var(--text-muted);">Atualizado:</span>
                                <span style="color: var(--text-primary);"><?= date('d/m/Y H:i', strtotime($whatsappConfig['updated_at'] ?? $whatsappConfig['created_at'])) ?></span>
                            </div>
                        </div>
                    </div>
                    <?php endif; ?>
                </div>
            </div>

            <!-- Configurações por Loja -->
            <div class="panel" style="margin-top: 1.5rem;">
                <div class="section-header">
                    <h3 class="section-title">
                        <iconify-icon icon="solar:shop-2-bold" style="margin-right: 0.5rem;"></iconify-icon>
                        Configurações por Loja
                    </h3>
                </div>

                <?php if (empty($storeConfigs)): ?>
                    <div style="text-align: center; padding: 2rem; color: var(--text-muted);">
                        <iconify-icon icon="solar:inbox-bold" style="font-size: 3rem; opacity: 0.5;"></iconify-icon>
                        <p>Nenhuma loja configurou WhatsApp ainda.</p>
                    </div>
                <?php else: ?>
                    <div class="table-responsive">
                        <table class="data-table">
                            <thead>
                                <tr>
                                    <th>Loja</th>
                                    <th>Instância</th>
                                    <th>Novo Pedido</th>
                                    <th>Status</th>
                                    <th>Pagamento</th>
                                    <th>Envio</th>
                                    <th>Atualizado</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($storeConfigs as $sc): ?>
                                    <tr>
                                        <td>
                                            <strong><?= htmlspecialchars($sc['store_name']) ?></strong>
                                            <br><small style="color: var(--text-muted);"><?= htmlspecialchars($sc['slug']) ?></small>
                                        </td>
                                        <td><?= htmlspecialchars($sc['integration_type'] === 'api_send' ? 'API Send' : $sc['instance_name']) ?></td>
                                        <td>
                                            <?php if ($sc['notify_new_order']): ?>
                                                <span class="status-badge status-active">Sim</span>
                                            <?php else: ?>
                                                <span class="status-badge status-inactive">Não</span>
                                            <?php endif; ?>
                                        </td>
                                        <td>
                                            <?php if ($sc['notify_status_change']): ?>
                                                <span class="status-badge status-active">Sim</span>
                                            <?php else: ?>
                                                <span class="status-badge status-inactive">Não</span>
                                            <?php endif; ?>
                                        </td>
                                        <td>
                                            <?php if ($sc['notify_payment']): ?>
                                                <span class="status-badge status-active">Sim</span>
                                            <?php else: ?>
                                                <span class="status-badge status-inactive">Não</span>
                                            <?php endif; ?>
                                        </td>
                                        <td>
                                            <?php if ($sc['notify_shipping']): ?>
                                                <span class="status-badge status-active">Sim</span>
                                            <?php else: ?>
                                                <span class="status-badge status-inactive">Não</span>
                                            <?php endif; ?>
                                        </td>
                                        <td><?= date('d/m/Y H:i', strtotime($sc['updated_at'] ?? $sc['created_at'])) ?></td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                <?php endif; ?>
            </div>

            <!-- Histórico de Notificações -->
            <div class="panel" style="margin-top: 1.5rem;">
                <div class="section-header">
                    <h3 class="section-title">
                        <iconify-icon icon="solar:history-bold" style="margin-right: 0.5rem;"></iconify-icon>
                        Histórico de Notificações (Últimas 50)
                    </h3>
                </div>

                <?php if (empty($notificationLogs)): ?>
                    <div style="text-align: center; padding: 2rem; color: var(--text-muted);">
                        <iconify-icon icon="solar:inbox-bold" style="font-size: 3rem; opacity: 0.5;"></iconify-icon>
                        <p>Nenhuma notificação enviada ainda.</p>
                    </div>
                <?php else: ?>
                    <div class="table-responsive">
                        <table class="data-table">
                            <thead>
                                <tr>
                                    <th>Data/Hora</th>
                                    <th>Loja</th>
                                    <th>Telefone</th>
                                    <th>Tipo</th>
                                    <th>Pedido</th>
                                    <th>Status</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($notificationLogs as $log): ?>
                                    <tr>
                                        <td><?= date('d/m/Y H:i', strtotime($log['created_at'])) ?></td>
                                        <td><?= htmlspecialchars($log['store_name'] ?? 'Global') ?></td>
                                        <td><?= htmlspecialchars($log['phone_number']) ?></td>
                                        <td>
                                            <?php
                                            $typeLabels = [
                                                'new_order' => 'Novo Pedido',
                                                'status_change' => 'Status',
                                                'payment_confirmed' => 'Pagamento',
                                                'shipping' => 'Envio',
                                                'test' => 'Teste'
                                            ];
                                            echo $typeLabels[$log['notification_type']] ?? $log['notification_type'];
                                            ?>
                                        </td>
                                        <td>
                                            <?php if ($log['order_number']): ?>
                                                #<?= htmlspecialchars($log['order_number']) ?>
                                            <?php else: ?>
                                                <span style="color: var(--text-muted);">-</span>
                                            <?php endif; ?>
                                        </td>
                                        <td>
                                            <?php if ($log['status'] === 'sent'): ?>
                                                <span class="status-badge status-active">Enviado</span>
                                            <?php elseif ($log['status'] === 'failed'): ?>
                                                <span class="status-badge status-past_due">Falhou</span>
                                            <?php else: ?>
                                                <span class="status-badge status-trial"><?= ucfirst($log['status']) ?></span>
                                            <?php endif; ?>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </main>
</div>

<script>
// Theme Switcher
document.querySelectorAll('.theme-btn').forEach(btn => {
    btn.addEventListener('click', function() {
        const theme = this.dataset.theme;
        localStorage.setItem('superadmin-theme', theme);
        
        if (theme === 'auto') {
            const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
            document.documentElement.setAttribute('data-theme', prefersDark ? 'dark' : 'light');
        } else {
            document.documentElement.setAttribute('data-theme', theme);
        }
        
        document.querySelectorAll('.theme-btn').forEach(b => b.classList.remove('active'));
        this.classList.add('active');
    });
});

// Set active theme button on load
const savedTheme = localStorage.getItem('superadmin-theme') || 'light';
document.querySelector(`.theme-btn[data-theme="${savedTheme}"]`)?.classList.add('active');

// Mobile menu toggle
const mobileMenuBtn = document.getElementById('mobileMenuBtn');
const sidebar = document.querySelector('.sidebar');
const overlay = document.getElementById('sidebarOverlay');

mobileMenuBtn?.addEventListener('click', () => {
    sidebar.classList.toggle('open');
    overlay.classList.toggle('active');
});

overlay?.addEventListener('click', () => {
    sidebar.classList.remove('open');
    overlay.classList.remove('active');
});

// Integration toggle script
function toggleIntegrationFields() {
    const type = document.getElementById('integration_type').value;
    const evoFields = document.getElementById('evolution_fields');
    const apisendFields = document.getElementById('apisend_fields');
    const autoNotify = document.getElementById('auto_notify_group');
    const testConnectionPanel = document.getElementById('test_connection_panel');
    const statusPanel = document.getElementById('status_panel');
    
    if (type === 'api_send') {
        evoFields.style.display = 'none';
        apisendFields.style.display = 'block';
        autoNotify.style.display = 'none';
        if(testConnectionPanel) testConnectionPanel.style.display = 'none';
        if(statusPanel) statusPanel.style.display = 'none';
    } else {
        evoFields.style.display = 'block';
        apisendFields.style.display = 'none';
        autoNotify.style.display = 'block';
        if(testConnectionPanel) testConnectionPanel.style.display = 'block';
        if(statusPanel) statusPanel.style.display = 'block';
    }
}
</script>

</body>
</html>
