<?php
require_once __DIR__ . '/../db.php';
require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../includes/functions.php';
require_admin();

// ── Auto-gera nome da instância se não existir ───────────────
$instanceName = get_system_setting('evolution_instance', '');
if (empty($instanceName)) {
    // Deriva do domínio do APP_URL: mp-monitor-provedor-com-br
    $host = parse_url(APP_URL, PHP_URL_HOST) ?: 'monitorping';
    $instanceName = 'mp-' . preg_replace('/[^a-z0-9]/', '-', strtolower($host));
    $instanceName = preg_replace('/-+/', '-', trim($instanceName, '-'));
    set_system_setting('evolution_instance', $instanceName);
    system_settings_cache(true);
}

// ── Salva override manual ────────────────────────────────────
$saveMsg = null;
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['evolution_instance'])) {
    if (!csrf_check($_POST['csrf_token'] ?? null)) {
        $saveMsg = ['ok' => false, 'text' => 'CSRF inválido.'];
    } else {
        $override = preg_replace('/[^a-zA-Z0-9_-]/', '', trim($_POST['evolution_instance']));
        if ($override) {
            set_system_setting('evolution_instance', $override);
            system_settings_cache(true);
            $instanceName = $override;
            $saveMsg = ['ok' => true, 'text' => 'Nome da instância salvo.'];
        }
    }
}

$evoConfigured = !empty(EVOLUTION_API_URL) && !empty(EVOLUTION_API_KEY);
$n8nWebhook    = get_system_setting('whatsapp_webhook_url', WHATSAPP_WEBHOOK_URL);

require_once __DIR__ . '/../includes/header.php';
?>

<style>
.wa-wrap { max-width: 640px; margin: 0 auto; }
.wa-card {
    background: var(--card); border: 1px solid var(--border);
    border-radius: 14px; padding: 1.8rem; margin-bottom: 1.4rem;
}
/* Status bar */
.wa-status {
    display: flex; align-items: center; gap: .75rem;
    padding: .9rem 1.1rem; border-radius: 10px;
    border: 1px solid var(--border); background: var(--bg);
    margin-bottom: 1.2rem; font-size: .93rem;
}
.wa-dot {
    width: 13px; height: 13px; border-radius: 50%; flex-shrink: 0;
    background: #94a3b8;
}
.wa-dot.open        { background: #22c55e; box-shadow: 0 0 0 4px rgba(34,197,94,.15); }
.wa-dot.loading     { background: #f59e0b; animation: blink .7s infinite alternate; }
.wa-dot.close,
.wa-dot.disconnected{ background: #ef4444; }
@keyframes blink { to { opacity: .25; } }

/* QR container */
#qr-box {
    display: flex; flex-direction: column; align-items: center; gap: .9rem;
    padding: 1.4rem 0;
}
#qr-img {
    width: 230px; height: 230px; border-radius: 12px;
    border: 5px solid var(--border); display: block;
    background: #f1f5f9;
}
#qr-hint { font-size: .82rem; color: var(--text-secondary); text-align: center; line-height: 1.5; }
#qr-countdown {
    font-size: .78rem; color: var(--text-secondary);
    background: var(--bg); border: 1px solid var(--border);
    border-radius: 20px; padding: .2rem .8rem;
}

/* Connected card */
#connected-box {
    background: #f0fdf4; border: 1px solid #86efac;
    border-radius: 10px; padding: 1rem 1.2rem;
    display: flex; align-items: center; gap: .9rem;
}
[data-theme="dark"] #connected-box { background: #052e16; border-color: #166534; }
#connected-phone { font-weight: 700; font-size: 1.05rem; color: #166534; }
[data-theme="dark"] #connected-phone { color: #4ade80; }

