{% extends "base.html" %}
{% block title %}Informes{% endblock %}
{% block page_title %}Informes — {{ año }}{% endblock %}

{% block topbar_actions %}
<form class="d-flex gap-2" method="get">
  <select name="año" class="form-select form-select-sm" style="width:120px">
    {% for a in años_disponibles %}
    <option value="{{ a }}" {% if a == año %}selected{% endif %}>{{ a }}</option>
    {% endfor %}
  </select>
  <button class="btn btn-sm btn-outline-secondary">Ver</button>
</form>
<button onclick="window.print()" class="btn btn-sm btn-outline-secondary no-print">
  <i class="bi bi-printer me-1"></i>Imprimir / PDF
</button>
<a href="{{ url_for('informes.exportar') }}?año={{ año }}" class="btn btn-sm btn-success">
  <i class="bi bi-file-earmark-excel"></i> Exportar Excel
</a>
{% endblock %}

{% block content %}

<!-- KPIs año -->
<div class="row g-3 mb-4">
  <div class="col-md-4">
    <div class="card">
      <div class="card-body text-center py-4">
        <div class="text-muted small mb-1">Ingresos {{ año }}</div>
        <div class="fw-bold text-success fs-3">{{ "%.2f"|format(total_ingresos) }} €</div>
      </div>
    </div>
  </div>
  <div class="col-md-4">
    <div class="card">
      <div class="card-body text-center py-4">
        <div class="text-muted small mb-1">Gastos {{ año }}</div>
        <div class="fw-bold text-danger fs-3">{{ "%.2f"|format(total_gastos) }} €</div>
      </div>
    </div>
  </div>
  <div class="col-md-4">
    <div class="card">
      <div class="card-body text-center py-4">
        <div class="text-muted small mb-1">Beneficio neto {{ año }}</div>
        <div class="fw-bold fs-3 {% if total_beneficio >= 0 %}text-success{% else %}text-danger{% endif %}">
          {{ "%.2f"|format(total_beneficio) }} €
        </div>
      </div>
    </div>
  </div>
</div>

<!-- Tabla mensual P&L -->
<div class="card mb-4">
  <div class="card-header py-3"><i class="bi bi-table me-2"></i>Cuenta de resultados mensual</div>
  <div class="table-responsive">
    <table class="table table-hover mb-0">
      <thead>
        <tr>
          <th>Mes</th>
          <th class="text-end text-success">Ingresos</th>
          <th class="text-end text-danger">Gastos</th>
          <th class="text-end">Beneficio</th>
          <th style="width:200px">Margen</th>
        </tr>
      </thead>
      <tbody>
        {% for m in meses_data %}
        <tr>
          <td class="fw-semibold">{{ m.mes }}</td>
          <td class="text-end text-success">{{ "%.2f"|format(m.ingresos) }} €</td>
          <td class="text-end text-danger">{{ "%.2f"|format(m.gastos) }} €</td>
          <td class="text-end fw-bold {% if m.beneficio >= 0 %}text-success{% else %}text-danger{% endif %}">
            {{ "%.2f"|format(m.beneficio) }} €
          </td>
          <td>
            {% if m.ingresos > 0 %}
            {% set pct = (m.beneficio / m.ingresos * 100)|round(1) %}
            <div class="progress" style="height:8px">
              <div class="progress-bar {% if pct >= 0 %}bg-success{% else %}bg-danger{% endif %}"
                   style="width:{{ [pct|abs, 100]|min }}%"></div>
            </div>
            <small class="text-muted">{{ pct }}%</small>
            {% else %}
            <span class="text-muted small">—</span>
            {% endif %}
          </td>
        </tr>
        {% endfor %}
      </tbody>
      <tfoot class="table-dark">
        <tr>
          <td class="fw-bold">TOTAL</td>
          <td class="text-end fw-bold text-success">{{ "%.2f"|format(total_ingresos) }} €</td>
          <td class="text-end fw-bold text-danger">{{ "%.2f"|format(total_gastos) }} €</td>
          <td class="text-end fw-bold {% if total_beneficio >= 0 %}text-success{% else %}text-danger{% endif %}">
            {{ "%.2f"|format(total_beneficio) }} €
          </td>
          <td></td>
        </tr>
      </tfoot>
    </table>
  </div>
</div>

