{% extends "base.html" %}
{% block title %}VeriFactu — {{ fac.numero }}{% endblock %}
{% block page_title %}VeriFactu — Factura {{ fac.numero }}{% endblock %}

{% block topbar_actions %}
<a href="{{ url_for('verifactu.index') }}" class="btn btn-outline-secondary btn-sm">
  <i class="bi bi-arrow-left me-1"></i>Volver
</a>
{% if fac.vf_huella %}
<a href="{{ url_for('verifactu.xml_factura', id=fac.id) }}" class="btn btn-outline-success btn-sm">
  <i class="bi bi-file-earmark-code me-1"></i>Descargar XML
</a>
{% endif %}
{% if fac.vf_estado == 'pendiente' %}
<form method="post" action="{{ url_for('verifactu.marcar_enviado', id=fac.id) }}" class="d-inline">
  <button class="btn btn-success btn-sm">
    <i class="bi bi-check2-circle me-1"></i>Marcar enviada
  </button>
</form>
{% endif %}
{% endblock %}

{% block content %}

<div class="row g-4">

  <!-- Panel izquierdo: datos + huella -->
  <div class="col-lg-8">

    <!-- Estado VeriFactu -->
    <div class="card border-0 shadow-sm mb-4">
      <div class="card-body">
        <div class="d-flex align-items-center gap-4 flex-wrap">
          <div>
            <div class="text-muted small mb-1">Estado VeriFactu</div>
            {% set vf_est = fac.vf_estado or 'sin_generar' %}
            {% if vf_est == 'enviado' %}
              <span class="badge fs-6 px-3 py-2" style="background:#dcfce7;color:#14532d;border:1px solid #86efac">
                <i class="bi bi-check2-circle me-2"></i>Enviada a AEAT
              </span>
            {% elif vf_est == 'pendiente' %}
              <span class="badge fs-6 px-3 py-2" style="background:#fef3c7;color:#92400e;border:1px solid #fcd34d">
                <i class="bi bi-clock me-2"></i>Pendiente de envío
              </span>
            {% elif vf_est == 'rechazado' %}
              <span class="badge fs-6 px-3 py-2" style="background:#fee2e2;color:#7f1d1d;border:1px solid #fca5a5">
                <i class="bi bi-x-circle me-2"></i>Rechazada por AEAT
              </span>
            {% else %}
              <span class="badge fs-6 px-3 py-2" style="background:#f1f5f9;color:#475569;border:1px solid #cbd5e1">
                <i class="bi bi-dash-circle me-2"></i>Sin huella generada
              </span>
            {% endif %}
          </div>
          {% if fac.vf_fecha_hora %}
          <div>
            <div class="text-muted small mb-1">Fecha de firma</div>
            <div class="fw-semibold">{{ fac.vf_fecha_hora }}</div>
          </div>
          {% endif %}
          {% if not fac.vf_huella %}
          <div class="ms-auto">
            <form method="post" action="{{ url_for('verifactu.generar', id=fac.id) }}">
              <button class="btn btn-primary">
                <i class="bi bi-lightning me-1"></i>Generar huella ahora
              </button>
            </form>
          </div>
          {% endif %}
        </div>
      </div>
    </div>

    <!-- Datos de la factura -->
    <div class="card border-0 shadow-sm mb-4">
      <div class="card-header border-0" style="background:linear-gradient(135deg,#eef3ff,#e0e7ff)">
        <i class="bi bi-file-earmark-text me-2 text-primary"></i>
        <span class="fw-semibold text-primary">Datos de la factura</span>
      </div>
      <div class="card-body">
        <div class="row g-3">
          <div class="col-sm-4">
            <div class="text-muted small">Número</div>
            <div class="fw-bold font-monospace">{{ fac.numero }}</div>
          </div>
          <div class="col-sm-4">
            <div class="text-muted small">Fecha</div>
            <div class="fw-semibold">{{ fac.fecha }}</div>
          </div>
          <div class="col-sm-4">
            <div class="text-muted small">Estado factura</div>
            <span class="badge-estado-{{ fac.estado }}">{{ fac.estado|capitalize }}</span>
          </div>
          <div class="col-sm-6">
            <div class="text-muted small">Cliente</div>
            <div class="fw-semibold">{{ fac.cliente or '—' }}</div>
            {% if fac.cliente_nif %}<div class="text-muted small">NIF: {{ fac.cliente_nif }}</div>{% endif %}
          </div>
          <div class="col-sm-2">
            <div class="text-muted small">Base imp.</div>
            <div class="fw-semibold">{{ "%.2f"|format(fac.subtotal or 0) }} €</div>
          </div>
          <div class="col-sm-2">
            <div class="text-muted small">Cuota IVA</div>
            <div class="fw-semibold text-primary">{{ "%.2f"|format(fac.iva_importe or 0) }} €</div>
          </div>
          <div class="col-sm-2">
            <div class="text-muted small">Total</div>
            <div class="fw-bold fs-5">{{ "%.2f"|format(fac.total or 0) }} €</div>
          </div>
        </div>
      </div>
    </div>

    <!-- Huella y encadenamiento -->
    {% if fac.vf_huella %}
    <div class="card border-0 shadow-sm mb-4">
      <div class="card-header border-0" style="background:linear-gradient(135deg,#fdf4ff,#f3e8ff)">
        <i class="bi bi-fingerprint me-2" style="color:#a855f7"></i>
        <span class="fw-semibold" style="color:#6b21a8">Cadena de huellas</span>
      </div>
      <div class="card-body">
        <div class="mb-3">
          <div class="text-muted small mb-1">Huella de esta factura (SHA-256)</div>
          <div class="p-2 rounded font-monospace" style="background:#1e293b;color:#a5f3fc;font-size:.78rem;word-break:break-all;letter-spacing:.04em">
            {{ fac.vf_huella }}
          </div>
        </div>
        {% if fac.vf_encadenamiento %}
        <div>
          <div class="text-muted small mb-1">Huella de la factura anterior (encadenamiento)</div>
          <div class="p-2 rounded font-monospace" style="background:#0f172a;color:#94a3b8;font-size:.78rem;word-break:break-all;letter-spacing:.04em">
            {{ fac.vf_encadenamiento }}
          </div>
        </div>
        {% else %}
        <div class="alert alert-info py-2 mb-0" style="font-size:.82rem">
          <i class="bi bi-info-circle me-1"></i>
          Primera factura de la cadena — no tiene encadenamiento anterior.
        </div>
        {% endif %}

        <!-- Cadena visual -->
        <div class="mt-3 d-flex align-items-center gap-2" style="font-size:.8rem;color:#64748b">
          {% if fac.vf_encadenamiento %}
          <div class="p-2 rounded text-center" style="background:#f8fafc;border:1px dashed #cbd5e1;min-width:80px">
            <i class="bi bi-file-earmark text-muted d-block"></i>
            <span>Anterior</span>
          </div>
          <div style="flex:1;height:2px;background:linear-gradient(90deg,#cbd5e1,#a855f7)"></div>
          {% endif %}
          <div class="p-2 rounded text-center fw-bold" style="background:#fdf4ff;border:2px solid #a855f7;min-width:80px;color:#6b21a8">
            <i class="bi bi-file-earmark-lock2 d-block" style="color:#a855f7"></i>
            <span>Esta</span>
          </div>
          <div style="flex:1;height:2px;background:linear-gradient(90deg,#a855f7,#cbd5e1)"></div>
          <div class="p-2 rounded text-center" style="background:#f8fafc;border:1px dashed #cbd5e1;min-width:80px">
            <i class="bi bi-file-earmark text-muted d-block"></i>
            <span>Siguiente</span>
          </div>
        </div>
      </div>
    </div>
    {% endif %}

    <!-- XML preview -->
    {% if fac.vf_huella %}
    <div class="card border-0 shadow-sm">
      <div class="card-header border-0 d-flex justify-content-between align-items-center"
           style="background:linear-gradient(135deg,#f0fdf4,#dcfce7)">
        <div>
          <i class="bi bi-code-slash me-2 text-success"></i>
          <span class="fw-semibold text-success">Vista previa XML AEAT</span>
        </div>
        <a href="{{ url_for('verifactu.xml_factura', id=fac.id) }}" class="btn btn-sm btn-outline-success">
          <i class="bi bi-download me-1"></i>Descargar
        </a>
      </div>
      <div class="card-body p-0">
        <pre class="mb-0 p-3" style="background:#0f172a;color:#86efac;font-size:.73rem;border-radius:0 0 14px 14px;overflow-x:auto;max-height:280px">&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;T:RegFactuSistemaFacturacion&gt;
  &lt;T:Cabecera&gt;
    &lt;T:IDVersionSistemaFacturacion&gt;1.0&lt;/T:IDVersionSistemaFacturacion&gt;
    &lt;T:ObligadoEmision&gt;{{ nif }}&lt;/T:ObligadoEmision&gt;
    &lt;T:Sistema&gt;{{ cfg.id_sistema or 'CONTAAPP' }}&lt;/T:Sistema&gt;
  &lt;/T:Cabecera&gt;
  &lt;T:RegistroFactura&gt;
    &lt;T:IDFactura&gt;
      &lt;T:IDEmisorFactura&gt;{{ nif }}&lt;/T:IDEmisorFactura&gt;
      &lt;T:NumSerieFactura&gt;{{ fac.numero }}&lt;/T:NumSerieFactura&gt;
      &lt;T:FechaExpedicion&gt;{{ fac.fecha.split('-')[2] }}-{{ fac.fecha.split('-')[1] }}-{{ fac.fecha.split('-')[0] }}&lt;/T:FechaExpedicion&gt;
    &lt;/T:IDFactura&gt;
    &lt;T:TipoFactura&gt;F1&lt;/T:TipoFactura&gt;
    &lt;T:Importes&gt;
      &lt;T:BaseImponible&gt;{{ "%.2f"|format(fac.subtotal or 0) }}&lt;/T:BaseImponible&gt;
      &lt;T:CuotaRepercutida&gt;{{ "%.2f"|format(fac.iva_importe or 0) }}&lt;/T:CuotaRepercutida&gt;
      &lt;T:ImporteTotal&gt;{{ "%.2f"|format(fac.total or 0) }}&lt;/T:ImporteTotal&gt;
    &lt;/T:Importes&gt;
    &lt;T:Huella&gt;{{ fac.vf_huella }}&lt;/T:Huella&gt;
  &lt;/T:RegistroFactura&gt;
