{% extends "base.html" %}
{% block title %}Nueva factura rectificativa{% endblock %}
{% block page_title %}Nueva factura rectificativa{% endblock %}

{% block topbar_actions %}
<a href="{{ url_for('rectificativas.lista') }}" class="btn btn-outline-secondary btn-sm">
  <i class="bi bi-arrow-left me-1"></i>Volver
</a>
{% endblock %}

{% block extra_head %}
<style>
  .linea-rect td { vertical-align: middle; }
  #tabla-lineas tfoot td { border: none; }
</style>
{% endblock %}

{% block content %}
<form method="post" id="form-rect">
<div class="row g-4">

  <div class="col-12">
    <div class="card">
      <div class="card-header"><i class="bi bi-file-earmark-minus me-2 text-danger"></i>Datos de la rectificativa</div>
      <div class="card-body">
        <div class="row g-3">
          <div class="col-md-3">
            <label class="form-label">Número *</label>
            <input type="text" name="numero" class="form-control" value="{{ numero_sug }}" required>
          </div>
          <div class="col-md-3">
            <label class="form-label">Fecha *</label>
            <input type="date" name="fecha" class="form-control" value="{{ fecha_hoy }}" required>
          </div>
          <div class="col-md-3">
            <label class="form-label">Factura que rectifica</label>
            <select name="factura_origen_id" class="form-select" id="sel-origen">
              <option value="">— Sin referencia —</option>
              {% for fe in emitidas %}
              <option value="{{ fe.id }}"
                data-cliente="{{ fe.cliente_id or '' }}"
                {% if origen and fe.id == origen.id %}selected{% endif %}>
                {{ fe.numero }} ({{ fe.fecha }})
              </option>
              {% endfor %}
            </select>
          </div>
          <div class="col-md-3">
            <label class="form-label">Cliente</label>
            <select name="cliente_id" class="form-select" id="sel-cliente">
              <option value="">— Sin cliente —</option>
              {% for c in clientes %}
              <option value="{{ c.id }}"
                {% if origen and origen.cliente_id == c.id %}selected{% endif %}>
                {{ c.nombre }}
              </option>
              {% endfor %}
            </select>
          </div>
          <div class="col-12">
            <label class="form-label">Motivo de la rectificativa *</label>
            <input type="text" name="motivo" class="form-control"
                   placeholder="Ej: Error en precio, devolución parcial, descuento posterior..."
                   required>
          </div>
          <div class="col-md-2">
            <label class="form-label">IVA (%)</label>
            <input type="number" name="iva_pct" class="form-control" id="iva_pct"
                   value="{{ origen.iva_pct if origen else 21 }}" min="0" max="100" step="0.1">
          </div>
          <div class="col-md-2">
            <label class="form-label">IRPF (%)</label>
            <input type="number" name="irpf_pct" class="form-control" id="irpf_pct"
                   value="{{ origen.irpf_pct if origen else 0 }}" min="0" max="100" step="0.1">
          </div>
          <div class="col-md-8">
            <label class="form-label">Notas adicionales</label>
            <textarea name="notas" class="form-control" rows="2"
                      placeholder="Información adicional..."></textarea>
          </div>
        </div>
      </div>
    </div>
  </div>

  <div class="col-12">
    <div class="card">
      <div class="card-header"><i class="bi bi-list-ul me-2"></i>Líneas a rectificar</div>
      <div class="card-body p-0">
        <div class="table-responsive">
          <table class="table mb-0" id="tabla-lineas">
            <thead class="table-light">
              <tr>
                <th style="min-width:260px">Descripción</th>
                <th style="width:80px">Cant.</th>
                <th style="width:120px">Precio unit.</th>
                <th style="width:80px">Dto. (%)</th>
                <th style="width:110px" class="text-end">Subtotal</th>
                <th style="width:44px"></th>
              </tr>
            </thead>
            <tbody id="lineas-body">
              {% if lineas_origen %}
                {% for l in lineas_origen %}
                <tr class="linea-rect">
                  <td><input type="text"   name="descripcion[]"     class="form-control form-control-sm" value="{{ l.descripcion }}"></td>
                  <td><input type="number" name="cantidad[]"        class="form-control form-control-sm linea-num" value="{{ l.cantidad }}"        min="0" step="any"></td>
                  <td><input type="number" name="precio_unitario[]" class="form-control form-control-sm linea-num" value="{{ l.precio_unitario }}" min="0" step="any"></td>
                  <td><input type="number" name="descuento_pct[]"   class="form-control form-control-sm linea-num" value="{{ l.descuento_pct }}"  min="0" max="100" step="any"></td>
                  <td class="text-end fw-semibold linea-sub">{{ "%.2f"|format(l.subtotal) }} €</td>
                  <td><button type="button" class="btn btn-sm btn-outline-danger btn-borrar-linea"><i class="bi bi-trash"></i></button></td>
                </tr>
                {% endfor %}
              {% else %}
                <tr class="linea-rect">
                  <td><input type="text"   name="descripcion[]"     class="form-control form-control-sm" placeholder="Descripción del concepto a rectificar"></td>
                  <td><input type="number" name="cantidad[]"        class="form-control form-control-sm linea-num" value="1"  min="0" step="any"></td>
                  <td><input type="number" name="precio_unitario[]" class="form-control form-control-sm linea-num" value="0"  min="0" step="any"></td>
                  <td><input type="number" name="descuento_pct[]"   class="form-control form-control-sm linea-num" value="0"  min="0" max="100" step="any"></td>
                  <td class="text-end fw-semibold linea-sub">0.00 €</td>
                  <td><button type="button" class="btn btn-sm btn-outline-danger btn-borrar-linea"><i class="bi bi-trash"></i></button></td>
                </tr>
              {% endif %}
            </tbody>
            <tfoot>
              <tr>
                <td colspan="6" class="pt-2 pb-3 px-3">
                  <button type="button" id="btn-add-linea" class="btn btn-outline-primary btn-sm">
                    <i class="bi bi-plus-lg me-1"></i>Añadir línea
                  </button>
                </td>
              </tr>
            </tfoot>
          </table>
        </div>
      </div>
    </div>
  </div>

  <div class="col-12 d-flex justify-content-between align-items-start flex-wrap gap-3">
    <div></div>
    <div class="card border-danger" style="min-width:280px">
      <div class="card-body">
        <table class="table table-sm mb-0">
          <tr><td class="text-muted">Base imponible</td><td class="text-end" id="tot-base">0.00 €</td></tr>
          <tr><td class="text-muted">IVA</td><td class="text-end" id="tot-iva">0.00 €</td></tr>
          <tr id="row-irpf" style="display:none">
            <td class="text-muted text-danger">IRPF</td>
            <td class="text-end text-danger" id="tot-irpf">0.00 €</td>
          </tr>
          <tr class="fw-bold fs-5">
            <td class="text-danger">TOTAL</td>
            <td class="text-end text-danger" id="tot-total">0.00 €</td>
          </tr>
        </table>
        <div class="d-grid mt-3">
          <button type="submit" class="btn btn-danger">
            <i class="bi bi-check-lg me-1"></i>Crear rectificativa
          </button>
        </div>
      </div>
    </div>
  </div>

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

