<?php
// qr_clickservice.php - Gerar QR Code para conexão

$apiKey = 'csk_03262f311f1bb2a935cee679adbb387508ace69a';

// Tenta obter o QR Code via API
$ch = curl_init('https://clickservice.com.br/api/v1/qrcode');
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER => ['apikey: ' . $apiKey],
    CURLOPT_TIMEOUT => 30
]);

$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

header('Content-Type: text/html; charset=utf-8');
?>
<!DOCTYPE html>
<html>
<head>
    <title>QR Code ClickService</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <style>
        * { box-sizing: border-box; }
        body { font-family: Arial, sans-serif; max-width: 600px; margin: 20px auto; padding: 20px; background: #0f1117; color: #dde8f5; }
        .card { background: #1a1d27; border-radius: 12px; padding: 24px; margin-bottom: 20px; border: 1px solid #2a2f3a; text-align: center; }
        .qr-container { background: #fff; border-radius: 12px; padding: 20px; display: inline-block; }
        .qr-container img { max-width: 280px; height: auto; }
        .error { color: #ef4444; font-size: 14px; }
        .success { color: #10b981; }
        .warning { color: #f59e0b; }
        .btn { display: inline-block; padding: 10px 24px; border-radius: 8px; background: #2563eb; color: #fff; text-decoration: none; border: none; cursor: pointer; font-size: 14px; margin: 5px; }
        .btn:hover { background: #1d4ed8; }
        .btn-success { background: #10b981; }
        .btn-success:hover { background: #059669; }
        .mono { font-family: monospace; background: #0f1117; padding: 2px 8px; border-radius: 4px; font-size: 12px; }
        .steps { text-align: left; line-height: 2; color: #9ca3af; font-size: 14px; }
        .steps strong { color: #dde8f5; }
        .status-box { padding: 12px; border-radius: 8px; margin: 10px 0; }
        .status-box.error { background: rgba(239,68,68,.1); border: 1px solid rgba(239,68,68,.3); }
        .status-box.success { background: rgba(16,185,129,.1); border: 1px solid rgba(16,185,129,.3); }
        .status-box.warning { background: rgba(245,158,11,.1); border: 1px solid rgba(245,158,11,.3); }
        .auto-refresh { font-size: 12px; color: #6b7280; margin-top: 10px; }
    </style>
</head>
<body>
    <h1>🔌 Conectar WhatsApp</h1>
    <p><strong>Chave API:</strong> <span class="mono"><?= substr($apiKey, 0, 15) ?>...<?= substr($apiKey, -10) ?></span></p>

    <?php if ($httpCode === 200 && $response): 
        $data = json_decode($response, true);
        $qr = $data['qrcode'] ?? $data['qr'] ?? '';
        if ($qr):
    ?>
    <div class="card">
        <h2>📱 Escaneie o QR Code</h2>
        <div class="qr-container">
            <img src="data:image/png;base64,<?= $qr ?>" alt="QR Code"/>
        </div>
        <p style="color: #6b7280; font-size: 12px; margin-top: 10px;">
            ⏱ QR Code expira em 60 segundos - <a href="?refresh=1" style="color: #2563eb;">recarregar</a>
        </p>
        <div style="display:flex;gap:10px;justify-content:center;flex-wrap:wrap;margin-top:10px;">
            <a href="https://wa.me/?text=Escaneie%20o%20QR%20Code%20para%20conectar%20o%20WhatsApp" 
               target="_blank" class="btn btn-success">📱 Abrir WhatsApp Web</a>
            <a href="?refresh=1" class="btn">🔄 Novo QR Code</a>
        </div>
    </div>

    <div class="card">
        <h3>📋 Como escanear:</h3>
        <div class="steps">
            <div>1️⃣ Abra o <strong>WhatsApp</strong> no seu celular</div>
            <div>2️⃣ No Android: toque nos <strong>3 pontos (⋮)</strong> → <strong>WhatsApp Web</strong></div>
            <div>3️⃣ No iOS: <strong>Configurações</strong> → <strong>WhatsApp Web/Desktop</strong></div>
            <div>4️⃣ <strong>Escaneie o QR Code</strong> acima com o leitor do celular</div>
            <div>5️⃣ Aguarde o status mudar para <strong class="success">"Conectado"</strong></div>
        </div>
        <div class="status-box warning">
            <p style="color:#f59e0b;font-size:12px;margin:0;">
                ⚠️ Mantenha o celular com internet e o WhatsApp aberto durante o processo
            </p>
        </div>
    </div>

    <div class="card">
        <h3>🔄 Verificar Status</h3>
        <button onclick="verificarStatus()" class="btn">🔍 Verificar se já está conectado</button>
        <div id="status-msg" style="margin-top:10px;"></div>
    </div>

    <?php else: ?>
    <div class="card">
        <div class="status-box error">
            <p class="error">❌ Não foi possível gerar o QR Code.</p>
            <p style="color:#6b7280;">Mensagem: <?= $data['error'] ?? 'Erro desconhecido' ?></p>
        </div>
        <a href="?refresh=1" class="btn">🔄 Tentar novamente</a>
    </div>
    <?php endif; ?>
    <?php else: ?>
    <div class="card">
        <div class="status-box error">
            <p class="error">❌ Erro ao conectar com a API (HTTP <?= $httpCode ?>)</p>
            <p style="color:#6b7280;">Resposta: <?= substr($response, 0, 200) ?></p>
        </div>
    </div>
    <?php endif; ?>

    <div class="card">
        <h3>🔧 Ações</h3>
        <div style="display:flex;gap:10px;justify-content:center;flex-wrap:wrap;">
            <a href="testar_clickservice.php" class="btn">🔍 Diagnóstico</a>
            <a href="https://clickservice.com.br/painel" target="_blank" class="btn">🖥️ Painel ClickService</a>
        </div>
        <div class="auto-refresh">
            <label>
                <input type="checkbox" id="auto-refresh" onchange="toggleAutoRefresh()"> 
                Auto-refresh a cada 10 segundos
            </label>
        </div>
    </div>
</body>
<script>
let refreshInterval = null;

function toggleAutoRefresh() {
    const chk = document.getElementById('auto-refresh');
    if (chk.checked) {
        refreshInterval = setInterval(() => {
            location.reload();
        }, 10000);
    } else {
        clearInterval(refreshInterval);
        refreshInterval = null;
    }
}

async function verificarStatus() {
    const msg = document.getElementById('status-msg');
    msg.innerHTML = '⏳ Verificando...';
    msg.style.color = '#f59e0b';
    
    try {
        const resp = await fetch('testar_clickservice.php?ajax=1');
        const text = await resp.text();
        
        if (text.includes('CONECTADO') || text.includes('200')) {
            msg.innerHTML = '✅ WhatsApp CONECTADO! Você já pode enviar mensagens.';
            msg.style.color = '#10b981';
        } else if (text.includes('409') || text.includes('DESCONECTADO')) {
            msg.innerHTML = '⚠️ WhatsApp ainda DESCONECTADO. Escaneie o QR Code acima.';
            msg.style.color = '#f59e0b';
        } else {
            msg.innerHTML = '📊 ' + text.substring(0, 200);
            msg.style.color = '#6b7280';
        }
    } catch(e) {
        msg.innerHTML = '❌ Erro ao verificar: ' + e.message;
        msg.style.color = '#ef4444';
    }
}
</script>
</html>