{% extends "base.html" %}
{% block title %}{% if abono %}Editar abono{{ abono.numero }}{% else %}Nuevo abono{% endif %}{% endblock %}
{% block page_title %}{% if abono %}Editar abono — {{ abono.numero }}{% else %}Nuevo abono a proveedor{% endif %}{% 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 %}

<form method="post" id="frmAbono">
<div class="row g-4">

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

    <!-- Datos principales -->
    <div class="card border-0 shadow-sm mb-4">
      <div class="card-header fw-semibold small"><i class="bi bi-info-circle me-2"></i>Datos del abono</div>
      <div class="card-body">
        <div class="row g-3">

          <div class="col-md-4">
            <label class="form-label small fw-semibold">Número</label>
            <div class="form-control bg-light text-muted" style="min-height:38px">
              {% if abono %}{{ abono.numero }}{% else %}{{ numero_prev }}{% endif %}
            </div>
          </div>

          <div class="col-md-4">
            <label class="form-label small fw-semibold">Fecha <span class="text-danger">*</span></label>
            <input type="date" name="fecha" class="form-control"
                   value="{{ abono.fecha if abono else hoy }}" required>
          </div>

          <div class="col-md-4">
            <label class="form-label small fw-semibold">Proveedor</label>
            <select name="proveedor_id" class="form-select">
              <option value="">— Sin proveedor —</option>
              {% for pv in proveedores %}
              <option value="{{ pv.id }}"
                {% if abono and abono.proveedor_id == pv.id %}selected{% endif %}>
                {{ pv.nombre }}
              </option>
              {% endfor %}
            </select>
          </div>

          <div class="col-md-6">
            <label class="form-label small fw-semibold">Referencia factura del proveedor</label>
            <input type="text" name="factura_ref" class="form-control"
                   value="{{ abono.factura_ref if abono else '' }}"
                   placeholder="Ej: FACT-2024-0123">
          </div>

          <div class="col-md-6">
            <label class="form-label small fw-semibold">IVA (%)</label>
            <select name="iva_pct" class="form-select" id="selIva">
              {% for pct in [0, 4, 10, 21] %}
              <option value="{{ pct }}"
                {% if abono and (abono.iva_pct|int) == pct %}selected
                {% elif not abono and pct == 21 %}selected{% endif %}>
                {{ pct }}%
              </option>
              {% endfor %}
            </select>
          </div>

          <div class="col-12">
            <label class="form-label small fw-semibold">Concepto general (opcional)</label>
            <input type="text" name="concepto" class="form-control"
                   value="{{ abono.concepto if abono else '' }}"
                   placeholder="Motivo resumido del abono">
          </div>

        </div>
      </div>
    </div>

    <!-- Líneas de detalle -->
    <div class="card border-0 shadow-sm mb-4">
      <div class="card-header d-flex justify-content-between align-items-center fw-semibold small">
        <span><i class="bi bi-list-ul me-2"></i>Líneas de detalle</span>
        <button type="button" class="btn btn-sm btn-outline-primary" id="btnAddLinea">
          <i class="bi bi-plus-lg me-1"></i>Añadir línea
        </button>
      </div>
      <div class="card-body p-0">
        <div class="table-responsive">
          <table class="table table-sm mb-0" id="tablaLineas">
            <thead class="table-light">
              <tr>
                <th>Descripción</th>
                <th style="width:90px">Cantidad</th>
                <th style="width:120px">Precio unit.</th>
                <th style="width:110px" class="text-end">Subtotal</th>
                <th style="width:40px"></th>
              </tr>
            </thead>
            <tbody id="cuerpoLineas">
              {% set lineas_list = lineas if lineas else [] %}
              {% if lineas_list %}
                {% for l in lineas_list %}
                <tr class="fila-linea">
                  <td><input type="text" name="descripcion[]" class="form-control form-control-sm" value="{{ l.descripcion }}" required></td>
                  <td><input type="number" name="cantidad[]" class="form-control form-control-sm inp-cant" step="0.01" min="0" value="{{ l.cantidad }}" required></td>
                  <td><input type="number" name="precio_unitario[]" class="form-control form-control-sm inp-precio" step="0.01" min="0" value="{{ l.precio_unitario }}" required></td>
                  <td class="text-end align-middle"><span class="span-sub">{{ '%.2f'|format(l.subtotal or 0) }}</span> €</td>
                  <td><button type="button" class="btn btn-sm btn-outline-danger btn-del-fila"><i class="bi bi-x"></i></button></td>
                </tr>
                {% endfor %}
              {% else %}
              <tr class="fila-linea">
                <td><input type="text" name="descripcion[]" class="form-control form-control-sm" required></td>
                <td><input type="number" name="cantidad[]" class="form-control form-control-sm inp-cant" step="0.01" min="0" value="1" required></td>
                <td><input type="number" name="precio_unitario[]" class="form-control form-control-sm inp-precio" step="0.01" min="0" value="0" required></td>
                <td class="text-end align-middle"><span class="span-sub">0.00</span> €</td>
                <td><button type="button" class="btn btn-sm btn-outline-danger btn-del-fila"><i class="bi bi-x"></i></button></td>
              </tr>
              {% endif %}
            </tbody>
          </table>
        </div>
      </div>
    </div>

    <!-- Notas -->
    <div class="card border-0 shadow-sm">
      <div class="card-header fw-semibold small"><i class="bi bi-sticky me-2"></i>Notas internas</div>
      <div class="card-body">
        <textarea name="notas" class="form-control" rows="3"
                  placeholder="Notas internas (no se envían al proveedor)">{{ abono.notas if abono else '' }}</textarea>
      </div>
    </div>

  </div>

  <!-- Columna derecha — resumen -->
  <div class="col-lg-4">
    <div class="card border-0 shadow-sm sticky-top" style="top:80px">
      <div class="card-header fw-semibold small"><i class="bi bi-calculator me-2"></i>Resumen</div>
      <div class="card-body">
        <div class="d-flex justify-content-between mb-2">
          <span class="text-muted">Base imponible</span>
          <span id="resBase" class="fw-semibold">0.00 €</span>
        </div>
        <div class="d-flex justify-content-between mb-2">
          <span class="text-muted">IVA (<span id="resIvaPct">21</span>%)</span>
          <span id="resIva" class="fw-semibold">0.00 €</span>
        </div>
        <hr>
        <div class="d-flex justify-content-between">
          <span class="fw-bold">Total</span>
          <span id="resTotal" class="fw-bold fs-5">0.00 €</span>
        </div>
      </div>
      <div class="card-footer bg-transparent d-flex gap-2">
        <button type="submit" class="btn btn-primary flex-grow-1">
          <i class="bi bi-save me-1"></i>{% if abono %}Guardar cambios{% else %}Crear abono{% endif %}
        </button>
        <a href="{{ url_for('abonos_prov.index') }}" class="btn btn-outline-secondary">Cancelar</a>
      </div>
    </div>
  </div>

