{% extends "base.html" %}
{% block title %}Libro de IVA{% endblock %}
{% block page_title %}Libro de IVA{% endblock %}

{% block topbar_actions %}
<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_iva', año=año, trim=trim) }}"
   class="btn btn-success btn-sm">
  <i class="bi bi-file-earmark-excel me-1"></i>Exportar Excel
</a>
{% endblock %}

{% block extra_head %}
<style>
  .cuota-pos { color: #065f46; font-weight: 700; }
  .cuota-neg { color: #991b1b; font-weight: 700; }
  .trim-card { border-radius: 12px; padding: 18px 20px; }
</style>
{% endblock %}

{% block content %}

<!-- Filtros -->
<div class="card mb-4">
  <div class="card-body py-3">
    <form method="get" class="d-flex align-items-center gap-3 flex-wrap">
      <div class="d-flex align-items-center gap-2">
        <label class="form-label mb-0 fw-semibold">Año:</label>
        <select name="año" class="form-select form-select-sm" style="width:100px" onchange="this.form.submit()">
          {% for a in años_disponibles %}
          <option value="{{ a }}" {% if a == año %}selected{% endif %}>{{ a }}</option>
          {% endfor %}
        </select>
      </div>
      <div class="d-flex align-items-center gap-2">
        <label class="form-label mb-0 fw-semibold">Período:</label>
        {% for val, lbl in [('anual','Anual'),('1','T1 (Ene–Mar)'),('2','T2 (Abr–Jun)'),('3','T3 (Jul–Sep)'),('4','T4 (Oct–Dic)')] %}
        <a href="?año={{ año }}&trim={{ val }}"
           class="btn btn-sm {% if trim == val %}btn-primary{% else %}btn-outline-secondary{% endif %}">
          {{ lbl }}
        </a>
        {% endfor %}
      </div>
    </form>
  </div>
</div>

<!-- Resumen trimestral (siempre visible) -->
<div class="row g-3 mb-4">
  {% for t in trimestres %}
  <div class="col-md-3">
    <div class="trim-card {% if t.cuota >= 0 %}bg-danger-subtle{% else %}bg-success-subtle{% endif %} border">
      <div class="fw-bold mb-2">{{ t.label }} — {{ año }}</div>
      <div class="d-flex justify-content-between small text-muted mb-1">
        <span>IVA repercutido</span><span>{{ "%.2f"|format(t.iva_repercutido) }} €</span>
      </div>
      <div class="d-flex justify-content-between small text-muted mb-2">
        <span>IVA soportado</span><span>{{ "%.2f"|format(t.iva_soportado) }} €</span>
      </div>
      <div class="d-flex justify-content-between fw-bold">
        <span>A {% if t.cuota >= 0 %}ingresar{% else %}devolver{% endif %}</span>
        <span class="{% if t.cuota >= 0 %}text-danger{% else %}text-success{% endif %}">
          {{ "%.2f"|format(t.cuota|abs) }} €
        </span>
      </div>
    </div>
  </div>
  {% endfor %}
</div>

<!-- Liquidación del período seleccionado -->
<div class="row g-3 mb-4">
  <div class="col-md-4">
    <div class="card h-100">
      <div class="card-body">
        <div class="text-muted small fw-semibold mb-3">LIQUIDACIÓN — {{ fecha_ini }} a {{ fecha_fin }}</div>
        <table class="table table-sm mb-0">
          <tr>
            <td class="text-muted">IVA repercutido</td>
            <td class="text-end">{{ "%.2f"|format(tot_rep_iva) }} €</td>
          </tr>
          {% if tot_rect_iva > 0 %}
          <tr>
            <td class="text-muted text-danger">— Rectificativas</td>
            <td class="text-end text-danger">−{{ "%.2f"|format(tot_rect_iva) }} €</td>
          </tr>
          {% endif %}
          <tr class="table-light">
            <td class="fw-semibold">IVA repercutido neto</td>
            <td class="text-end fw-semibold">{{ "%.2f"|format(iva_repercutido_neto) }} €</td>
          </tr>
          <tr>
            <td class="text-muted">IVA soportado</td>
            <td class="text-end">−{{ "%.2f"|format(iva_soportado) }} €</td>
          </tr>
          <tr class="{% if cuota_diferencial >= 0 %}table-danger{% else %}table-success{% endif %} fw-bold fs-5">
            <td>{% if cuota_diferencial >= 0 %}A ingresar{% else %}A devolver{% endif %}</td>
            <td class="text-end">{{ "%.2f"|format(cuota_diferencial|abs) }} €</td>
          </tr>
        </table>
      </div>
    </div>
  </div>
  <div class="col-md-4">
    <div class="card h-100">
      <div class="card-body">
        <div class="text-muted small fw-semibold mb-3">IVA REPERCUTIDO (EMITIDAS)</div>
        <div class="d-flex justify-content-between mb-1"><span class="text-muted small">Facturas</span><span class="fw-semibold">{{ emitidas|length }}</span></div>
        <div class="d-flex justify-content-between mb-1"><span class="text-muted small">Base imponible</span><span>{{ "%.2f"|format(tot_rep_base) }} €</span></div>
        <div class="d-flex justify-content-between mb-1"><span class="text-muted small">Cuota IVA</span><span class="fw-semibold text-primary">{{ "%.2f"|format(tot_rep_iva) }} €</span></div>
        {% if rectificativas %}
        <hr class="my-2">
        <div class="d-flex justify-content-between mb-1"><span class="text-muted small">Rectificativas ({{ rectificativas|length }})</span><span class="text-danger">−{{ "%.2f"|format(tot_rect_iva) }} €</span></div>
        {% endif %}
      </div>
    </div>
  </div>
  <div class="col-md-4">
    <div class="card h-100">
      <div class="card-body">
        <div class="text-muted small fw-semibold mb-3">IVA SOPORTADO (RECIBIDAS)</div>
        <div class="d-flex justify-content-between mb-1"><span class="text-muted small">Facturas</span><span class="fw-semibold">{{ recibidas|length }}</span></div>
        <div class="d-flex justify-content-between mb-1"><span class="text-muted small">Base imponible</span><span>{{ "%.2f"|format(tot_sop_base) }} €</span></div>
        <div class="d-flex justify-content-between mb-1"><span class="text-muted small">Cuota IVA</span><span class="fw-semibold text-danger">{{ "%.2f"|format(iva_soportado) }} €</span></div>
        <div class="d-flex justify-content-between mb-1"><span class="text-muted small">IRPF retenido</span><span>{{ "%.2f"|format(tot_sop_irpf) }} €</span></div>
      </div>
    </div>
  </div>
</div>

<!-- Tabs: Emitidas / Recibidas / Rectificativas -->
<ul class="nav nav-tabs mb-0" id="tabsIVA">
  <li class="nav-item">
    <button class="nav-link active" data-bs-toggle="tab" data-bs-target="#tab-emit">
      <i class="bi bi-file-earmark-arrow-up me-1"></i>Emitidas
      <span class="badge bg-primary ms-1">{{ emitidas|length }}</span>
    </button>
  </li>
  <li class="nav-item">
    <button class="nav-link" data-bs-toggle="tab" data-bs-target="#tab-recib">
      <i class="bi bi-file-earmark-arrow-down me-1"></i>Recibidas
      <span class="badge bg-danger ms-1">{{ recibidas|length }}</span>
    </button>
  </li>
  {% if rectificativas %}
  <li class="nav-item">
    <button class="nav-link" data-bs-toggle="tab" data-bs-target="#tab-rect">
      <i class="bi bi-file-earmark-minus me-1"></i>Rectificativas
      <span class="badge bg-warning text-dark ms-1">{{ rectificativas|length }}</span>
    </button>
  </li>
  {% endif %}
</ul>

<div class="tab-content">

  <!-- Emitidas -->
  <div class="tab-pane fade show active" id="tab-emit">
    <div class="card" style="border-top-left-radius:0; border-top-right-radius:0">
      <div class="table-responsive">
        {% if emitidas %}
        <table class="table table-hover mb-0">
          <thead>
            <tr>
              <th>Número</th><th>Fecha</th><th>Cliente</th>
              <th class="text-end">Base imp.</th><th class="text-center">IVA %</th>
              <th class="text-end">Cuota IVA</th><th class="text-end">Total</th>
              <th>Estado</th>
            </tr>
          </thead>
          <tbody>
            {% for f in emitidas %}
            <tr>
              <td class="fw-semibold">{{ f.numero }}</td>
              <td>{{ f.fecha }}</td>
              <td>{{ f.cliente or '—' }}</td>
              <td class="text-end">{{ "%.2f"|format(f.subtotal) }} €</td>
              <td class="text-center">{{ f.iva_pct }}%</td>
              <td class="text-end fw-semibold text-primary">{{ "%.2f"|format(f.iva_importe) }} €</td>
              <td class="text-end">{{ "%.2f"|format(f.total) }} €</td>
              <td><span class="badge-estado-{{ f.estado }}">{{ f.estado|capitalize }}</span></td>
            </tr>
            {% endfor %}
          </tbody>
          <tfoot class="table-light fw-bold">
            <tr>
              <td colspan="3">TOTAL</td>
              <td class="text-end">{{ "%.2f"|format(tot_rep_base) }} €</td>
              <td></td>
              <td class="text-end text-primary">{{ "%.2f"|format(tot_rep_iva) }} €</td>
              <td class="text-end">{{ "%.2f"|format(tot_rep_base + tot_rep_iva - tot_rep_irpf) }} €</td>
              <td></td>
            </tr>
          </tfoot>
        </table>
        {% else %}
        <div class="text-center py-4 text-muted">No hay facturas emitidas en este período.</div>
        {% endif %}
      </div>
    </div>
  </div>

  <!-- Recibidas -->
  <div class="tab-pane fade" id="tab-recib">
    <div class="card" style="border-top-left-radius:0">
      <div class="table-responsive">
        {% if recibidas %}
        <table class="table table-hover mb-0">
          <thead>
            <tr>
              <th>Número</th><th>Fecha</th><th>Proveedor</th>
              <th class="text-end">Base imp.</th><th class="text-center">IVA %</th>
              <th class="text-end">Cuota IVA</th><th class="text-end">Total</th>
              <th>Estado</th>
            </tr>
          </thead>
          <tbody>
            {% for f in recibidas %}
            <tr>
              <td class="fw-semibold">{{ f.numero }}</td>
              <td>{{ f.fecha }}</td>
              <td>{{ f.proveedor or '—' }}</td>
              <td class="text-end">{{ "%.2f"|format(f.subtotal) }} €</td>
              <td class="text-center">{{ f.iva_pct }}%</td>
              <td class="text-end fw-semibold text-danger">{{ "%.2f"|format(f.iva_importe) }} €</td>
              <td class="text-end">{{ "%.2f"|format(f.total) }} €</td>
              <td><span class="badge-estado-{{ f.estado }}">{{ f.estado|capitalize }}</span></td>
            </tr>
            {% endfor %}
          </tbody>
          <tfoot class="table-light fw-bold">
            <tr>
              <td colspan="3">TOTAL</td>
              <td class="text-end">{{ "%.2f"|format(tot_sop_base) }} €</td>
              <td></td>
              <td class="text-end text-danger">{{ "%.2f"|format(iva_soportado) }} €</td>
              <td class="text-end">{{ "%.2f"|format(tot_sop_base + iva_soportado - tot_sop_irpf) }} €</td>
              <td></td>
            </tr>
          </tfoot>
        </table>
        {% else %}
        <div class="text-center py-4 text-muted">No hay facturas recibidas en este período.</div>
        {% endif %}
      </div>
    </div>
  </div>

  <!-- Rectificativas -->
  {% if rectificativas %}
  <div class="tab-pane fade" id="tab-rect">
    <div class="card" style="border-top-left-radius:0">
      <div class="table-responsive">
        <table class="table table-hover mb-0">
          <thead>
            <tr>
              <th>Número</th><th>Fecha</th><th>Cliente</th><th>Rectifica</th>
              <th class="text-end">Base imp.</th><th class="text-center">IVA %</th>
              <th class="text-end">Cuota IVA</th><th class="text-end">Total</th>
            </tr>
          </thead>
          <tbody>
            {% for r in rectificativas %}
            <tr>
              <td class="fw-semibold text-danger">{{ r.numero }}</td>
              <td>{{ r.fecha }}</td>
              <td>{{ r.cliente or '—' }}</td>
              <td class="text-muted small">{{ r.origen_numero or '—' }}</td>
              <td class="text-end">{{ "%.2f"|format(r.subtotal) }} €</td>
              <td class="text-center">{{ r.iva_pct }}%</td>
              <td class="text-end fw-semibold text-warning">−{{ "%.2f"|format(r.iva_importe) }} €</td>
              <td class="text-end">{{ "%.2f"|format(r.total) }} €</td>
            </tr>
            {% endfor %}
          </tbody>
          <tfoot class="table-light fw-bold">
            <tr>
              <td colspan="4">TOTAL (reduce IVA repercutido)</td>
              <td class="text-end">{{ "%.2f"|format(tot_rect_base) }} €</td>
              <td></td>
              <td class="text-end text-warning">−{{ "%.2f"|format(tot_rect_iva) }} €</td>
              <td class="text-end">{{ "%.2f"|format(tot_rect_base + tot_rect_iva) }} €</td>
            </tr>
          </tfoot>
        </table>
      </div>
    </div>
  </div>
  {% endif %}

</div>
{% endblock %}
