<section class="page-header page-header-flex">
    <div>
        <h2>Integração WayChat + WhatsApp</h2>
        <p>Configure o envio real de mensagens via API do WayChat e, se desejar, a criação de card/deal no kanban do CRM.</p>
    </div>
</section>

<?php if ($msg = Session::getFlash('sucesso')): ?>
    <div class="alert success"><?= e($msg) ?></div>
<?php endif; ?>
<?php if ($msg = Session::getFlash('erro')): ?>
    <div class="alert error"><?= e($msg) ?></div>
<?php endif; ?>

<div class="card" style="margin-bottom:18px;">
    <h3>Como funciona nesta versão</h3>
    <ol class="help-list">
        <li><strong>API Key da conexão</strong> do WayChat: usada para enviar mensagem real pelo WhatsApp.</li>
        <li><strong>API Key da empresa</strong>: usada para criar o card/deal opcional no kanban do CRM.</li>
        <li><strong>Webhook de entrada</strong>: continua disponível para o CRM abrir ocorrência ou consultar protocolo no Prefeitura Resolve.</li>
        <li>O modo recomendado é <strong>WayChat + mensagem normal</strong>, dentro da janela de 24h.</li>
    </ol>
</div>

<div class="grid-2">
    <div class="card form-card">
        <form method="POST" action="<?= base_url('/admin/whatsapp/save') ?>">
            <div class="grid-2">
                <div>
                    <label for="provider_name">Provedor / origem</label>
                    <input type="text" id="provider_name" name="provider_name" value="<?= e($config['provider_name'] ?? 'WayChat') ?>" maxlength="100">
                </div>
                <div>
                    <label for="integration_mode">Modo de integração</label>
                    <select id="integration_mode" name="integration_mode">
                        <option value="waychat" <?= ($config['integration_mode'] ?? 'waychat') === 'waychat' ? 'selected' : '' ?>>WayChat (recomendado)</option>
                        <option value="generic" <?= ($config['integration_mode'] ?? '') === 'generic' ? 'selected' : '' ?>>Webhook genérico</option>
                    </select>
                </div>
                <div>
                    <label for="waychat_base_url">Base URL do WayChat</label>
                    <input type="url" id="waychat_base_url" name="waychat_base_url" value="<?= e($config['waychat_base_url'] ?? 'https://waychat.app.br') ?>">
                </div>
                <div>
                    <label for="telefone_remetente">Telefone remetente</label>
                    <input type="text" id="telefone_remetente" name="telefone_remetente" value="<?= e($config['telefone_remetente'] ?? '') ?>" maxlength="30" placeholder="5535999999999">
                </div>
                <div>
                    <label for="auth_token">API Key da conexão</label>
                    <input type="text" id="auth_token" name="auth_token" value="<?= e($config['auth_token'] ?? '') ?>" maxlength="255">
                    <p class="help-text">Usada nos endpoints <code>/send-message</code>, <code>/uazapi/send-message</code> e <code>/send-template</code>.</p>
                </div>
                <div>
                    <label for="company_auth_token">API Key da empresa</label>
                    <input type="text" id="company_auth_token" name="company_auth_token" value="<?= e($config['company_auth_token'] ?? '') ?>" maxlength="255">
                    <p class="help-text">Necessária apenas para criar card/deal no kanban do CRM.</p>
                </div>
                <div>
                    <label for="waychat_connection_type">Tipo de conexão</label>
                    <select id="waychat_connection_type" name="waychat_connection_type">
                        <option value="cloud" <?= ($config['waychat_connection_type'] ?? 'cloud') === 'cloud' ? 'selected' : '' ?>>Cloud API</option>
                        <option value="lite" <?= ($config['waychat_connection_type'] ?? '') === 'lite' ? 'selected' : '' ?>>WhatsApp Lite</option>
                    </select>
                </div>
                <div>
                    <label for="waychat_send_mode">Modo de envio</label>
                    <select id="waychat_send_mode" name="waychat_send_mode">
                        <option value="message" <?= ($config['waychat_send_mode'] ?? 'message') === 'message' ? 'selected' : '' ?>>Mensagem normal</option>
                        <option value="template" <?= ($config['waychat_send_mode'] ?? '') === 'template' ? 'selected' : '' ?>>Template WhatsApp</option>
                    </select>
                </div>
                <div>
                    <label for="waychat_template_name">Nome do template</label>
                    <input type="text" id="waychat_template_name" name="waychat_template_name" value="<?= e($config['waychat_template_name'] ?? '') ?>" maxlength="120" placeholder="confirma_protocolo">
                </div>
                <div>
                    <label for="waychat_template_language">Idioma do template</label>
                    <input type="text" id="waychat_template_language" name="waychat_template_language" value="<?= e($config['waychat_template_language'] ?? 'pt_BR') ?>" maxlength="20">
                </div>
                <div class="grid-col-span-2">
                    <label for="webhook_url">Webhook de saída do CRM (modo genérico)</label>
                    <input type="url" id="webhook_url" name="webhook_url" value="<?= e($config['webhook_url'] ?? '') ?>" placeholder="https://seu-crm.com/webhook/abc123">
                </div>
                <div>
                    <label for="webhook_token">Token do webhook de entrada</label>
                    <input type="text" id="webhook_token" name="webhook_token" value="<?= e($config['webhook_token'] ?? '') ?>" maxlength="255">
                </div>
                <div>
                    <label for="waychat_status_on_send">Status da conversa ao enviar</label>
                    <select id="waychat_status_on_send" name="waychat_status_on_send">
                        <?php $statusAtual = (string) ($config['waychat_status_on_send'] ?? 'waiting'); ?>
                        <option value="">Não alterar</option>
                        <option value="open" <?= $statusAtual === 'open' ? 'selected' : '' ?>>open</option>
                        <option value="waiting" <?= $statusAtual === 'waiting' ? 'selected' : '' ?>>waiting</option>
                        <option value="closed" <?= $statusAtual === 'closed' ? 'selected' : '' ?>>closed</option>
                    </select>
                </div>
                <div>
                    <label for="waychat_sector_name">Pipeline / setor do deal</label>
                    <input type="text" id="waychat_sector_name" name="waychat_sector_name" value="<?= e($config['waychat_sector_name'] ?? '') ?>" maxlength="120" placeholder="Prefeitura">
                </div>
                <div>
                    <label for="waychat_column_name">Coluna do deal</label>
                    <input type="text" id="waychat_column_name" name="waychat_column_name" value="<?= e($config['waychat_column_name'] ?? '') ?>" maxlength="120" placeholder="Nova Ocorrência">
                </div>
            </div>

            <div class="grid-2" style="margin-top:16px;">
                <label class="checkbox-inline checkbox-inline-card"><input type="checkbox" name="ativo" value="1" <?= (int)($config['ativo'] ?? 0) === 1 ? 'checked' : '' ?>> Integração ativa</label>
                <label class="checkbox-inline checkbox-inline-card"><input type="checkbox" name="auto_create_from_webhook" value="1" <?= (int)($config['auto_create_from_webhook'] ?? 0) === 1 ? 'checked' : '' ?>> Criar ocorrência via webhook de entrada</label>
                <label class="checkbox-inline checkbox-inline-card"><input type="checkbox" name="auto_notify_new" value="1" <?= (int)($config['auto_notify_new'] ?? 0) === 1 ? 'checked' : '' ?>> Notificar nova ocorrência</label>
                <label class="checkbox-inline checkbox-inline-card"><input type="checkbox" name="auto_notify_status" value="1" <?= (int)($config['auto_notify_status'] ?? 0) === 1 ? 'checked' : '' ?>> Notificar mudança de status</label>
                <label class="checkbox-inline checkbox-inline-card"><input type="checkbox" name="auto_notify_sla" value="1" <?= (int)($config['auto_notify_sla'] ?? 0) === 1 ? 'checked' : '' ?>> Notificar SLA</label>
                <label class="checkbox-inline checkbox-inline-card"><input type="checkbox" name="waychat_create_deal" value="1" <?= (int)($config['waychat_create_deal'] ?? 0) === 1 ? 'checked' : '' ?>> Criar card/deal no WayChat</label>
            </div>

            <div style="margin-top:16px;">
                <label for="template_nova_ocorrencia">Mensagem enviada no evento: nova ocorrência</label>
                <textarea id="template_nova_ocorrencia" name="template_nova_ocorrencia" rows="3"><?= e($config['template_nova_ocorrencia'] ?? '') ?></textarea>
            </div>
            <div style="margin-top:16px;">
                <label for="template_status">Mensagem enviada no evento: alteração de status</label>
                <textarea id="template_status" name="template_status" rows="3"><?= e($config['template_status'] ?? '') ?></textarea>
            </div>
            <div style="margin-top:16px;">
                <label for="template_sla">Mensagem enviada no evento: SLA</label>
                <textarea id="template_sla" name="template_sla" rows="3"><?= e($config['template_sla'] ?? '') ?></textarea>
            </div>
            <p class="help-text">Placeholders disponíveis: {nome}, {protocolo}, {status}, {servico}, {descricao}, {telefone}, {sla_label}, {link_consulta}</p>

            <div class="actions-row">
                <button class="btn" type="submit">Salvar configuração</button>
            </div>
        </form>
    </div>

    <div>
        <div class="card form-card" style="margin-bottom:16px;">
            <h3>Teste real de envio</h3>
            <form method="POST" action="<?= base_url('/admin/whatsapp/test') ?>">
                <label for="telefone_teste">Telefone para teste</label>
                <input type="text" id="telefone_teste" name="telefone_teste" placeholder="5535999999999" required>
                <p class="help-text">O sistema enviará mensagem real usando a API do WayChat configurada acima.</p>
                <div class="actions-row" style="margin-top:12px;">
                    <button class="btn" type="submit">Enviar teste</button>
                </div>
            </form>
        </div>

        <div class="card form-card" style="margin-bottom:16px;">
            <h3>Automação manual</h3>
            <p class="help-text">Dispare agora a rotina de SLA. Depois você pode chamar esse mesmo processo por cron ou agendador externo.</p>
            <form method="POST" action="<?= base_url('/admin/whatsapp/process-sla') ?>">
                <button class="btn btn-outline" type="submit">Processar SLA agora</button>
            </form>
        </div>

        <div class="card">
            <h3>Endpoints prontos</h3>
            <div class="help-text">Webhook de entrada: <code><?= e(base_url('/api/index.php?route=/whatsapp/webhook')) ?></code></div>
            <div class="help-text">Cron/API SLA: <code><?= e(base_url('/api/index.php?route=/whatsapp/cron-sla')) ?></code></div>
        </div>
    </div>
