{% extends "base.html" %}
{% block title %}VeriFactu{% endblock %}
{% block page_title %}VeriFactu — Facturación electrónica AEAT{% endblock %}

{% block topbar_actions %}
{% if not cfg.activo %}
<a href="{{ url_for('verifactu.configuracion') }}" class="btn btn-warning btn-sm">
  <i class="bi bi-gear me-1"></i>Configurar VeriFactu
</a>
{% else %}
<form method="post" action="{{ url_for('verifactu.generar_lote') }}" class="d-inline">
  <button class="btn btn-primary btn-sm">
    <i class="bi bi-lightning me-1"></i>Generar lote sin huella
  </button>
</form>
<a href="{{ url_for('verifactu.xml_lote') }}" class="btn btn-success btn-sm">
  <i class="bi bi-file-earmark-code me-1"></i>Exportar XML pendientes
</a>
<a href="{{ url_for('verifactu.configuracion') }}" class="btn btn-outline-secondary btn-sm">
  <i class="bi bi-gear"></i>
</a>
{% endif %}
{% endblock %}

{% block content %}

{% if not cfg.activo %}
<div class="alert alert-warning d-flex gap-3 align-items-start mb-4">
  <i class="bi bi-exclamation-triangle-fill fs-3 flex-shrink-0"></i>
  <div>
    <h6 class="mb-1">VeriFactu no está activado</h6>
    <p class="mb-2 small">Para cumplir con el RD 1007/2023 debes configurar y activar VeriFactu.
    Será obligatorio para empresas y autónomos a partir de 2026.</p>
    <a href="{{ url_for('verifactu.configuracion') }}" class="btn btn-warning btn-sm">
      <i class="bi bi-gear me-1"></i>Configurar ahora
    </a>
  </div>
</div>
{% endif %}

<!-- Stats -->
<div class="row g-3 mb-4">
  {% set total = (stats.sin_generar or 0) + (stats.pendiente or 0) + (stats.enviado or 0) + (stats.rechazado or 0) %}
  <div class="col-sm-6 col-lg-3">
    <div class="stat-card" style="background:linear-gradient(135deg,#4f86f7,#3a6fd8)">
      <div class="d-flex align-items-start justify-content-between">
        <div>
          <div class="small mb-1 fw-semibold opacity-85">Total facturas</div>
          <div class="fw-bold fs-4">{{ total }}</div>
        </div>
        <div class="rounded-circle d-flex align-items-center justify-content-center bg-white bg-opacity-25" style="width:40px;height:40px;flex-shrink:0">
          <i class="bi bi-files text-white"></i>
        </div>
      </div>
    </div>
  </div>
  <div class="col-sm-6 col-lg-3">
    <div class="stat-card" style="background:linear-gradient(135deg,#94a3b8,#64748b)">
      <div class="d-flex align-items-start justify-content-between">
        <div>
          <div class="small mb-1 fw-semibold opacity-85">Sin huella</div>
          <div class="fw-bold fs-4">{{ stats.sin_generar or 0 }}</div>
        </div>
        <div class="rounded-circle d-flex align-items-center justify-content-center bg-white bg-opacity-25" style="width:40px;height:40px;flex-shrink:0">
          <i class="bi bi-dash-circle text-white"></i>
        </div>
      </div>
    </div>
  </div>
  <div class="col-sm-6 col-lg-3">
    <div class="stat-card" style="background:linear-gradient(135deg,#f59e0b,#d97706)">
      <div class="d-flex align-items-start justify-content-between">
        <div>
          <div class="small mb-1 fw-semibold opacity-85">Pendientes de envío</div>
          <div class="fw-bold fs-4">{{ stats.pendiente or 0 }}</div>
        </div>
        <div class="rounded-circle d-flex align-items-center justify-content-center bg-white bg-opacity-25" style="width:40px;height:40px;flex-shrink:0">
          <i class="bi bi-clock text-white"></i>
        </div>
      </div>
    </div>
  </div>
  <div class="col-sm-6 col-lg-3">
    <div class="stat-card" style="background:linear-gradient(135deg,#10b981,#059669)">
      <div class="d-flex align-items-start justify-content-between">
        <div>
          <div class="small mb-1 fw-semibold opacity-85">Enviadas a AEAT</div>
          <div class="fw-bold fs-4">{{ stats.enviado or 0 }}</div>
        </div>
        <div class="rounded-circle d-flex align-items-center justify-content-center bg-white bg-opacity-25" style="width:40px;height:40px;flex-shrink:0">
          <i class="bi bi-check-circle text-white"></i>
        </div>
      </div>
    </div>
  </div>
</div>