&lt;/T:RegFactuSistemaFacturacion&gt;</pre>
      </div>
    </div>
    {% endif %}

  </div>

  <!-- Panel derecho: QR -->
  <div class="col-lg-4">

    {% if qr_ok and fac.vf_huella and nif %}
    <div class="card border-0 shadow-sm mb-4 text-center">
      <div class="card-header border-0" style="background:linear-gradient(135deg,#eef3ff,#e0e7ff)">
        <i class="bi bi-qr-code me-2 text-primary"></i>
        <span class="fw-semibold text-primary">QR de verificación AEAT</span>
      </div>
      <div class="card-body">
        <img src="{{ url_for('verifactu.qr_png', id=fac.id) }}"
             alt="QR VeriFactu {{ fac.numero }}"
             style="width:180px;height:180px;image-rendering:pixelated;border:4px solid #e0e7ff;border-radius:12px">
        <div class="mt-3 text-muted small">
          <i class="bi bi-phone me-1"></i>Escanea para verificar en la AEAT
        </div>
        {% if qr_url %}
        <div class="mt-2">
          <a href="{{ qr_url }}" target="_blank" class="btn btn-sm btn-outline-primary">
            <i class="bi bi-box-arrow-up-right me-1"></i>Abrir URL de verificación
          </a>
        </div>
        {% endif %}
      </div>
    </div>
    {% elif not fac.vf_huella %}
    <div class="card border-0 shadow-sm mb-4">
      <div class="card-body text-center py-5">
        <i class="bi bi-qr-code text-muted" style="font-size:3rem;opacity:.3"></i>
        <p class="text-muted mt-3 small">Genera la huella para<br>obtener el QR de verificación</p>
      </div>
    </div>
    {% elif not nif %}
    <div class="card border-0 shadow-sm mb-4">
      <div class="card-body">
        <div class="alert alert-warning py-2 mb-0" style="font-size:.82rem">
          <i class="bi bi-exclamation-triangle me-1"></i>
          Configura el NIF de empresa para generar el QR.
        </div>
      </div>
    </div>
    {% endif %}

    <!-- Info técnica -->
    <div class="card border-0 shadow-sm">
      <div class="card-header border-0" style="background:linear-gradient(135deg,#f8fafc,#f1f5f9)">
        <i class="bi bi-terminal me-2 text-muted"></i>
        <span class="fw-semibold text-muted">Datos técnicos</span>
      </div>
      <div class="card-body" style="font-size:.8rem">
        <div class="mb-2">
          <div class="text-muted">NIF emisor</div>
          <div class="font-monospace fw-semibold">{{ nif or '—' }}</div>
        </div>
        <div class="mb-2">
          <div class="text-muted">Tipo factura</div>
          <div class="fw-semibold">F1 — Factura completa</div>
        </div>
        <div class="mb-2">
          <div class="text-muted">Sistema</div>
          <div class="fw-semibold">{{ cfg.id_sistema or '—' }} v{{ cfg.version_sistema or '—' }}</div>
        </div>
        <div class="mb-2">
          <div class="text-muted">Entorno</div>
          <div>
            {% if cfg.entorno == 'produccion' %}
            <span class="badge bg-success">Producción</span>
            {% else %}
            <span class="badge bg-warning text-dark">Pruebas</span>
            {% endif %}
          </div>
        </div>
        {% if fac.vf_fecha_hora %}
        <div>
          <div class="text-muted">Firmada el</div>
          <div class="fw-semibold">{{ fac.vf_fecha_hora }}</div>
        </div>
        {% endif %}
      </div>
    </div>

  </div>
</div>

{% endblock %}