</div>
</form>
{% endblock %}

{% block extra_scripts %}
<script>
const TEMPLATE_ROW = `
<tr class="fila-linea">
  <td><input type="text" name="descripcion[]" class="form-control form-control-sm" required></td>
  <td><input type="number" name="cantidad[]" class="form-control form-control-sm inp-cant" step="0.01" min="0" value="1" required></td>
  <td><input type="number" name="precio_unitario[]" class="form-control form-control-sm inp-precio" step="0.01" min="0" value="0" required></td>
  <td class="text-end align-middle"><span class="span-sub">0.00</span> €</td>
  <td><button type="button" class="btn btn-sm btn-outline-danger btn-del-fila"><i class="bi bi-x"></i></button></td>
</tr>`;

function recalc() {
  let base = 0;
  document.querySelectorAll('.fila-linea').forEach(tr => {
    const c = parseFloat(tr.querySelector('.inp-cant').value) || 0;
    const p = parseFloat(tr.querySelector('.inp-precio').value) || 0;
    const sub = Math.round(c * p * 100) / 100;
    tr.querySelector('.span-sub').textContent = sub.toFixed(2);
    base += sub;
  });
  const ivaPct = parseFloat(document.getElementById('selIva').value) || 0;
  const iva    = Math.round(base * ivaPct) / 100;
  const total  = Math.round((base + iva) * 100) / 100;
  document.getElementById('resBase').textContent  = base.toFixed(2) + ' €';
  document.getElementById('resIvaPct').textContent = ivaPct;
  document.getElementById('resIva').textContent   = iva.toFixed(2) + ' €';
  document.getElementById('resTotal').textContent = total.toFixed(2) + ' €';
}

document.getElementById('btnAddLinea').addEventListener('click', () => {
  document.getElementById('cuerpoLineas').insertAdjacentHTML('beforeend', TEMPLATE_ROW);
  recalc();
});

document.getElementById('cuerpoLineas').addEventListener('click', e => {
  const btn = e.target.closest('.btn-del-fila');
  if (btn) {
    const filas = document.querySelectorAll('.fila-linea');
    if (filas.length > 1) { btn.closest('tr').remove(); recalc(); }
  }
});

document.getElementById('cuerpoLineas').addEventListener('input', recalc);
document.getElementById('selIva').addEventListener('change', recalc);
recalc();
</script>
{% endblock %}
