{% extends "base.html" %}
{% block title %}Abono {{ abono.numero }}{% endblock %}
{% block page_title %}Abono {{ abono.numero }}{% endblock %}

{% block content %}
{% with msgs = get_flashed_messages(with_categories=true) %}
  {% for cat, msg in msgs %}
  <div class="alert alert-{{ cat }} alert-dismissible fade show">{{ msg }}<button type="button" class="btn-close" data-bs-dismiss="alert"></button></div>
  {% endfor %}
{% endwith %}

<!-- Barra de acciones -->
<div class="d-flex flex-wrap gap-2 mb-4">
  <a href="{{ url_for('abonos_prov.editar', id=abono.id) }}" class="btn btn-outline-primary btn-sm">
    <i class="bi bi-pencil me-1"></i>Editar
  </a>
  <button class="btn btn-outline-danger btn-sm" data-bs-toggle="modal" data-bs-target="#modalEliminar">
    <i class="bi bi-trash me-1"></i>Eliminar
  </button>
  <a href="{{ url_for('abonos_prov.index') }}" class="btn btn-outline-secondary btn-sm ms-auto">
    <i class="bi bi-arrow-left me-1"></i>Volver al listado
  </a>
</div>

<div class="row g-4">

  <!-- Detalle izquierda -->
  <div class="col-lg-8">

    <!-- Cabecera del documento -->
    <div class="card border-0 shadow-sm mb-4">
      <div class="card-body p-4">
        <div class="row g-3">
          <div class="col-sm-6">
            <div class="text-muted small mb-1">Número</div>
            <div class="fw-bold fs-5">{{ abono.numero }}</div>
          </div>
          <div class="col-sm-6 text-sm-end">
            {% if abono.estado == 'pendiente' %}
            <span class="badge bg-warning text-dark fs-6">Pendiente</span>
            {% elif abono.estado == 'enviado' %}
            <span class="badge bg-info text-dark fs-6">Enviado</span>
            {% elif abono.estado == 'aceptado' %}
            <span class="badge bg-success fs-6">Aceptado</span>
            {% else %}
            <span class="badge bg-secondary fs-6">Cancelado</span>
            {% endif %}
          </div>
          <div class="col-sm-6">
            <div class="text-muted small mb-1">Proveedor</div>
            <div class="fw-semibold">{{ abono.prov_nombre or '—' }}</div>
            {% if abono.prov_nif %}<div class="text-muted small">NIF: {{ abono.prov_nif }}</div>{% endif %}
          </div>
          <div class="col-sm-6">
            <div class="text-muted small mb-1">Fecha</div>
            <div>{{ abono.fecha }}</div>
          </div>
          {% if abono.factura_ref %}
          <div class="col-sm-6">
            <div class="text-muted small mb-1">Referencia factura</div>
            <div>{{ abono.factura_ref }}</div>
          </div>
          {% endif %}
          {% if abono.concepto %}
          <div class="col-12">
            <div class="text-muted small mb-1">Concepto</div>
            <div>{{ abono.concepto }}</div>
          </div>
          {% endif %}
        </div>
      </div>
    </div>

    <!-- Líneas -->
    <div class="card border-0 shadow-sm mb-4">
      <div class="card-header fw-semibold small"><i class="bi bi-list-ul me-2"></i>Detalle de líneas</div>
      <div class="table-responsive">
        <table class="table table-sm mb-0">
          <thead class="table-light">
            <tr>
              <th>Descripción</th>
              <th class="text-end">Cantidad</th>
              <th class="text-end">Precio unit.</th>
              <th class="text-end">Subtotal</th>
            </tr>
          </thead>
          <tbody>
            {% for l in lineas %}
            <tr>
              <td>{{ l.descripcion }}</td>
              <td class="text-end">{{ '%.2f'|format(l.cantidad or 1) }}</td>
              <td class="text-end">{{ '%.2f'|format(l.precio_unitario or 0) }} €</td>
              <td class="text-end">{{ '%.2f'|format(l.subtotal or 0) }} €</td>
            </tr>
            {% endfor %}
          </tbody>
          <tfoot class="table-light">
            <tr>
              <td colspan="3" class="text-end text-muted small">Base imponible</td>
              <td class="text-end fw-semibold">{{ '%.2f'|format(abono.importe_base or 0) }} €</td>
            </tr>
            <tr>
              <td colspan="3" class="text-end text-muted small">IVA ({{ abono.iva_pct|int }}%)</td>
              <td class="text-end fw-semibold">{{ '%.2f'|format(abono.iva_importe or 0) }} €</td>
            </tr>
            <tr>
              <td colspan="3" class="text-end fw-bold">Total</td>
              <td class="text-end fw-bold fs-5">{{ '%.2f'|format(abono.total or 0) }} €</td>
            </tr>
          </tfoot>
        </table>
      </div>
    </div>

    {% if abono.notas %}
    <div class="card border-0 shadow-sm mb-4">
      <div class="card-header fw-semibold small"><i class="bi bi-sticky me-2"></i>Notas internas</div>
      <div class="card-body text-muted small" style="white-space:pre-line">{{ abono.notas }}</div>
    </div>
    {% endif %}

  </div>

  <!-- Columna derecha -->
  <div class="col-lg-4">

    <!-- Cambiar estado -->
    <div class="card border-0 shadow-sm mb-4">
      <div class="card-header fw-semibold small"><i class="bi bi-arrow-repeat me-2"></i>Cambiar estado</div>
      <div class="card-body">
        <form method="post" action="{{ url_for('abonos_prov.cambiar_estado', id=abono.id) }}"
              id="frmEstado">
          <select name="estado" class="form-select form-select-sm mb-2" onchange="this.form.submit()">
            {% for est in estados %}
            <option value="{{ est }}" {% if abono.estado == est %}selected{% endif %}>
              {{ est | capitalize }}
            </option>
            {% endfor %}
          </select>
        </form>
        {% if abono.email_enviado %}
        <div class="small text-muted">
          <i class="bi bi-envelope-check me-1 text-success"></i>
          Enviado el {{ abono.fecha_envio or '' }}
        </div>
        {% endif %}
      </div>
    </div>

    <!-- Enviar por email -->
    <div class="card border-0 shadow-sm">
      <div class="card-header fw-semibold small"><i class="bi bi-envelope me-2"></i>Enviar por correo</div>
      <div class="card-body">
        {% if not smtp_ok %}
        <div class="alert alert-warning small mb-0">
          <i class="bi bi-exclamation-triangle me-2"></i>
          No hay servidor de correo configurado.<br>
          Ve a <a href="{{ url_for('configuracion.index') }}" class="alert-link">Configuración → SMTP</a> para configurarlo.
        </div>
        {% else %}
        <form method="post" action="{{ url_for('abonos_prov.enviar_email', id=abono.id) }}">

          <!-- Selector de plantilla -->
          {% if plantillas %}
          <div class="mb-3">
            <label class="form-label small fw-semibold">Usar plantilla</label>
            <select class="form-select form-select-sm" id="selPlantilla">
              <option value="">— Sin plantilla —</option>
              {% for pt in plantillas %}
              <option value="{{ pt.id }}">
                {{ pt.nombre }}{% if pt.prov_nombre %} ({{ pt.prov_nombre }}){% endif %}
              </option>
              {% endfor %}
            </select>
          </div>
          {% endif %}

          <div class="mb-3">
            <label class="form-label small fw-semibold">Destinatario <span class="text-danger">*</span></label>
            <input type="email" name="destinatario" class="form-control form-control-sm" id="inpDest"
                   value="{{ abono.prov_email or '' }}" required>
          </div>

          <div class="mb-3">
            <label class="form-label small fw-semibold">Asunto</label>
            <input type="text" name="asunto" class="form-control form-control-sm" id="inpAsunto"
                   value="Nota de abono {{ abono.numero }}">
          </div>

          <div class="mb-3">
            <label class="form-label small fw-semibold">Mensaje</label>
            <textarea name="cuerpo" class="form-control form-control-sm" id="inpCuerpo"
                      rows="7"></textarea>
          </div>

          <button type="submit" class="btn btn-primary btn-sm w-100">
            <i class="bi bi-send me-1"></i>Enviar email
          </button>
        </form>
        {% endif %}
      </div>
    </div>

  </div>