</div>

<div class="grid-2" style="margin-top:18px; align-items:start;">
    <div class="card">
        <h3>Payload atual</h3>
        <p class="help-text">Preview do payload realmente enviado conforme o modo configurado.</p>
        <pre class="code-block"><code><?= e(json_encode($payloadPreview, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)) ?></code></pre>
    </div>

    <div class="card">
        <h3>Mapeamento / uso recomendado</h3>
        <table class="table responsive-table">
            <thead>
                <tr>
                    <th>Cenário</th>
                    <th>Endpoint / dado</th>
                </tr>
            </thead>
            <tbody>
                <tr><td>Mensagem normal</td><td><code>/api/v1/send-message</code> ou <code>/api/v1/uazapi/send-message</code></td></tr>
                <tr><td>Template</td><td><code>/api/v1/send-template</code></td></tr>
                <tr><td>Card/deal</td><td><code>/api/v1/deals/create</code></td></tr>
                <tr><td>Token de envio</td><td>API Key da conexão</td></tr>
                <tr><td>Token do deal</td><td>API Key da empresa</td></tr>
            </tbody>
        </table>
    </div>
</div>

<div class="card" style="margin-top:18px;">
    <h3>Últimos logs</h3>
    <?php if (empty($logs)): ?>
        <p>Nenhum log registrado ainda.</p>
    <?php else: ?>
        <table class="table responsive-table">
            <thead>
                <tr>
                    <th>Data</th>
                    <th>Direção</th>
                    <th>Evento</th>
                    <th>Telefone</th>
                    <th>Protocolo</th>
                    <th>Status</th>
                    <th>Mensagem</th>
                </tr>
            </thead>
            <tbody>
            <?php foreach ($logs as $log): ?>
                <tr>
                    <td><?= e($log['criado_em']) ?></td>
                    <td><?= e($log['direction']) ?></td>
                    <td><?= e($log['evento']) ?></td>
                    <td><?= e($log['telefone']) ?></td>
                    <td><?= e($log['protocolo'] ?: '-') ?></td>
                    <td>
                        <?php if ((int)($log['sucesso'] ?? 0) === 1): ?>
                            <span class="sla-badge sla-badge-ok">OK</span>
                        <?php else: ?>
                            <span class="sla-badge sla-badge-danger">FALHA</span>
                        <?php endif; ?>
                    </td>
                    <td><?= e($log['mensagem']) ?></td>
                </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    <?php endif; ?>
</div>
