{% extends "base.html" %}
{% block title %}{% if rec %}Editar plantilla{% else %}Nueva plantilla recurrente{% endif %}{% endblock %}
{% block page_title %}{% if rec %}Editar «{{ rec.nombre }}»{% else %}Nueva plantilla recurrente{% endif %}{% endblock %}

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

{% block extra_head %}
<style>
  .lineas-table td { padding: 5px 4px; }
  .lineas-table input { padding: 4px 8px; font-size: .875rem; }
</style>
{% endblock %}

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

  <!-- Datos de la plantilla -->
  <div class="col-12">
    <div class="card">
      <div class="card-header"><i class="bi bi-arrow-repeat me-2"></i>Datos de la plantilla</div>
      <div class="card-body">
        <div class="row g-3">
          <div class="col-md-6">
            <label class="form-label fw-semibold">Nombre de la plantilla *</label>
            <input type="text" name="nombre" class="form-control"
                   value="{{ rec.nombre if rec else '' }}"
                   placeholder="Ej: Alquiler oficina mensual" required autofocus>
          </div>
          <div class="col-md-6">
            <label class="form-label fw-semibold">Cliente</label>
            <select name="cliente_id" class="form-select">
              <option value="">— Sin cliente —</option>
              {% for c in clientes %}
              <option value="{{ c.id }}"
                {% if rec and rec.cliente_id == c.id %}selected{% endif %}>
                {{ c.nombre }}
              </option>
              {% endfor %}
            </select>
          </div>
          <div class="col-md-3">
            <label class="form-label fw-semibold">Frecuencia</label>
            <select name="frecuencia" class="form-select" id="frecuencia">
              {% for val, lbl in freq_label.items() %}
              <option value="{{ val }}"
                {% if rec and rec.frecuencia == val %}selected
                {% elif not rec and val == 'mensual' %}selected
                {% endif %}>{{ lbl }}</option>
              {% endfor %}
            </select>
          </div>
          <div class="col-md-3">
            <label class="form-label fw-semibold">Primera / próxima generación</label>
            <input type="date" name="proxima_fecha" class="form-control"
                   value="{{ rec.proxima_fecha if rec else hoy }}" required>
          </div>
          <div class="col-md-2">
            <label class="form-label fw-semibold">IVA (%)</label>
            <select name="iva_pct" class="form-select" id="iva_pct" onchange="recalc()">
              {% for pct in [0, 4, 10, 21] %}
              <option value="{{ pct }}"
                {% if rec and rec.iva_pct == pct %}selected
                {% elif not rec and pct == 21 %}selected
                {% endif %}>{{ pct }}%</option>
              {% endfor %}
            </select>
          </div>
          <div class="col-md-2">
            <label class="form-label fw-semibold">IRPF (%)</label>
            <select name="irpf_pct" class="form-select" id="irpf_pct" onchange="recalc()">
              {% for pct in [0, 7, 15, 19] %}
              <option value="{{ pct }}"
                {% if rec and rec.irpf_pct == pct %}selected
                {% elif not rec and pct == 0 %}selected
                {% endif %}>{{ pct }}%</option>
              {% endfor %}
            </select>
          </div>
          <div class="col-md-2 d-flex align-items-end">
            {% if rec %}
            <div class="form-check mb-2">
              <input type="checkbox" name="activa" id="activa" class="form-check-input"
                     {% if rec.activa %}checked{% endif %}>
              <label class="form-check-label fw-semibold" for="activa">Plantilla activa</label>
            </div>
            {% endif %}
          </div>
          <div class="col-12">
            <label class="form-label fw-semibold">Notas</label>
            <textarea name="notas" class="form-control" rows="2"
                      placeholder="Condiciones, referencia del contrato...">{{ rec.notas if rec and rec.notas else '' }}</textarea>
          </div>
        </div>
      </div>
    </div>
  </div>

  <!-- Líneas -->
  <div class="col-12">
    <div class="card">
      <div class="card-header d-flex justify-content-between align-items-center">
        <span><i class="bi bi-list-ul me-2"></i>Líneas de la factura</span>
        <button type="button" class="btn btn-sm btn-outline-primary" onclick="addLinea()">
          <i class="bi bi-plus-lg"></i> Añadir línea
        </button>
      </div>
      <div class="card-body p-0">
        <div class="table-responsive">
          <table class="table lineas-table mb-0" id="tbl-lineas">
            <thead class="table-light">
              <tr>
                <th style="min-width:260px">Descripción</th>
                <th style="width:80px">Cant.</th>
                <th style="width:130px">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 %}
                {% for l in lineas %}
                <tr class="linea-row">
                  <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-del"><i class="bi bi-x"></i></button></td>
                </tr>
                {% endfor %}
              {% else %}
                <tr class="linea-row">
                  <td><input type="text"   name="descripcion[]"     class="form-control form-control-sm" placeholder="Descripción"></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-del"><i class="bi bi-x"></i></button></td>
                </tr>
              {% endif %}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  </div>

  <!-- Totales + Guardar -->
  <div class="col-12 d-flex justify-content-end">
    <div class="card" style="min-width:280px">
      <div class="card-body">
        <div class="text-muted small fw-semibold mb-2">ESTIMACIÓN POR GENERACIÓN</div>
        <div class="d-flex justify-content-between mb-1">
          <span class="text-muted">Base</span>
          <span id="res-base">0.00 €</span>
        </div>
        <div class="d-flex justify-content-between mb-1">
          <span class="text-muted">IVA</span>
          <span id="res-iva">0.00 €</span>
        </div>
        <div class="d-flex justify-content-between mb-1" id="row-irpf" style="display:none!important">
          <span class="text-muted text-danger">IRPF (−)</span>
          <span id="res-irpf" class="text-danger">0.00 €</span>
        </div>
        <hr class="my-2">
        <div class="d-flex justify-content-between fw-bold fs-5">
          <span>Total</span>
          <span id="res-total">0.00 €</span>
        </div>
        <div class="d-grid mt-3 gap-2">
          <button type="submit" class="btn btn-primary">
            <i class="bi bi-check-lg me-1"></i>
            {% if rec %}Guardar cambios{% else %}Crear plantilla{% endif %}
          </button>
          <a href="{{ url_for('recurrentes.lista') }}" class="btn btn-outline-secondary">Cancelar</a>
        </div>
      </div>
    </div>
  </div>

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

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