</div>

<!-- Modal eliminar -->
<div class="modal fade" id="modalEliminar" tabindex="-1">
  <div class="modal-dialog modal-sm">
    <div class="modal-content">
      <div class="modal-header">
        <h6 class="modal-title">Eliminar abono</h6>
        <button class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body small">
        ¿Eliminar el abono <strong>{{ abono.numero }}</strong>? Esta acción no se puede deshacer.
      </div>
      <div class="modal-footer">
        <button class="btn btn-sm btn-secondary" data-bs-dismiss="modal">Cancelar</button>
        <form method="post" action="{{ url_for('abonos_prov.eliminar', id=abono.id) }}">
          <button class="btn btn-sm btn-danger">Eliminar</button>
        </form>
      </div>
    </div>
  </div>
</div>
{% endblock %}

{% block extra_scripts %}
{% if smtp_ok and plantillas %}
<script>
document.getElementById('selPlantilla')?.addEventListener('change', function() {
  const pid = this.value;
  if (!pid) return;
  fetch('/abonos-proveedor/plantillas/' + pid + '/contenido')
    .then(r => r.json())
    .then(d => {
      const asunto = d.asunto || '';
      const cuerpo = d.cuerpo || '';
      // Reemplazar marcadores básicos
      const num    = {{ abono.numero | tojson }};
      const fecha  = {{ abono.fecha | tojson }};
      const total  = {{ ('%.2f' | format(abono.total or 0) + ' €') | tojson }};
      const conc   = {{ (abono.concepto or '') | tojson }};
      const ref    = {{ (abono.factura_ref or '') | tojson }};
      const emp    = {{ ((empresa.nombre if empresa else '') | tojson) }};
      function repl(s) {
        return s.replace(/\{numero\}/g, num)
                .replace(/\{fecha\}/g, fecha)
                .replace(/\{total\}/g, total)
                .replace(/\{concepto\}/g, conc)
                .replace(/\{factura_ref\}/g, ref)
                .replace(/\{empresa\}/g, emp);
      }
      document.getElementById('inpAsunto').value = repl(asunto);
      document.getElementById('inpCuerpo').value = repl(cuerpo);
    });
});
</script>
{% endif %}
{% endblock %}