{% block extra_scripts %}
<script>
function fmtEur(v) { return parseFloat(v || 0).toFixed(2) + ' €'; }

function recalcLinea(tr) {
  var cant   = parseFloat(tr.querySelector('[name="cantidad[]"]').value)        || 0;
  var precio = parseFloat(tr.querySelector('[name="precio_unitario[]"]').value) || 0;
  var dto    = parseFloat(tr.querySelector('[name="descuento_pct[]"]').value)   || 0;
  var sub    = cant * precio * (1 - dto / 100);
  tr.querySelector('.linea-sub').textContent = fmtEur(sub);
  return sub;
}

function recalcTotales() {
  var subtotal = 0;
  document.querySelectorAll('#lineas-body tr.linea-rect').forEach(function(tr) {
    subtotal += recalcLinea(tr);
  });
  var ivaPct  = parseFloat(document.getElementById('iva_pct').value)  || 0;
  var irpfPct = parseFloat(document.getElementById('irpf_pct').value) || 0;
  var iva     = subtotal * ivaPct / 100;
  var irpf    = subtotal * irpfPct / 100;
  var total   = subtotal + iva - irpf;
  document.getElementById('tot-base').textContent  = fmtEur(subtotal);
  document.getElementById('tot-iva').textContent   = fmtEur(iva);
  document.getElementById('tot-irpf').textContent  = '-' + fmtEur(irpf);
  document.getElementById('tot-total').textContent = fmtEur(total);
  document.getElementById('row-irpf').style.display = irpfPct > 0 ? '' : 'none';
}

function nuevaLinea() {
  var tr = document.createElement('tr');
  tr.className = 'linea-rect';
  tr.innerHTML =
    '<td><input type="text"   name="descripcion[]"     class="form-control form-control-sm" placeholder="Descripcion"></td>' +
    '<td><input type="number" name="cantidad[]"        class="form-control form-control-sm linea-num" value="1"  min="0" step="any"></td>' +
    '<td><input type="number" name="precio_unitario[]" class="form-control form-control-sm linea-num" value="0"  min="0" step="any"></td>' +
    '<td><input type="number" name="descuento_pct[]"   class="form-control form-control-sm linea-num" value="0"  min="0" max="100" step="any"></td>' +
    '<td class="text-end fw-semibold linea-sub">0.00 €</td>' +
    '<td><button type="button" class="btn btn-sm btn-outline-danger btn-borrar-linea"><i class="bi bi-trash"></i></button></td>';
  document.getElementById('lineas-body').appendChild(tr);
  tr.querySelector('input[name="descripcion[]"]').focus();
  wireLinea(tr);
}

function wireLinea(tr) {
  tr.querySelectorAll('.linea-num').forEach(function(inp) {
    inp.addEventListener('input', recalcTotales);
  });
  tr.querySelector('.btn-borrar-linea').addEventListener('click', function() {
    var rows = document.querySelectorAll('#lineas-body tr.linea-rect');
    if (rows.length > 1) { tr.remove(); recalcTotales(); }
  });
}

document.querySelectorAll('#lineas-body tr.linea-rect').forEach(wireLinea);
document.getElementById('btn-add-linea').addEventListener('click', nuevaLinea);
document.getElementById('iva_pct').addEventListener('input', recalcTotales);
document.getElementById('irpf_pct').addEventListener('input', recalcTotales);
recalcTotales();
</script>
{% endblock %}
