<section class="page-header page-header-flex">
    <div>
        <h2>Integração WhatsApp + automações</h2>
        <p>Configure o webhook de saída, o token de entrada e os envios automáticos do sistema.</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="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</label>
                    <input type="text" id="provider_name" name="provider_name" value="<?= e($config['provider_name'] ?? '') ?>" maxlength="100">
                </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 class="grid-col-span-2">
                    <label for="webhook_url">Webhook de saída</label>
                    <input type="url" id="webhook_url" name="webhook_url" value="<?= e($config['webhook_url'] ?? '') ?>" placeholder="https://seu-provedor/webhook">
                </div>
                <div>
                    <label for="auth_token">Token Bearer do provedor</label>
                    <input type="text" id="auth_token" name="auth_token" value="<?= e($config['auth_token'] ?? '') ?>" maxlength="255">
                </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>

            <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</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' : '' ?>> Rodar alerta de SLA</label>
            </div>

            <div style="margin-top:16px;">
                <label for="template_nova_ocorrencia">Template: 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">Template: status atualizado</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">Template: alerta de 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 rápido</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>
                <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="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>
