{% extends "base.html" %}
{% block title %}Nuevo presupuesto{% endblock %}
{% block page_title %}Nuevo presupuesto{% endblock %}

{% block topbar_actions %}
<a href="{{ url_for('presupuestos.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-pres td { vertical-align: middle; }
  #tabla-lineas tfoot td { border: none; }
</style>
{% endblock %}

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

  <!-- Cabecera del presupuesto -->
  <div class="col-12">
    <div class="card">
      <div class="card-header"><i class="bi bi-file-earmark-text me-2"></i>Datos del presupuesto</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">Válido hasta</label>
            <input type="date" name="fecha_validez" class="form-control" value="{{ fecha_validez }}">
          </div>
          <div class="col-md-3">
            <label class="form-label">Cliente</label>
            <select name="cliente_id" class="form-select">
              <option value="">— Sin cliente —</option>
              {% for c in clientes %}
              <option value="{{ c.id }}">{{ c.nombre }}</option>
              {% endfor %}
            </select>
          </div>
          <div class="col-md-2">
            <label class="form-label">IVA (%)</label>
            <input type="number" name="iva_pct" class="form-control" value="21" min="0" max="100" step="0.1" id="iva_pct">
          </div>
          <div class="col-md-2">
            <label class="form-label">IRPF (%)</label>
            <input type="number" name="irpf_pct" class="form-control" value="0" min="0" max="100" step="0.1" id="irpf_pct">
          </div>
          <div class="col-md-8">
            <label class="form-label">Notas / Condiciones</label>
            <textarea name="notas" class="form-control" rows="2" placeholder="Condiciones de pago, observaciones..."></textarea>
          </div>
        </div>
      </div>
    </div>
  </div>

  <!-- Líneas -->
  <div class="col-12">
    <div class="card">
      <div class="card-header"><i class="bi bi-list-ul me-2"></i>Líneas del presupuesto</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">
              <tr class="linea-pres">
                <td><input type="text"   name="descripcion[]"     class="form-control form-control-sm" placeholder="Descripción del producto o servicio"></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>
            </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>

  <!-- Totales + acciones -->
  <div class="col-12 d-flex justify-content-between align-items-start flex-wrap gap-3">
    <div></div>
    <div class="card" 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="table-dark fw-bold fs-5">
            <td>TOTAL</td>
            <td class="text-end" id="tot-total">0.00 €</td>
          </tr>
        </table>
        <div class="d-grid mt-3">
          <button type="submit" class="btn btn-primary">
            <i class="bi bi-check-lg me-1"></i>Guardar presupuesto
          </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-pres').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 tmpl = document.querySelector('#lineas-body tr.linea-pres').cloneNode(true);
  tmpl.querySelectorAll('input').forEach(function(i) {
    i.value = i.name.includes('cantidad') || i.name.includes('precio') || i.name.includes('descuento') ? '0' : '';
    if (i.name.includes('cantidad')) i.value = '1';
  });
  tmpl.querySelector('.linea-sub').textContent = '0.00 €';
  document.getElementById('lineas-body').appendChild(tmpl);
  tmpl.querySelector('input[name="descripcion[]"]').focus();
  wireLinea(tmpl);
}

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-pres');
    if (rows.length > 1) { tr.remove(); recalcTotales(); }
    else { tr.querySelectorAll('input').forEach(function(i) { i.value = i.name.includes('cantidad') ? '1' : '0'; if(i.name.includes('descripcion')) i.value=''; }); recalcTotales(); }
  });
}

document.querySelectorAll('#lineas-body tr.linea-pres').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();

// ── 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();
        recalcTotales();
      });
      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 %}