<!-- Gráfica anual -->
<div class="row g-3 mb-4">
  <div class="col-lg-8">
    <div class="card">
      <div class="card-header py-3"><i class="bi bi-bar-chart me-2"></i>Evolución mensual</div>
      <div class="card-body">
        <canvas id="chartAnual" height="100"></canvas>
      </div>
    </div>
  </div>
  <div class="col-lg-4">
    <div class="card h-100">
      <div class="card-header py-3"><i class="bi bi-pie-chart me-2"></i>Distribución gastos</div>
      <div class="card-body d-flex align-items-center justify-content-center">
        {% if gastos_cat %}
        <canvas id="chartGasCat" height="200"></canvas>
        {% else %}
        <div class="text-muted small text-center">Sin datos de gastos</div>
        {% endif %}
      </div>
    </div>
  </div>
</div>

<!-- Top clientes / proveedores -->
<div class="row g-3">
  <div class="col-md-6">
    <div class="card">
      <div class="card-header py-3"><i class="bi bi-trophy me-2"></i>Top clientes {{ año }}</div>
      <div class="table-responsive">
        <table class="table table-sm mb-0">
          <thead><tr><th>#</th><th>Cliente</th><th class="text-end">Facturas</th><th class="text-end">Importe</th></tr></thead>
          <tbody>
            {% for c in top_clientes %}
            <tr>
              <td class="text-muted small">{{ loop.index }}</td>
              <td class="small fw-semibold">{{ c.nombre }}</td>
              <td class="text-end small">{{ c.num_facturas }}</td>
              <td class="text-end fw-semibold text-success small">{{ "%.2f"|format(c.facturado) }} €</td>
            </tr>
            {% else %}
            <tr><td colspan="4" class="text-center text-muted py-3 small">Sin datos</td></tr>
            {% endfor %}
          </tbody>
        </table>
      </div>
    </div>
  </div>
  <div class="col-md-6">
    <div class="card">
      <div class="card-header py-3"><i class="bi bi-truck me-2"></i>Top proveedores {{ año }}</div>
      <div class="table-responsive">
        <table class="table table-sm mb-0">
          <thead><tr><th>#</th><th>Proveedor</th><th class="text-end">Facturas</th><th class="text-end">Importe</th></tr></thead>
          <tbody>
            {% for p in top_proveedores %}
            <tr>
              <td class="text-muted small">{{ loop.index }}</td>
              <td class="small fw-semibold">{{ p.nombre }}</td>
              <td class="text-end small">{{ p.num_facturas }}</td>
              <td class="text-end fw-semibold text-danger small">{{ "%.2f"|format(p.facturado) }} €</td>
            </tr>
            {% else %}
            <tr><td colspan="4" class="text-center text-muted py-3 small">Sin datos</td></tr>
            {% endfor %}
          </tbody>
        </table>
      </div>
    </div>
  </div>
</div>

{% endblock %}

{% block extra_scripts %}
<script>
const meses = {{ meses_data | map(attribute='mes') | list | tojson }};
const ingresos = {{ meses_data | map(attribute='ingresos') | list | tojson }};
const gastos = {{ meses_data | map(attribute='gastos') | list | tojson }};
const beneficios = {{ meses_data | map(attribute='beneficio') | list | tojson }};

new Chart(document.getElementById('chartAnual'), {
  type: 'bar',
  data: {
    labels: meses,
    datasets: [
      { label: 'Ingresos', data: ingresos, backgroundColor: 'rgba(40,167,69,.7)', borderRadius: 4 },
      { label: 'Gastos',   data: gastos,   backgroundColor: 'rgba(220,53,69,.7)',  borderRadius: 4 },
      { label: 'Beneficio', data: beneficios, type: 'line', borderColor: '#007bff',
        backgroundColor: 'rgba(0,123,255,.1)', fill: true, tension: .3, pointRadius: 4 },
    ]
  },
  options: {
    plugins: { legend: { position: 'top' } },
    scales: { y: { beginAtZero: true, ticks: { callback: v => v + ' €' } } },
    responsive: true,
  }
});

{% if gastos_cat %}
new Chart(document.getElementById('chartGasCat'), {
  type: 'doughnut',
  data: {
    labels: {{ gastos_cat | map(attribute='nombre') | list | tojson }},
    datasets: [{ data: {{ gastos_cat | map(attribute='total') | list | tojson }},
                 backgroundColor: {{ gastos_cat | map(attribute='color') | list | tojson }}, borderWidth: 2 }]
  },
  options: { plugins: { legend: { position: 'bottom', labels: { font: { size: 10 } } } }, cutout: '60%' }
});
{% endif %}
</script>
{% endblock %}
