<?php
require_once __DIR__ . '/../../../includes/config.php';
require_once __DIR__ . '/../../../includes/check-access.php';

// Headers anti-cache
header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
header("Pragma: no-cache");
header("Expires: 0");
header("ETag: v" . time());
require_once __DIR__ . '/../../../includes/premium-lock.php';

$pdo = getDB();
$userId = $_SESSION['user_id'] ?? null;
$storeId = $_SESSION['store_id'] ?? null;

if (!$userId || !$storeId) {
    header('Location: /pages/login.php');
    exit;
}

$userStmt = $pdo->prepare("SELECT * FROM users WHERE id = ?");
$userStmt->execute([$userId]);
$user = $userStmt->fetch(PDO::FETCH_ASSOC);

$storeStmt = $pdo->prepare("SELECT * FROM stores WHERE id = ?");
$storeStmt->execute([$storeId]);
$store = $storeStmt->fetch(PDO::FETCH_ASSOC);

$globalConfigStmt = $pdo->prepare("SELECT * FROM whatsapp_config WHERE store_id = 0");
$globalConfigStmt->execute();
$globalConfig = $globalConfigStmt->fetch(PDO::FETCH_ASSOC);

$configStmt = $pdo->prepare("SELECT * FROM whatsapp_config WHERE store_id = ?");
$configStmt->execute([$storeId]);
$whatsappConfig = $configStmt->fetch(PDO::FETCH_ASSOC);

if (!$whatsappConfig) {
    $whatsappConfig = $globalConfig;
    // Removendo a cópia do número global para a loja para que ela use o dela
    $whatsappConfig['whatsapp_number'] = ''; 
} else if ($globalConfig) {
    $whatsappConfig['integration_type'] = $globalConfig['integration_type'] ?? 'evolution';
}

// Processar formulário do Modal API Send
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'save_api_send') {
    $whatsappNumber = preg_replace('/[^0-9]/', '', $_POST['whatsapp_number'] ?? '');
    
    $checkStmt = $pdo->prepare("SELECT id FROM whatsapp_config WHERE store_id = ?");
    $checkStmt->execute([$storeId]);
    if ($checkStmt->fetch()) {
        $updateStmt = $pdo->prepare("UPDATE whatsapp_config SET whatsapp_number = ? WHERE store_id = ?");
        $updateStmt->execute([$whatsappNumber, $storeId]);
    } else {
        $insertStmt = $pdo->prepare("INSERT INTO whatsapp_config (store_id, integration_type, whatsapp_number) VALUES (?, 'api_send', ?)");
        $insertStmt->execute([$storeId, $whatsappNumber]);
    }
    
    header('Location: /pages/dashboard/whatsapp/');
    exit;
}

$integrationType = $whatsappConfig['integration_type'] ?? 'evolution';

$pageTitle = 'WhatsApp';
include __DIR__ . '/../../../includes/dashboard-header.php';
?>

