{% extends "admin/base.html" %}
{% load i18n %}

{% block content %}
<div class="portal-dashboard">
    {% if demo_mode %}
    <div class="portal-demo-banner">
        <span class="material-symbols-outlined">science</span>
        <div>
            <strong>Modo de demonstração ativo</strong>
            <span>Todos os clientes, domínios, valores e contactos apresentados são fictícios.</span>
        </div>
    </div>
    {% endif %}

    <section class="portal-hero">
        <div class="portal-hero-orb portal-hero-orb-one"></div>
        <div class="portal-hero-orb portal-hero-orb-two"></div>
        <div class="portal-hero-content">
            <div class="portal-hero-copy">
                <span class="portal-eyebrow">CENTRO DE OPERAÇÕES · {{ today|date:"d/m/Y" }}</span>
                <h1>Olá, {{ request.user.get_short_name|default:request.user.username }}</h1>
                <p>Acompanha renovações, clientes, pagamentos, suporte e infraestrutura a partir de uma única visão.</p>
                <div class="portal-hero-meta">
                    <span><span class="portal-live-dot"></span> Sistema operacional</span>
                    <span><span class="material-symbols-outlined">schedule</span> Atualizado às {{ system_time|date:"H:i" }}</span>
                </div>
            </div>
            <div class="portal-hero-actions">
                <a href="{% url 'operations_center' %}" class="portal-hero-button portal-hero-button-soft">
                    <span class="material-symbols-outlined">space_dashboard</span>Operações
                </a>
                <a href="{% url 'report_center' %}" class="portal-hero-button portal-hero-button-soft">
                    <span class="material-symbols-outlined">analytics</span>Relatórios
                </a>
                <a href="{% url 'admin:clients_client_add' %}" class="portal-hero-button portal-hero-button-soft">
                    <span class="material-symbols-outlined">person_add</span>Novo cliente
                </a>
                <a href="{% url 'admin:services_service_add' %}" class="portal-hero-button portal-hero-button-primary">
                    <span class="material-symbols-outlined">add_circle</span>Novo serviço
                </a>
                <button type="button" class="portal-hero-button portal-hero-button-icon" data-density-toggle aria-pressed="false" title="Alternar densidade">
                    <span class="material-symbols-outlined">view_compact</span><span class="density-label">Vista compacta</span>
                </button>
            </div>
        </div>
    </section>

    <div class="portal-metric-grid">
        {% for card in dashboard_cards %}
        <a href="{{ card.url }}" class="portal-metric-card portal-tone-{{ card.tone }}">
            <div class="portal-metric-top">
                <span class="portal-metric-icon material-symbols-outlined">{{ card.icon }}</span>
                <span class="portal-metric-arrow material-symbols-outlined">arrow_outward</span>
            </div>
            <strong class="portal-metric-value" data-animate-value="{{ card.value }}"{% if card.suffix %} data-suffix="{{ card.suffix }}"{% endif %}>{{ card.value }}{% if card.suffix %}{{ card.suffix }}{% endif %}</strong>
            <span class="portal-metric-title">{{ card.title }}</span>
            <span class="portal-metric-caption">{{ card.caption }}</span>
        </a>
        {% endfor %}
    </div>

    <div class="portal-layout portal-layout-main">
        <section class="portal-panel portal-panel-chart">
            <div class="portal-panel-header">
                <div>
                    <span class="portal-panel-kicker">FINANCEIRO</span>
                    <h2>Evolução dos últimos 6 meses</h2>
                </div>
                <div class="portal-chart-legend">
                    <span><i class="portal-dot portal-dot-blue"></i>Previsto</span>
                    <span><i class="portal-dot portal-dot-green"></i>Recebido</span>
                </div>
            </div>
            <div class="portal-chart-summary">
                <div><span>Previsto este mês</span><strong>{{ expected_month|floatformat:2 }} €</strong></div>
                <div><span>Recebido este mês</span><strong>{{ received_month|floatformat:2 }} €</strong></div>
                <div><span>Em aberto</span><strong>{{ outstanding_total|floatformat:2 }} €</strong></div>
            </div>
            <div class="portal-line-chart" role="img" aria-label="Gráfico de valores previstos e recebidos nos últimos seis meses">
                <svg viewBox="0 0 620 220" preserveAspectRatio="none">
                    <defs>
                        <linearGradient id="portalAreaBlue" x1="0" y1="0" x2="0" y2="1">
                            <stop offset="0" stop-color="#2684ff" stop-opacity=".28"/>
                            <stop offset="1" stop-color="#2684ff" stop-opacity="0"/>
                        </linearGradient>
                    </defs>
                    <g class="portal-chart-grid">
                        <line x1="18" y1="30" x2="602" y2="30"/><line x1="18" y1="75" x2="602" y2="75"/>
                        <line x1="18" y1="120" x2="602" y2="120"/><line x1="18" y1="165" x2="602" y2="165"/>
                    </g>
                    <polyline class="portal-chart-line portal-chart-line-blue" points="{{ expected_points }}"/>
                    <polyline class="portal-chart-line portal-chart-line-green" points="{{ received_points }}"/>
                    {% for x,y in expected_coordinates %}<circle class="portal-chart-point portal-chart-point-blue" cx="{{ x }}" cy="{{ y }}" r="4"/>{% endfor %}
                    {% for x,y in received_coordinates %}<circle class="portal-chart-point portal-chart-point-green" cx="{{ x }}" cy="{{ y }}" r="4"/>{% endfor %}
                </svg>
                <div class="portal-chart-labels">
                    {% for month in monthly_finance %}<span>{{ month.label }}<small>{{ month.year }}</small></span>{% endfor %}
                </div>
            </div>
            <div class="portal-progress-block">
                <div class="portal-progress-copy"><span>Execução do mês</span><strong>{{ financial_progress }}%</strong></div>
                <div class="portal-progress portal-progress-blue" data-progress="{{ financial_progress }}"><span></span></div>
            </div>
        </section>

        <section class="portal-panel portal-panel-pipeline">
            <div class="portal-panel-header">
                <div><span class="portal-panel-kicker">RENOVAÇÕES</span><h2>Prioridades do ciclo</h2></div>
                <a href="{% url 'admin:billing_renewal_changelist' %}">Abrir agenda</a>
            </div>
            <div class="portal-pipeline-total">
                <span>Serviços em observação</span>
                <strong>{{ renewal_buckets.0.count|add:renewal_buckets.1.count|add:renewal_buckets.2.count|add:renewal_buckets.3.count }}</strong>
            </div>
            <div class="portal-pipeline-list">
                {% for bucket in renewal_buckets %}
                <div class="portal-pipeline-item">
                    <div class="portal-pipeline-copy"><span>{{ bucket.label }}</span><strong>{{ bucket.count }}</strong></div>
                    <div class="portal-progress portal-progress-{{ bucket.tone }}" data-progress="{{ bucket.percentage }}"><span></span></div>
                </div>
                {% endfor %}
            </div>
            <div class="portal-quick-actions">
                <a href="{% url 'admin:billing_renewal_add' %}"><span class="material-symbols-outlined">event_repeat</span>Criar renovação</a>
                <a href="{% url 'admin:notifications_notificationlog_add' %}"><span class="material-symbols-outlined">send</span>Nova comunicação</a>
                <a href="{% url 'admin:operations_internaltask_add' %}"><span class="material-symbols-outlined">add_task</span>Nova tarefa</a>
                <a href="{% url 'admin:support_supportticket_add' %}"><span class="material-symbols-outlined">support_agent</span>Registar pedido</a>
            </div>
        </section>
    </div>

    <div class="portal-layout portal-layout-content">
        <section class="portal-panel portal-panel-table">
            <div class="portal-panel-header">
                <div><span class="portal-panel-kicker">AGENDA</span><h2>Renovações urgentes</h2></div>
                <a href="{% url 'admin:services_service_changelist' %}">Ver todos os serviços</a>
            </div>
            <div class="portal-table-wrap">
                <table class="portal-table">
                    <thead><tr><th>Cliente / serviço</th><th>Tipo</th><th>Renovação</th><th>Dias</th><th>Valor</th><th></th></tr></thead>
                    <tbody>
                    {% for service in upcoming_services %}
                    <tr>
                        <td><strong>{{ service.client }}</strong><span>{{ service.name }}</span></td>
                        <td><span class="portal-tag">{{ service.get_service_type_display }}</span></td>
                        <td>{{ service.next_renewal_date|date:"d/m/Y" }}</td>
                        <td><span class="portal-days {% if service.days_until_renewal <= 7 %}is-critical{% endif %}">{{ service.days_until_renewal }}</span></td>
                        <td><strong>{{ service.sale_price|floatformat:2 }} €</strong></td>
                        <td><a class="portal-row-link" href="{% url 'admin:services_service_change' service.pk %}"><span class="material-symbols-outlined">chevron_right</span></a></td>
                    </tr>
                    {% empty %}<tr><td colspan="6" class="portal-empty">Sem renovações nos próximos 30 dias.</td></tr>{% endfor %}
                    </tbody>
                </table>
            </div>
        </section>

        <section class="portal-panel portal-panel-distribution">
            <div class="portal-panel-header">
                <div><span class="portal-panel-kicker">CARTEIRA</span><h2>Serviços ativos</h2></div>
            </div>
            <div class="portal-donut-wrap">
                <div class="portal-donut" style="--portal-donut: {{ service_distribution_gradient }}">
                    <div><strong>{{ service_distribution_total }}</strong><span>Total</span></div>
                </div>
                <ul class="portal-distribution-list">
                    {% for item in service_distribution %}
                    <li><i style="--item-color: {{ item.color }}"></i><span>{{ item.label }}</span><strong>{{ item.count }}</strong><small>{{ item.percentage }}%</small></li>
                    {% empty %}<li class="portal-empty-list">Sem serviços ativos.</li>{% endfor %}
                </ul>
            </div>
        </section>
    </div>

    <div class="portal-layout portal-layout-three">
        <section class="portal-panel">
            <div class="portal-panel-header">
                <div><span class="portal-panel-kicker">SUPORTE</span><h2>Pedidos em aberto</h2></div>
                <a href="{% url 'admin:support_supportticket_changelist' %}">Ver todos</a>
            </div>
            <ul class="portal-activity-list">
                {% for ticket in open_tickets %}
                <li>
                    <span class="portal-activity-icon portal-activity-icon-violet material-symbols-outlined">support_agent</span>
                    <div><a href="{% url 'admin:support_supportticket_change' ticket.pk %}">{{ ticket.subject }}</a><span>{{ ticket.client }} · {{ ticket.get_category_display }}</span></div>
                    <strong class="portal-status portal-status-{{ ticket.priority }}">{{ ticket.get_priority_display }}</strong>
                </li>
                {% empty %}<li class="portal-empty-list">Sem pedidos de suporte em aberto.</li>{% endfor %}
            </ul>
        </section>

        <section class="portal-panel">
            <div class="portal-panel-header">
                <div><span class="portal-panel-kicker">OPERAÇÕES</span><h2>Tarefas em aberto</h2></div>
                <a href="{% url 'admin:operations_internaltask_changelist' %}">Ver todas</a>
            </div>
            <ul class="portal-activity-list">
                {% for task in pending_tasks %}
                <li>
                    <span class="portal-activity-icon portal-activity-icon-blue material-symbols-outlined">task_alt</span>
                    <div><a href="{% url 'admin:operations_internaltask_change' task.pk %}">{{ task.title }}</a><span>{{ task.client|default:"Sem cliente" }} · {{ task.get_status_display }}</span></div>
                    <strong class="{% if task.is_overdue %}portal-danger{% endif %}">{{ task.due_date|date:"d/m"|default:"—" }}</strong>
                </li>
                {% empty %}<li class="portal-empty-list">Sem tarefas em aberto.</li>{% endfor %}
            </ul>
        </section>

        <section class="portal-panel">
            <div class="portal-panel-header">
                <div><span class="portal-panel-kicker">COBRANÇAS</span><h2>Pagamentos pendentes</h2></div>
                <a href="{% url 'admin:billing_payment_changelist' %}">Ver todos</a>
            </div>
            <ul class="portal-activity-list">
                {% for payment in pending_payments %}
                <li>
                    <span class="portal-activity-icon portal-activity-icon-coral material-symbols-outlined">payments</span>
                    <div><a href="{% url 'admin:billing_payment_change' payment.pk %}">{{ payment.client }}</a><span>{{ payment.renewal.service.name }} · {{ payment.get_status_display }}</span></div>
                    <strong>{{ payment.amount|floatformat:2 }} €</strong>
                </li>
                {% empty %}<li class="portal-empty-list">Sem pagamentos pendentes.</li>{% endfor %}
            </ul>
        </section>
    </div>

    <div class="portal-layout portal-layout-three portal-layout-lower">
        <section class="portal-panel">
            <div class="portal-panel-header"><div><span class="portal-panel-kicker">CLIENTES</span><h2>Valor previsto em {{ year }}</h2></div></div>
            <div class="portal-ranking-list">
                {% for client in top_clients %}
                <div class="portal-ranking-item">
                    <div><span>{{ forloop.counter }}</span><strong>{{ client.service__client__name }}</strong><small>{{ client.services }} serviço{{ client.services|pluralize }}</small></div>
                    <b>{{ client.total|floatformat:2 }} €</b>
                    <div class="portal-ranking-bar"><i style="width: {{ client.percentage }}%"></i></div>
                </div>
                {% empty %}<div class="portal-empty-list">Sem dados financeiros anuais.</div>{% endfor %}
            </div>
        </section>

        <section class="portal-panel">
            <div class="portal-panel-header"><div><span class="portal-panel-kicker">QUALIDADE</span><h2>Dados a rever</h2></div><a href="{% url 'quality_center' %}">Corrigir {{ data_quality_total }}</a></div>
            <ul class="portal-quality-list">
                <li><span>Serviços recorrentes sem data</span><strong>{{ data_quality.services_without_date }}</strong></li>
                <li><span>Serviços sem valor definido</span><strong>{{ data_quality.services_without_value }}</strong></li>
                <li><span>Clientes sem email</span><strong>{{ data_quality.clients_without_email }}</strong></li>
                <li><span>Domínios sem registador</span><strong>{{ data_quality.domains_without_registrar }}</strong></li>
                <li><span>Documentos sem ficheiro</span><strong>{{ data_quality.documents_without_file }}</strong></li>
            </ul>
        </section>

        <section class="portal-panel">
            <div class="portal-panel-header"><div><span class="portal-panel-kicker">INFRAESTRUTURA</span><h2>Saúde técnica</h2></div><a href="{% url 'monitoring_center' %}">Monitorização</a></div>
            <div class="portal-health-grid">
                <div><span class="material-symbols-outlined">developer_board</span><strong>{{ infrastructure.assets_total }}</strong><small>Ativos registados</small></div>
                <div><span class="material-symbols-outlined">warning</span><strong>{{ infrastructure.assets_attention }}</strong><small>Requerem atenção</small></div>
                <div><span class="material-symbols-outlined">lock_open</span><strong>{{ infrastructure.ssl_missing }}</strong><small>Sem SSL</small></div>
                <div><span class="material-symbols-outlined">backup</span><strong>{{ infrastructure.failed_backups }}</strong><small>Backups falhados</small></div>
                <div><span class="material-symbols-outlined">web</span><strong>{{ infrastructure.wordpress_attention }}</strong><small>WordPress com alertas</small></div>
                <div><span class="material-symbols-outlined">bug_report</span><strong>{{ infrastructure.plugins_vulnerable }}</strong><small>Plugins vulneráveis</small></div>
                <div><span class="material-symbols-outlined">system_update</span><strong>{{ infrastructure.plugins_updates }}</strong><small>Plugins a atualizar</small></div>
                <div><span class="material-symbols-outlined">lock_clock</span><strong>{{ infrastructure.ssl_expiring }}</strong><small>SSL a expirar</small></div>
                <div><span class="material-symbols-outlined">monitor_heart</span><strong>{{ infrastructure.monitors_total }}</strong><small>Monitores ativos</small></div>
                <div><span class="material-symbols-outlined">cloud_off</span><strong>{{ infrastructure.monitors_down }}</strong><small>Websites indisponíveis</small></div>
                <div><span class="material-symbols-outlined">speed</span><strong>{{ infrastructure.monitors_degraded }}</strong><small>Desempenho degradado</small></div>
                <div><span class="material-symbols-outlined">query_stats</span><strong>{% if infrastructure.monitor_uptime_24h is not None %}{{ infrastructure.monitor_uptime_24h }}%{% else %}—{% endif %}</strong><small>Uptime 24h</small></div>
            </div>
            <div class="portal-panel-header portal-communications-title"><div><span class="portal-panel-kicker">ATIVIDADE</span><h2>Comunicações recentes</h2></div></div>
            <ul class="portal-mini-list">
                {% for notification in recent_notifications %}
                <li><span>{{ notification.subject|default:"Sem assunto" }}</span><strong>{{ notification.get_status_display }}</strong></li>
                {% empty %}<li class="portal-empty-list">Sem comunicações recentes.</li>{% endfor %}
            </ul>
        </section>
    </div>
</div>
{% endblock %}