<!-- Filtros -->
<div class="card mb-3 border-0 shadow-sm">
  <div class="card-body py-2">
    <div class="d-flex gap-2 flex-wrap">
      {% for f, lbl, col in [('todos','Todas','secondary'),('sin_generar','Sin huella','secondary'),('pendiente','Pendientes','warning'),('enviado','Enviadas','success'),('rechazado','Rechazadas','danger')] %}
      <a href="{{ url_for('verifactu.index', estado=f) }}"
         class="btn btn-sm {% if filtro==f %}btn-{{ col }}{% else %}btn-outline-{{ col }}{% endif %}">
        {{ lbl }}
        {% if f != 'todos' and stats.get(f) %}
        <span class="badge bg-white text-{{ col }} ms-1">{{ stats[f] }}</span>
        {% endif %}
      </a>
      {% endfor %}
      <a href="{{ url_for('verifactu.verificar_cadena') }}" class="btn btn-sm btn-outline-primary ms-auto"
         target="_blank">
        <i class="bi bi-shield-check me-1"></i>Verificar cadena
      </a>
    </div>
  </div>
</div>

<!-- Tabla -->
<div class="card border-0 shadow-sm">
  <div class="card-body p-0">
    <div class="table-responsive">
      <table class="table table-hover mb-0" style="font-size:.845rem">
        <thead>
          <tr>
            <th>Nº Factura</th>
            <th>Fecha</th>
            <th>Cliente</th>
            <th class="text-end">Total</th>
            <th class="text-center">Estado VeriFactu</th>
            <th>Huella SHA-256</th>
            <th class="text-center no-print">Acciones</th>
          </tr>
        </thead>
        <tbody>
          {% for f in facturas %}
          {% set vf_est = f.vf_estado or 'sin_generar' %}
          <tr>
            <td class="font-monospace fw-semibold">{{ f.numero }}</td>
            <td>{{ f.fecha }}</td>
            <td>{{ f.cliente or '—' }}</td>
            <td class="text-end fw-semibold">{{ "%.2f"|format(f.total or 0) }} €</td>
            <td class="text-center">
              {% if vf_est == 'enviado' %}
                <span class="badge" style="background:#dcfce7;color:#14532d;border:1px solid #86efac">
                  <i class="bi bi-check2-circle me-1"></i>Enviado
                </span>
              {% elif vf_est == 'pendiente' %}
                <span class="badge" style="background:#fef3c7;color:#92400e;border:1px solid #fcd34d">
                  <i class="bi bi-clock me-1"></i>Pendiente
                </span>
              {% elif vf_est == 'rechazado' %}
                <span class="badge" style="background:#fee2e2;color:#7f1d1d;border:1px solid #fca5a5">
                  <i class="bi bi-x-circle me-1"></i>Rechazado
                </span>
              {% else %}
                <span class="badge" style="background:#f1f5f9;color:#475569;border:1px solid #cbd5e1">
                  <i class="bi bi-dash me-1"></i>Sin huella
                </span>
              {% endif %}
            </td>
            <td class="font-monospace" style="font-size:.73rem;color:#64748b;max-width:200px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap">
              {{ f.vf_huella or '—' }}
            </td>
            <td class="text-center no-print">
              <div class="d-flex gap-1 justify-content-center">
                <a href="{{ url_for('verifactu.detalle', id=f.id) }}"
                   class="btn btn-sm btn-outline-primary btn-action" title="Detalle">
                  <i class="bi bi-eye"></i>
                </a>
                {% if vf_est == 'sin_generar' %}
                <form method="post" action="{{ url_for('verifactu.generar', id=f.id) }}" class="d-inline">
                  <button class="btn btn-sm btn-outline-secondary btn-action" title="Generar huella">
                    <i class="bi bi-lightning"></i>
                  </button>
                </form>
                {% endif %}
                {% if vf_est == 'pendiente' %}
                <a href="{{ url_for('verifactu.xml_factura', id=f.id) }}"
                   class="btn btn-sm btn-outline-success btn-action" title="Descargar XML">
                  <i class="bi bi-file-earmark-code"></i>
                </a>
                <form method="post" action="{{ url_for('verifactu.marcar_enviado', id=f.id) }}" class="d-inline">
                  <button class="btn btn-sm btn-outline-success btn-action" title="Marcar como enviada">
                    <i class="bi bi-check2"></i>
                  </button>
                </form>
                {% endif %}
              </div>
            </td>
          </tr>
          {% else %}
          <tr>
            <td colspan="7" class="text-center py-5 text-muted">
              <i class="bi bi-file-earmark-x fs-1 d-block mb-2 opacity-30"></i>
              No hay facturas en este filtro
            </td>
          </tr>
          {% endfor %}
        </tbody>
      </table>
    </div>
  </div>
  {% if total_rows > per_page %}
  <div class="card-footer border-0 bg-transparent d-flex justify-content-between align-items-center py-2">
    <small class="text-muted">Mostrando {{ facturas|length }} de {{ total_rows }}</small>
    <div class="d-flex gap-1">
      {% if page > 1 %}
      <a href="{{ url_for('verifactu.index', estado=filtro, page=page-1) }}" class="btn btn-sm btn-outline-secondary">
        <i class="bi bi-chevron-left"></i>
      </a>
      {% endif %}
      <span class="btn btn-sm disabled">{{ page }}</span>
      {% if page * per_page < total_rows %}
      <a href="{{ url_for('verifactu.index', estado=filtro, page=page+1) }}" class="btn btn-sm btn-outline-secondary">
        <i class="bi bi-chevron-right"></i>
      </a>
      {% endif %}
    </div>
  </div>
  {% endif %}
</div>

{% endblock %}