<style>
/* Cards e Grid */
.whatsapp-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(280px, 1fr)); gap: 1.5rem; margin-top: 1.5rem; }
.feature-card { background: var(--bg-card); border: 1px solid var(--border); border-radius: var(--radius-lg); padding: 1.5rem; }
.feature-icon { width: 56px; height: 56px; border-radius: 12px; display: flex; align-items: center; justify-content: center; margin-bottom: 1rem; }
.feature-icon iconify-icon { font-size: 1.75rem; }
.feature-icon.green { background: rgba(34, 197, 94, .15); }
.feature-icon.green iconify-icon { color: #22C55E; }
.feature-icon.blue { background: rgba(59, 130, 246, .15); }
.feature-icon.blue iconify-icon { color: #3B82F6; }
.feature-icon.purple { background: rgba(168, 85, 247, .15); }
.feature-icon.purple iconify-icon { color: #A855F7; }
.feature-icon.orange { background: rgba(249, 115, 22, .15); }
.feature-icon.orange iconify-icon { color: #F97316; }
.feature-card h3 { font-size: 1.1rem; font-weight: 600; margin-bottom: .5rem; color: var(--text-primary); }
.feature-card p { font-size: .9rem; color: var(--text-muted); margin-bottom: 1rem; line-height: 1.5; }
.badge-soon { display: inline-flex; align-items: center; gap: .35rem; padding: .35rem .75rem; background: rgba(59, 130, 246, .15); color: #3B82F6; border-radius: 6px; font-size: .75rem; font-weight: 500; }

/* Connection Card */
.connection-card { background: var(--bg-card); border: 1px solid var(--border); border-radius: var(--radius-lg); padding: 1.5rem; margin-bottom: 1.5rem; }
.connection-header { display: flex; align-items: center; justify-content: space-between; margin-bottom: 1rem; padding-bottom: 1rem; border-bottom: 1px solid var(--border); }
.connection-header h2 { display: flex; align-items: center; gap: .5rem; font-size: 1.1rem; margin: 0; color: var(--text-primary); }
.badge-status { display: inline-flex; align-items: center; gap: .35rem; padding: .35rem .75rem; border-radius: 6px; font-size: .8rem; font-weight: 500; }
.badge-warning { background: rgba(245, 158, 11, .15); color: #F59E0B; }
.badge-success { background: rgba(34, 197, 94, .15); color: #22C55E; }
.btn-danger { background: #EF4444; color: #fff; }
.btn-danger:hover { background: #DC2626; }
#instance-name { background: var(--bg); padding: .2rem .5rem; border-radius: 4px; font-family: monospace; font-size: .85rem; }

/* History Card */
.history-card { background: var(--bg-card); border: 1px solid var(--border); border-radius: var(--radius-lg); padding: 1.5rem; margin-top: 1.5rem; }
.history-card h2 { display: flex; align-items: center; gap: .5rem; font-size: 1.1rem; margin-bottom: 1rem; padding-bottom: 1rem; border-bottom: 1px solid var(--border); color: var(--text-primary); }
.empty-state { text-align: center; padding: 3rem; }
.empty-state iconify-icon { font-size: 4rem; color: var(--text-muted); opacity: .5; }
.empty-state p { color: var(--text-muted); margin-top: 1rem; }

/* Responsive */
@media (max-width: 768px) {
    .whatsapp-grid { grid-template-columns: 1fr; }
    .connection-header { flex-direction: column; align-items: flex-start; gap: 1rem; }
}

/* Modal QR Code - Estilo Dashboard */
.modal-overlay {
    display: none;
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.7);
    backdrop-filter: blur(8px);
    z-index: 9999;
    align-items: center;
    justify-content: center;
    padding: 1rem;
}
.modal-overlay.active {
    display: flex;
}
.modal-box {
    background-color: var(--bg-card);
    border: 1px solid var(--border);
    border-radius: 12px;
    box-shadow: 0 12px 48px rgba(0,0,0,0.2);
    max-width: 480px;
    width: 100%;
    animation: modalSlideIn 0.3s cubic-bezier(0.4, 0, 0.2, 1);
    overflow: hidden;
}
@keyframes modalSlideIn {
    from { opacity: 0; transform: translateY(20px) scale(0.95); }
    to { opacity: 1; transform: translateY(0) scale(1); }
}
.modal-box .modal-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 24px;
    border-bottom: 1px solid var(--border);
}
.modal-box .modal-header h3 {
    display: flex;
    align-items: center;
    gap: 12px;
    font-size: 1.5rem;
    font-weight: 800;
    color: var(--text-primary);
    margin: 0;
    letter-spacing: -0.02em;
}
.modal-box .modal-header h3 iconify-icon {
    color: var(--primary);
    font-size: 1.75rem;
}
.modal-close {
    background: var(--bg-hover);
    border: none;
    color: var(--text-muted);
    cursor: pointer;
    font-size: 1.25rem;
    display: flex;
    padding: 8px;
    border-radius: 9999px;
    transition: all 0.2s;
}
.modal-close:hover {
    color: var(--text-primary);
    transform: scale(1.1);
}
.modal-box .modal-body {
    padding: 24px;
    color: var(--text-muted);
}
.modal-box .modal-footer {
    padding: 16px 24px;
    border-top: 1px solid var(--border);
    background: var(--bg-card);
    display: flex;
    justify-content: flex-end;
    gap: 12px;
}
.modal-box .form-input {
    height: 48px;
    background: var(--bg);
    border: 1px solid var(--border);
    border-radius: 4px;
    padding: 0 16px;
    color: var(--text-primary);
    width: 100%;
    font-size: 14px;
    transition: all 0.2s;
}
.modal-box .form-input:focus {
    border-color: var(--primary);
    outline: none;
}
.modal-box .btn-primary {
    background: var(--primary);
    color: #FFFFFF;
    font-weight: 700;
    height: 48px;
    padding: 0 32px;
    border-radius: 9999px;
    border: none;
    cursor: pointer;
    text-transform: uppercase;
    letter-spacing: 0.05em;
    font-size: 14px;
    transition: all 0.2s;
}
.modal-box .btn-primary:hover {
    filter: brightness(1.1);
    transform: scale(1.04);
}
.modal-box .btn-secondary {
    background: transparent;
    color: var(--text-primary);
    font-weight: 700;
    height: 48px;
    padding: 0 32px;
    border-radius: 9999px;
    border: 1px solid var(--border);
    cursor: pointer;
    text-transform: uppercase;
    letter-spacing: 0.05em;
    font-size: 14px;
    transition: all 0.2s;
}
.modal-box .btn-secondary:hover {
    background: var(--bg-hover);
    transform: scale(1.04);
}
#qr-body {
    min-height: 280px;
    display: flex;
    align-items: center;
    justify-content: center;
    flex-direction: column;
}
.qr-loading {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 1rem;
    color: var(--text-muted);
}
.qr-loading iconify-icon {
    font-size: 3rem;
    color: #25D366;
}
.qr-loading .spin {
    animation: spin 1s linear infinite;
}
@keyframes spin {
    to { transform: rotate(360deg); }
}
.qr-box {
    background: #ffffff;
    padding: 1rem;
    border-radius: var(--radius-lg);
    display: inline-block;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}
.qr-box img {
    width: 220px;
    height: 220px;
    display: block;
    border-radius: var(--radius);
}
.qr-error {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 1rem;
    color: #EF4444;
}
.qr-error iconify-icon {
    font-size: 3.5rem;
}
.qr-error p {
    color: var(--text-muted);
    margin: 0;
}
.qr-success {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 1rem;
    color: #22C55E;
}
.qr-success iconify-icon {
    font-size: 3.5rem;
}
.qr-success p {
    color: var(--text-muted);
    margin: 0;
}
.btn-retry {
    margin-top: 0.5rem;
    padding: 0.6rem 1.25rem;
    background: var(--primary);
    color: #fff;
    border: none;
    border-radius: var(--radius);
    cursor: pointer;
    font-weight: 500;
    transition: all 0.2s;
}
.btn-retry:hover {
    filter: brightness(1.1);
}
</style>


<main class="main-content">
<?php if (shouldLockFeature('whatsapp_integration')): ?>
    <!-- CONTEÚDO FAKE - Apenas visual, não funcional -->
    <div class="premium-locked premium-full">
        <div class="premium-content">
            <div class="page-header">
                <h1><iconify-icon icon="solar:chat-round-dots-bold"></iconify-icon> WhatsApp</h1>
                <p>Gerencie suas integrações e automações do WhatsApp</p>
            </div>
            <div class="connection-card">
                <div class="connection-header">
                    <h2><iconify-icon icon="solar:link-bold"></iconify-icon> Status da Conexão</h2>
                    <span class="badge-status badge-warning">
                        <iconify-icon icon="solar:refresh-circle-bold"></iconify-icon> Desconectado
                    </span>
                </div>
                <p style="color:var(--text-muted)">Conecte seu WhatsApp Business para enviar mensagens automáticas.</p>
                <button class="btn btn-primary" disabled><iconify-icon icon="solar:qr-code-bold"></iconify-icon> Conectar WhatsApp</button>
            </div>
            <div class="whatsapp-grid">
                <div class="feature-card">
                    <div class="feature-icon green"><iconify-icon icon="solar:chat-round-dots-bold"></iconify-icon></div>
                    <h3>Mensagens Automáticas</h3>
                    <p>Configure mensagens de boas-vindas e lembretes.</p>
                </div>
                <div class="feature-card">
                    <div class="feature-icon blue"><iconify-icon icon="solar:bell-bold"></iconify-icon></div>
                    <h3>Notificações de Pedidos</h3>
                    <p>Envie atualizações automáticas sobre pedidos.</p>
                </div>
            </div>
        </div>
        <div class="premium-overlay">
            <div class="premium-card">
                <div class="premium-card-icon">
                    <iconify-icon icon="solar:lock-keyhole-bold"></iconify-icon>
                </div>
                <h3 class="premium-card-title">Integração WhatsApp</h3>
                <p class="premium-card-description">Conecte seu WhatsApp Business para enviar mensagens automáticas, notificações de pedidos e muito mais!</p>
                <div class="premium-card-plan">
                    <iconify-icon icon="solar:crown-bold"></iconify-icon>
                    Disponível no plano Starter
                </div>
                <ul class="premium-card-features">
                    <li><iconify-icon icon="solar:check-circle-bold"></iconify-icon> Mensagens automáticas de pedidos</li>
                    <li><iconify-icon icon="solar:check-circle-bold"></iconify-icon> Notificações em tempo real</li>
                    <li><iconify-icon icon="solar:check-circle-bold"></iconify-icon> Atendimento automatizado</li>
                </ul>
                <a href="/pages/upgrade.php" class="btn-upgrade">
                    <iconify-icon icon="solar:rocket-bold"></iconify-icon>
                    Fazer Upgrade
                </a>
            </div>
        </div>
    </div>
</main>
<?php include __DIR__ . '/../../../includes/dashboard-footer.php'; ?>
<?php else: ?>
    <!-- CONTEÚDO REAL - Só renderiza se tem acesso -->
    <div class="page-header">
        <h1><iconify-icon icon="solar:chat-round-dots-bold"></iconify-icon> WhatsApp</h1>
        <p>Gerencie suas integrações e automações do WhatsApp</p>
    </div>

    <div class="connection-card">
        <div class="connection-header">
            <?php if ($integrationType === 'api_send'): ?>
                <h2><iconify-icon icon="solar:link-bold"></iconify-icon> Modo de Envio: API Send</h2>
                <span class="badge-status badge-success">
                    <iconify-icon icon="solar:check-circle-bold"></iconify-icon> Ativo
                </span>
            <?php else: ?>
                <h2><iconify-icon icon="solar:link-bold"></iconify-icon> Status da Conexão</h2>
                <span class="badge-status badge-warning" id="connection-badge">
                    <iconify-icon icon="solar:refresh-circle-bold"></iconify-icon> <span id="status-text">Verificando...</span>
                </span>
            <?php endif; ?>
        </div>
        
        <?php if ($integrationType === 'api_send'): ?>
            <p style="color:var(--text-muted);margin-bottom:.5rem">O sistema está configurado para envio manual via redirecionamento (WhatsApp Web/App).</p>
            <p style="color:var(--text-muted);font-size:.85rem;margin-bottom:1rem">
                <strong>Número Padrão:</strong> <code><?php echo htmlspecialchars($whatsappConfig['whatsapp_number'] ?? 'Não configurado'); ?></code>
            </p>
            <div>
                <button type="button" class="btn btn-secondary" onclick="openApiSendModal()">
                    <iconify-icon icon="solar:settings-bold"></iconify-icon> Alterar Configuração
                </button>
            </div>
        <?php else: ?>
            <p style="color:var(--text-muted);margin-bottom:.5rem">Conecte seu WhatsApp Business para enviar mensagens automáticas.</p>
            <p style="color:var(--text-muted);font-size:.85rem;margin-bottom:1rem"><strong>Instância:</strong> <code id="instance-name"><?php echo htmlspecialchars($store['slug']); ?></code></p>
            <div id="connection-actions">
                <button class="btn btn-primary" id="btn-connect"><iconify-icon icon="solar:qr-code-bold"></iconify-icon> Conectar WhatsApp</button>
                <button class="btn btn-danger" id="btn-disconnect" style="display:none;margin-left:.5rem"><iconify-icon icon="solar:logout-2-bold"></iconify-icon> Desconectar</button>
            </div>
        <?php endif; ?>
    </div>

    <div class="whatsapp-grid">
        <div class="feature-card">
            <div class="feature-icon green"><iconify-icon icon="solar:chat-round-dots-bold"></iconify-icon></div>
            <h3>Mensagens Automáticas</h3>
            <p>Configure mensagens de boas-vindas e lembretes.</p>
            <a href="/pages/dashboard/whatsapp/mensagens-auto.php" class="btn btn-secondary"><iconify-icon icon="solar:settings-bold"></iconify-icon> Configurar</a>
        </div>
        <div class="feature-card">
            <div class="feature-icon blue"><iconify-icon icon="solar:bell-bold"></iconify-icon></div>
            <h3>Notificações de Pedidos</h3>
            <p>Envie atualizações automáticas sobre pedidos.</p>
            <a href="/pages/dashboard/whatsapp/notificacoes-pedidos.php" class="btn btn-secondary"><iconify-icon icon="solar:settings-bold"></iconify-icon> Configurar</a>
        </div>
        <div class="feature-card">
            <div class="feature-icon purple"><iconify-icon icon="solar:robot-bold"></iconify-icon></div>
            <h3>Chatbot Inteligente</h3>
            <p>Responda perguntas frequentes com IA.</p>
            <span class="badge-soon"><iconify-icon icon="solar:clock-circle-bold"></iconify-icon> Em breve</span>
        </div>
        <div class="feature-card">
            <div class="feature-icon orange"><iconify-icon icon="solar:megaphone-bold"></iconify-icon></div>
            <h3>Campanhas em Massa</h3>
            <p>Envie promoções para todos os clientes.</p>
            <span class="badge-soon"><iconify-icon icon="solar:clock-circle-bold"></iconify-icon> Em breve</span>
        </div>
    </div>

    <div class="history-card">
        <h2><iconify-icon icon="solar:history-bold"></iconify-icon> Histórico de Mensagens</h2>
        <div class="empty-state"><iconify-icon icon="solar:chat-round-dots-outline"></iconify-icon><p>Conecte seu WhatsApp para ver o histórico.</p></div>
    </div>
</main>

<?php include __DIR__ . '/../../../includes/dashboard-footer.php'; ?>
<?php endif; ?>

<?php if (!shouldLockFeature('whatsapp_integration')): ?>
<!-- Modal QR Code - SÓ RENDERIZA SE TEM ACESSO -->
<div class="modal-overlay" id="qr-modal">
    <div class="modal-box">
        <div class="modal-header">
            <h3><iconify-icon icon="solar:qr-code-bold"></iconify-icon> Escanear QR Code</h3>
            <button class="modal-close" onclick="closeQrModal()"><iconify-icon icon="solar:close-circle-bold"></iconify-icon></button>
        </div>
        <div class="modal-body" id="qr-body">
            <div class="qr-loading">
                <iconify-icon icon="solar:refresh-circle-bold" class="spin"></iconify-icon>
                <p>Gerando QR Code...</p>
            </div>
        </div>
        <div class="modal-footer">
            <p style="font-size:.8rem;color:var(--text-muted)">Abra o WhatsApp no celular &gt; Menu &gt; Aparelhos Conectados &gt; Conectar</p>
        </div>
    </div>
</div>

<!-- Modal API Send -->
<div class="modal-overlay" id="api-send-modal">
    <div class="modal-box">
        <form method="POST">
            <input type="hidden" name="action" value="save_api_send">
            <div class="modal-header">
                <h3><iconify-icon icon="solar:link-bold"></iconify-icon> Configurar API Send</h3>
                <button type="button" class="modal-close" onclick="closeApiSendModal()"><iconify-icon icon="solar:close-circle-bold"></iconify-icon></button>
            </div>
            <div class="modal-body" style="text-align: left;">
                <p style="margin-bottom: 24px; font-size: 14px; line-height: 1.6;">
                    Informe o número de WhatsApp que receberá os pedidos. O cliente será redirecionado para este número.
                </p>
                <div class="form-group">
                    <label style="display: block; font-weight: 700; margin-bottom: 8px; color: var(--text-primary); font-size: 12px; text-transform: uppercase; letter-spacing: 0.1em;">Número do WhatsApp <span style="color: var(--primary);">*</span></label>
                    <input type="text" name="whatsapp_number" class="form-input" value="<?php echo htmlspecialchars($whatsappConfig['whatsapp_number'] ?? ''); ?>" placeholder="5527996322138" required>
                    <small style="color: var(--text-muted); display: block; margin-top: 8px; font-size: 12px;">Use o formato: Código do país + DDD + Número (ex: 5527999999999)</small>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn-secondary" onclick="closeApiSendModal()">Cancelar</button>
                <button type="submit" class="btn-primary">Salvar Número</button>
            </div>
        </form>
    </div>
</div>

<script>
<?php if ($integrationType === 'evolution'): ?>
const instanceName = '<?php echo addslashes($store['slug']); ?>';
const proxyUrl = '/proxy/evolution.php';
let statusCheckInterval = null;

async function checkStatus() {
    try {
        const res = await fetch(`${proxyUrl}?_t=${Date.now()}&action=status&instance=${instanceName}`, { credentials: "include" });
        if (!res.ok) throw new Error('Erro ao verificar');
        const data = await res.json();
        const state = data.instance?.state || 'close';
        updateUI(state);
    } catch (e) {
        updateUI('close');
    }
}

function updateUI(state) {
    const badge = document.getElementById('connection-badge');
    const btnConnect = document.getElementById('btn-connect');
    const btnDisconnect = document.getElementById('btn-disconnect');

    if (!badge) return;

    if (state === 'open') {
        badge.className = 'badge-status badge-success';
        badge.innerHTML = '<iconify-icon icon="solar:check-circle-bold"></iconify-icon> <span id="status-text">Conectado</span>';
        if (btnConnect) btnConnect.style.display = 'none';
        if (btnDisconnect) btnDisconnect.style.display = 'inline-flex';
    } else {
        badge.className = 'badge-status badge-warning';
        badge.innerHTML = '<iconify-icon icon="solar:close-circle-bold"></iconify-icon> <span id="status-text">Desconectado</span>';
        if (btnConnect) btnConnect.style.display = 'inline-flex';
        if (btnDisconnect) btnDisconnect.style.display = 'none';
    }
}

async function connectWhatsApp() {
    document.getElementById('qr-modal').classList.add('active');
    document.getElementById('qr-body').innerHTML = '<div class="qr-loading"><iconify-icon icon="solar:refresh-circle-bold" class="spin"></iconify-icon><p>Gerando QR Code...</p></div>';

    try {
        // Criar instância
        await fetch(`${proxyUrl}?_t=${Date.now()}&action=create&instance=${instanceName}`, { credentials: "include" });
        
        // Conectar e obter QR
        const connectRes = await fetch(`${proxyUrl}?_t=${Date.now()}&action=qrcode&instance=${instanceName}`, { credentials: "include" });
        if (!connectRes.ok) throw new Error('Erro ao conectar');
        const connectData = await connectRes.json();

        if (connectData.base64) {
            document.getElementById('qr-body').innerHTML = `<img src="${connectData.base64}" alt="QR Code" style="max-width:280px;border-radius:8px">`;
            startStatusCheck();
        } else {
            throw new Error('QR Code não disponível');
        }
    } catch (e) {
        document.getElementById('qr-body').innerHTML = `<div class="qr-error"><iconify-icon icon="solar:danger-triangle-bold"></iconify-icon><p>Erro: ${e.message}</p><button class="btn btn-primary" onclick="connectWhatsApp()">Tentar novamente</button></div>`;
    }
}

async function disconnectWhatsApp() {
    if (!confirm('Deseja realmente desconectar o WhatsApp?')) return;
    try {
        await fetch(`${proxyUrl}?_t=${Date.now()}&action=disconnect&instance=${instanceName}`, { credentials: "include" });
        checkStatus();
    } catch (e) {
        alert('Erro ao desconectar');
    }
}

function closeQrModal() {
    document.getElementById('qr-modal').classList.remove('active');
    stopStatusCheck();
    checkStatus();
}

function startStatusCheck() {
    statusCheckInterval = setInterval(async () => {
        const res = await fetch(`${proxyUrl}?_t=${Date.now()}&action=status&instance=${instanceName}`, { credentials: "include" });
        const data = await res.json();
        if (data.instance?.state === 'open') {
            closeQrModal();
            checkStatus();
        }
    }, 3000);
}

function stopStatusCheck() {
    if (statusCheckInterval) {
        clearInterval(statusCheckInterval);
        statusCheckInterval = null;
    }
}

if (document.getElementById('btn-connect')) {
    document.getElementById('btn-connect').addEventListener('click', connectWhatsApp);
}
if (document.getElementById('btn-disconnect')) {
    document.getElementById('btn-disconnect').addEventListener('click', disconnectWhatsApp);
}

checkStatus();
<?php endif; ?>
</script>

<script>
// Funções globais independentes do tipo de integração
function openApiSendModal() {
    const modal = document.getElementById('api-send-modal');
    if(modal) modal.classList.add('active');
}

function closeApiSendModal() {
    const modal = document.getElementById('api-send-modal');
    if(modal) modal.classList.remove('active');
}

// Fechar modals genéricos
document.addEventListener('DOMContentLoaded', () => {
    document.querySelectorAll('.modal-overlay').forEach(overlay => {
        if (!overlay.dataset.listenerAdded) {
            overlay.addEventListener('click', function(e) {
                if (e.target === this) {
                    this.classList.remove('active');
                }
            });
            overlay.dataset.listenerAdded = 'true';
        }
    });
});
</script>
<?php endif; ?>

<!-- Versão: 2025-12-16-17:20 - Fix proxy routing -->