function recalc() {
  var base = 0;
  document.querySelectorAll('#lineas-body .linea-row').forEach(function(tr) {
    var c  = parseFloat(tr.querySelector('[name="cantidad[]"]').value) || 0;
    var p  = parseFloat(tr.querySelector('[name="precio_unitario[]"]').value) || 0;
    var d  = parseFloat(tr.querySelector('[name="descuento_pct[]"]').value) || 0;
    var s  = c * p * (1 - d / 100);
    tr.querySelector('.linea-sub').textContent = fmtEur(s);
    base += s;
  });
  var iva    = parseFloat(document.getElementById('iva_pct').value) || 0;
  var irpf   = parseFloat(document.getElementById('irpf_pct').value) || 0;
  var ivaImp = base * iva / 100;
  var irpfImp= base * irpf / 100;
  document.getElementById('res-base').textContent  = fmtEur(base);
  document.getElementById('res-iva').textContent   = fmtEur(ivaImp);
  document.getElementById('res-irpf').textContent  = fmtEur(irpfImp);
  document.getElementById('res-total').textContent = fmtEur(base + ivaImp - irpfImp);
  document.getElementById('row-irpf').style.display = irpf > 0 ? 'flex' : 'none';
}

function addLinea() {
  var tr = document.createElement('tr');
  tr.className = 'linea-row';
  tr.innerHTML = '<td><input type="text"   name="descripcion[]"     class="form-control form-control-sm" placeholder="Descripción"></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-del"><i class="bi bi-x"></i></button></td>';
  document.getElementById('lineas-body').appendChild(tr);
  wireRow(tr);
  tr.querySelector('input[name="descripcion[]"]').focus();
}

function wireRow(tr) {
  tr.querySelectorAll('.linea-num').forEach(function(i) { i.addEventListener('input', recalc); });
  tr.querySelector('.btn-del').addEventListener('click', function() {
    var rows = document.querySelectorAll('#lineas-body .linea-row');
    if (rows.length > 1) { tr.remove(); recalc(); }
  });
}

document.querySelectorAll('#lineas-body .linea-row').forEach(wireRow);
recalc();

// ── Catálogo autocomplete ────────────────────────────────────
(function() {
  var _dd = null, _timer = null;
  function hide() { if (_dd) { _dd.remove(); _dd = null; } }
  function show(inp, prods) {
    hide();
    if (!prods.length) return;
    var dd = document.createElement('div');
    dd.style.cssText = 'position:fixed;z-index:9999;background:#fff;border:1px solid #dee2e6;border-radius:8px;box-shadow:0 4px 12px rgba(0,0,0,.1);max-height:200px;overflow-y:auto;';
    prods.forEach(function(p) {
      var item = document.createElement('div');
      item.style.cssText = 'padding:8px 12px;cursor:pointer;font-size:.85rem;border-bottom:1px solid #f3f5fa;';
      item.innerHTML = '<strong>' + p.nombre + '</strong><span style="color:#6c757d;margin-left:8px">' + p.precio.toFixed(2) + ' € &middot; IVA ' + p.iva_pct + '%</span>';
      item.addEventListener('mouseover', function() { this.style.background = '#f0f5ff'; });
      item.addEventListener('mouseout',  function() { this.style.background = ''; });
      item.addEventListener('mousedown', function(e) {
        e.preventDefault();
        var tr = inp.closest('tr');
        inp.value = p.nombre;
        var prEl = tr.querySelector('[name="precio_unitario[]"]');
        if (prEl) { prEl.value = p.precio.toFixed(2); }
        hide();
        recalc();
      });
      dd.appendChild(item);
    });
    var rect = inp.getBoundingClientRect();
    dd.style.left = rect.left + 'px';
    dd.style.top  = (rect.bottom + 2) + 'px';
    dd.style.width = Math.max(rect.width, 260) + 'px';
    document.body.appendChild(dd);
    _dd = dd;
  }
  document.addEventListener('input', function(e) {
    if (!e.target || e.target.name !== 'descripcion[]') return;
    clearTimeout(_timer);
    var q = e.target.value.trim();
    if (q.length < 1) { hide(); return; }
    var inp = e.target;
    _timer = setTimeout(function() {
      fetch('/catalogo/api/buscar?q=' + encodeURIComponent(q))
        .then(function(r) { return r.json(); })
        .then(function(data) { show(inp, data); })
        .catch(function() {});
    }, 220);
  });
  document.addEventListener('click', function(e) { if (_dd && !_dd.contains(e.target)) hide(); });
  document.addEventListener('keydown', function(e) { if (e.key === 'Escape') hide(); });
})();
</script>
{% endblock %}
