{% extends "admin/base.html" %}
{% block content %}
<div class="portal-v4-page">
  <section class="portal-v4-hero portal-v4-hero-violet">
    <div>
      <span class="portal-eyebrow">V5 · EMAIL E AUTOMAÇÃO</span>
      <h1>Centro de comunicações</h1>
      <p>Valide o SMTP em modo seguro, prepare avisos, acompanhe a fila, repita falhas e controle a automação periódica.</p>
    </div>
    <div class="portal-v4-actions">
      <a href="{% url 'admin:notifications_notificationlog_add' %}"><span class="material-symbols-outlined">edit_square</span>Nova mensagem</a>
      <a href="{% url 'admin:notifications_notificationtemplate_changelist' %}"><span class="material-symbols-outlined">drafts</span>Modelos</a>
      <a href="{% url 'admin:core_portalconfiguration_changelist' %}"><span class="material-symbols-outlined">settings</span>Configuração</a>
    </div>
  </section>

  {% if warnings %}
  <section class="portal-v5-warning-stack">
    {% for warning in warnings %}<div><span class="material-symbols-outlined">warning</span><p>{{ warning }}</p></div>{% endfor %}
  </section>
  {% endif %}

  <div class="portal-v4-kpis">
    <div><span class="material-symbols-outlined">edit_note</span><small>Rascunhos</small><strong>{{ counts.draft }}</strong></div>
    <div><span class="material-symbols-outlined">schedule_send</span><small>Agendadas</small><strong>{{ counts.scheduled }}</strong></div>
    <div class="is-danger"><span class="material-symbols-outlined">error</span><small>Falharam</small><strong>{{ counts.failed }}</strong></div>
    <div class="is-success"><span class="material-symbols-outlined">mark_email_read</span><small>Enviadas em 30 dias</small><strong>{{ counts.sent_30 }}</strong></div>
  </div>

  <div class="portal-v4-grid portal-v4-grid-2">
    <section class="portal-v4-panel">
      <header><div><span>CONTROLO MANUAL</span><h2>Ações imediatas</h2></div></header>
      <div class="portal-v5-action-grid">
        <form method="post">{% csrf_token %}<input type="hidden" name="action" value="prepare"><button type="submit"><span class="material-symbols-outlined">notification_add</span><strong>Preparar avisos</strong><small>Cria rascunhos para as renovações aplicáveis.</small></button></form>
        <form method="post">{% csrf_token %}<input type="hidden" name="action" value="send_scheduled"><button type="submit"><span class="material-symbols-outlined">send</span><strong>Processar fila</strong><small>Envia as mensagens já agendadas.</small></button></form>
        <form method="post">{% csrf_token %}<input type="hidden" name="action" value="retry_failed"><button type="submit"><span class="material-symbols-outlined">refresh</span><strong>Repetir falhas</strong><small>Força nova tentativa das mensagens elegíveis.</small></button></form>
        <form method="post">{% csrf_token %}<input type="hidden" name="action" value="setup_schedule"><button type="submit"><span class="material-symbols-outlined">automation</span><strong>Configurar automação</strong><small>Cria as tarefas periódicas do Celery Beat.</small></button></form>
      </div>
    </section>

    <section class="portal-v4-panel">
      <header><div><span>TESTE SEGURO</span><h2>Validar configuração de email</h2></div></header>
      <p class="portal-v5-muted">O destinatário representa o cliente original. Com o modo de teste ativo, a mensagem é redirecionada para o email de testes configurado.</p>
      <form method="post" class="portal-v5-test-form">
        {% csrf_token %}<input type="hidden" name="action" value="test_email">
        <label>Email a simular</label>
        <div><input type="email" name="recipient" placeholder="cliente@exemplo.pt" required><button type="submit"><span class="material-symbols-outlined">science</span>Enviar teste</button></div>
      </form>
      <dl class="portal-v5-config-list">
        <div><dt>Backend</dt><dd>{{ backend }}</dd></div>
        <div><dt>Broker</dt><dd>{{ broker }}</dd></div>
        <div><dt>Modo de teste</dt><dd>{% if config and config.email_test_mode %}Ativo{% else %}Desligado{% endif %}</dd></div>
        <div><dt>Envio automático</dt><dd>{% if config and config.auto_send_notifications %}Ativo{% else %}Desligado{% endif %}</dd></div>
      </dl>
    </section>
  </div>

  <div class="portal-v4-grid portal-v4-grid-2">
    <section class="portal-v4-panel"><header><div><span>FILA</span><h2>Próximas mensagens</h2></div><a href="{% url 'admin:notifications_notificationlog_changelist' %}?status__exact=scheduled">Ver todas</a></header><div class="portal-v4-list">
      {% for item in scheduled_notifications %}<a href="{% url 'admin:notifications_notificationlog_change' item.pk %}"><i class="material-symbols-outlined">schedule_send</i><div><strong>{{ item.subject|default:"Sem assunto" }}</strong><small>{{ item.client }} · {{ item.original_recipient|default:item.recipient }}</small></div><b>{{ item.scheduled_for|date:"d/m H:i" }}</b></a>{% empty %}<p class="portal-v4-empty">Não existem mensagens agendadas.</p>{% endfor %}
    </div></section>
    <section class="portal-v4-panel portal-v4-panel-danger"><header><div><span>ERROS</span><h2>Falhas a resolver</h2></div><a href="{% url 'admin:notifications_notificationlog_changelist' %}?status__exact=failed">Ver todas</a></header><div class="portal-v4-list">
      {% for item in failed_notifications %}<a href="{% url 'admin:notifications_notificationlog_change' item.pk %}"><i class="material-symbols-outlined">error</i><div><strong>{{ item.subject|default:"Sem assunto" }}</strong><small>{{ item.client }} · {{ item.error_message|truncatechars:70 }}</small></div><b>{{ item.attempts_count }}/{{ item.max_attempts }}</b></a>{% empty %}<p class="portal-v4-empty">Não existem falhas de envio.</p>{% endfor %}
    </div></section>
  </div>

  <div class="portal-v4-grid portal-v4-grid-2">
    <section class="portal-v4-panel"><header><div><span>AUDITORIA</span><h2>Tentativas recentes</h2></div><a href="{% url 'admin:notifications_notificationattempt_changelist' %}">Abrir histórico</a></header><div class="portal-v4-list compact">
      {% for attempt in recent_attempts %}<a href="{% url 'admin:notifications_notificationlog_change' attempt.notification.pk %}"><div><strong>{{ attempt.notification.subject|default:"Notificação" }}</strong><small>{{ attempt.recipient_used }} · {{ attempt.get_result_display }} · {{ attempt.duration_ms }} ms</small></div><b>{{ attempt.attempted_at|date:"d/m H:i" }}</b></a>{% empty %}<p class="portal-v4-empty">Ainda não existem tentativas.</p>{% endfor %}
    </div></section>
    <section class="portal-v4-panel"><header><div><span>CELERY BEAT</span><h2>Automação periódica</h2></div><a href="{% url 'admin:django_celery_beat_periodictask_changelist' %}">Gerir</a></header><div class="portal-v4-list compact">
      {% for task in periodic_tasks %}<a href="{% url 'admin:django_celery_beat_periodictask_change' task.pk %}"><div><strong>{{ task.name }}</strong><small>{{ task.task }}</small></div><b>{% if task.enabled %}Ativa{% else %}Pausa{% endif %}</b></a>{% empty %}<p class="portal-v4-empty">Ainda não existem agendamentos. Use “Configurar automação”.</p>{% endfor %}
    </div><p class="portal-v5-footnote">{{ automatic_templates }} modelos ativos permitem envio automático; {{ inactive_templates }} modelos estão inativos.</p></section>
  </div>
</div>
{% endblock %}