/* Buttons */
.wa-btn {
    display: inline-flex; align-items: center; gap: .4rem;
    padding: .55rem 1.2rem; border-radius: 8px; font-size: .9rem;
    cursor: pointer; border: 1px solid var(--border);
    background: var(--card); color: var(--text); text-decoration: none;
}
.wa-btn.primary { background: #2563eb; color: #fff; border-color: #2563eb; }
.wa-btn.danger  { background: #fee2e2; color: #991b1b; border-color: #fca5a5; }
[data-theme="dark"] .wa-btn.danger { background: #450a0a; color: #fca5a5; border-color: #7f1d1d; }
.wa-btn:disabled { opacity: .5; cursor: not-allowed; }
.wa-actions { display: flex; gap: .6rem; flex-wrap: wrap; margin-top: 1rem; }

/* Advanced toggle */
details { margin-top: 1rem; }
details summary {
    cursor: pointer; font-size: .82rem; color: var(--text-secondary);
    list-style: none; display: flex; align-items: center; gap: .3rem;
}
details summary::before { content: '▶'; font-size: .65rem; transition: transform .2s; }
details[open] summary::before { transform: rotate(90deg); }

.wa-warn { background: #fef3c7; border: 1px solid #f59e0b; border-radius: 8px; padding: .75rem 1rem; font-size: .85rem; color: #92400e; margin-bottom: 1rem; }
[data-theme="dark"] .wa-warn { background: #451a03; color: #fde68a; border-color: #92400e; }
</style>

<div class="wa-wrap">
    <h2 style="margin-bottom:.3rem;">📱 WhatsApp</h2>
    <p style="color:var(--text-secondary);font-size:.9rem;margin-bottom:1.5rem;">
        Conecte o número que enviará os alertas. Basta escanear o QR Code.
    </p>

    <?php if (!$evoConfigured): ?>
    <div class="wa-warn">
        <strong>Evolution API não configurada.</strong><br>
        Adicione <code>EVOLUTION_API_URL</code> e <code>EVOLUTION_API_KEY</code> no <code>.env</code> e reinicie os containers.
    </div>
    <?php else: ?>

    <!-- Card principal -->
    <div class="wa-card">

        <!-- Status -->
        <div class="wa-status">
            <span class="wa-dot loading" id="dot"></span>
            <span id="status-text">Verificando conexão...</span>
            <span id="status-phone" style="margin-left:auto;color:var(--text-secondary);font-size:.82rem;"></span>
        </div>

        <!-- QR Code (visível quando desconectado) -->
        <div id="qr-section" style="display:none;">
            <div style="font-size:.85rem;color:var(--text-secondary);margin-bottom:.5rem;text-align:center;">
                Abra o WhatsApp → <strong>Aparelhos conectados</strong> → <strong>Conectar um aparelho</strong>
            </div>
            <div id="qr-box">
                <img id="qr-img" src="" alt="QR Code">
                <span id="qr-hint">Carregando QR Code...</span>
                <span id="qr-countdown" style="display:none;"></span>
            </div>
        </div>

        <!-- Conectado -->
        <div id="connected-section" style="display:none;">
            <div id="connected-box">
                <span style="font-size:1.8rem;">✅</span>
                <div>
                    <div id="connected-phone">WhatsApp conectado</div>
                    <div style="font-size:.82rem;color:var(--text-secondary);margin-top:.15rem;">
                        <?php if ($n8nWebhook): ?>
                            Alertas serão enviados via <code><?= h($n8nWebhook) ?></code>
                        <?php else: ?>
                            <a href="<?= BASE_URL ?>index.php?page=admin_settings" style="color:#2563eb;">Configure o webhook n8n para ativar os envios →</a>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>

        <!-- Ações -->
        <div class="wa-actions">
            <button class="wa-btn primary" id="btn-qr" onclick="loadQR()" style="display:none;">🔄 Novo QR Code</button>
            <button class="wa-btn danger"  id="btn-dc"  onclick="disconnect()" style="display:none;">Desconectar</button>
            <button class="wa-btn" onclick="checkStatus()">Atualizar</button>
            <?php if (!$n8nWebhook): ?>
            <a class="wa-btn" href="<?= BASE_URL ?>index.php?page=admin_settings">Configurar n8n</a>
            <?php endif; ?>
        </div>

        <!-- Avançado: trocar nome da instância -->
        <details>
            <summary>Configuração avançada — instância: <code><?= h($instanceName) ?></code></summary>
            <?php if ($saveMsg): ?>
            <p style="font-size:.82rem;color:<?= $saveMsg['ok'] ? '#16a34a' : '#dc2626' ?>;margin:.5rem 0;">
                <?= h($saveMsg['text']) ?>
            </p>
            <?php endif; ?>
            <form method="post" style="display:flex;gap:.5rem;margin-top:.75rem;flex-wrap:wrap;">
                <input type="hidden" name="csrf_token" value="<?= h(csrf_token()) ?>">
                <input type="text" name="evolution_instance"
                    value="<?= h($instanceName) ?>"
                    placeholder="nome-da-instancia"
                    pattern="[a-zA-Z0-9_\-]+"
                    style="flex:1;min-width:180px;">
                <button type="submit" class="wa-btn">Salvar</button>
            </form>
            <p style="font-size:.75rem;color:var(--text-secondary);margin-top:.3rem;">
                Alterar o nome desconecta a instância atual. Use apenas letras, números, - e _.
            </p>
        </details>
    </div>

    <?php endif; ?>
</div>

<script>
const PROXY    = <?= json_encode(BASE_URL . 'index.php?page=api_whatsapp_proxy') ?>;
const CSRF     = <?= json_encode(csrf_token()) ?>;
const EVO_OK   = <?= json_encode($evoConfigured) ?>;
let pollTimer  = null;
let qrTimer    = null;
let qrSecs     = 60;
let qrAutoRenew = null;

if (!EVO_OK) {
    // Sem Evolution API configurada — nada a fazer
} else {
    init();
}

async function init() {
    const state = await checkStatus();
    if (state !== 'open') loadQR();
    // Polling a cada 4s para detectar quando escanear
    pollTimer = setInterval(async () => {
        const s = await checkStatus();
        if (s === 'open') {
            clearInterval(pollTimer);
            clearInterval(qrTimer);
            clearInterval(qrAutoRenew);
            document.getElementById('qr-section').style.display = 'none';
        }
    }, 4000);
}

async function checkStatus() {
    try {
        const r    = await fetch(PROXY + '&action=status');
        const data = await r.json();
        const state = data.state || 'unknown';
        const phone = data.raw?.instance?.profileName
                   || data.raw?.instance?.owner
                   || '';
        renderStatus(state, phone);
        return state;
    } catch(e) {
        renderStatus('error', '');
        return 'error';
    }
}

function renderStatus(state, phone) {
    const dot  = document.getElementById('dot');
    const txt  = document.getElementById('status-text');
    const ph   = document.getElementById('status-phone');
    const qrS  = document.getElementById('qr-section');
    const okS  = document.getElementById('connected-section');
    const btnQr= document.getElementById('btn-qr');
    const btnDc= document.getElementById('btn-dc');
    const cpn  = document.getElementById('connected-phone');

    dot.className = 'wa-dot';

    if (state === 'open') {
        dot.classList.add('open');
        txt.textContent = 'Conectado';
        ph.textContent  = phone || '';
        cpn.textContent = phone ? '✅ ' + phone : '✅ WhatsApp conectado';
        qrS.style.display = 'none';
        okS.style.display = 'block';
        btnQr.style.display = 'none';
        btnDc.style.display = '';
    } else if (state === 'connecting') {
        dot.classList.add('loading');
        txt.textContent = 'Conectando...';
        ph.textContent  = '';
        okS.style.display = 'none';
        btnQr.style.display = '';
        btnDc.style.display = 'none';
    } else if (state === 'not_configured') {
        txt.textContent = 'Instância não encontrada — gerando QR Code...';
        okS.style.display = 'none';
        btnQr.style.display = '';
        btnDc.style.display = 'none';
    } else {
        dot.classList.add('close');
        txt.textContent = 'Desconectado';
        ph.textContent  = '';
        okS.style.display = 'none';
        btnQr.style.display = '';
        btnDc.style.display = 'none';
    }
}

async function loadQR() {
    const qrS = document.getElementById('qr-section');
    qrS.style.display = 'block';
    document.getElementById('qr-img').src = '';
    document.getElementById('qr-hint').textContent = 'Buscando QR Code...';
    document.getElementById('qr-countdown').style.display = 'none';
    clearInterval(qrTimer);

    try {
        const r    = await fetch(PROXY + '&action=qrcode');
        const data = await r.json();
        if (data.error) {
            document.getElementById('qr-hint').textContent = '⚠ ' + data.error;
            return;
        }
        let b64 = data.qrcode || '';
        if (b64 && !b64.startsWith('data:')) b64 = 'data:image/png;base64,' + b64;
        document.getElementById('qr-img').src = b64;
        document.getElementById('qr-hint').textContent =
            'Abra o WhatsApp → Aparelhos conectados → Conectar um aparelho';

        // Countdown 60s
        qrSecs = 60;
        const cd = document.getElementById('qr-countdown');
        cd.style.display = '';
        cd.textContent   = 'QR válido por ' + qrSecs + 's';
        qrTimer = setInterval(() => {
            qrSecs--;
            if (qrSecs <= 0) {
                clearInterval(qrTimer);
                cd.textContent = 'Renovando QR Code...';
                loadQR();
            } else {
                cd.textContent = 'QR válido por ' + qrSecs + 's';
            }
        }, 1000);
    } catch(e) {
        document.getElementById('qr-hint').textContent = '⚠ Erro ao buscar QR Code.';
    }
}

async function disconnect() {
    if (!confirm('Desconectar o WhatsApp desta instância?')) return;
    const fd = new FormData();
    fd.append('csrf_token', CSRF);
    await fetch(PROXY + '&action=disconnect', { method: 'POST', body: fd }).catch(() => {});
    setTimeout(() => { checkStatus(); loadQR(); }, 1500);
}
</script>

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