{% extends "base.html" %}
{% block title %}Registrar factura recibida{% endblock %}
{% block page_title %}Registrar factura recibida{% endblock %}

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

{% block content %}
<form method="post" id="formFactura" enctype="multipart/form-data">
<div class="row g-3">
  <div class="col-lg-8">
    <div class="card">
      <div class="card-header py-3"><i class="bi bi-file-earmark-arrow-down me-2"></i>Datos de la factura</div>
      <div class="card-body p-4">
        <div class="row g-3">
          <div class="col-md-4">
            <label class="form-label">Número de factura *</label>
            <input type="text" name="numero" class="form-control" required>
          </div>
          <div class="col-md-4">
            <label class="form-label">Fecha *</label>
            <input type="date" name="fecha" class="form-control" value="{{ hoy }}" required>
          </div>
          <div class="col-md-4">
            <label class="form-label">Fecha de vencimiento</label>
            <input type="date" name="fecha_vencimiento" class="form-control" value="{{ venc }}">
          </div>
          <div class="col-md-6">
            <label class="form-label">Proveedor</label>
            <select name="proveedor_id" class="form-select">
              <option value="">— Sin proveedor —</option>
              {% for p in proveedores %}
              <option value="{{ p.id }}">{{ p.nombre }}</option>
              {% endfor %}
            </select>
          </div>
          <div class="col-md-6">
            <label class="form-label">Categoría de gasto</label>
            <select name="categoria_id" class="form-select">
              <option value="">— Sin categoría —</option>
              {% for c in categorias %}
              <option value="{{ c.id }}">{{ c.nombre }}</option>
              {% endfor %}
            </select>
          </div>
        </div>
      </div>
    </div>

    <div class="card mt-3">
      <div class="card-header py-3 d-flex justify-content-between align-items-center">
        <span><i class="bi bi-list-ul me-2"></i>Líneas de 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">
            <thead><tr>
              <th style="width:40%">Descripción</th><th style="width:12%">Cant.</th>
              <th style="width:17%">Precio unit.</th><th style="width:12%">Dto. %</th>
              <th style="width:14%" class="text-end">Subtotal</th><th style="width:5%"></th>
            </tr></thead>
            <tbody id="lineasBody">
              <tr class="linea-row">
                <td><input type="text" name="descripcion[]" class="form-control" placeholder="Descripción"></td>
                <td><input type="number" name="cantidad[]" class="form-control linea-num" value="1" min="0" step="any"></td>
                <td><input type="number" name="precio_unitario[]" class="form-control linea-num" value="0" min="0" step="any"></td>
                <td><input type="number" name="descuento_pct[]" class="form-control linea-num" value="0" min="0" max="100" step="any"></td>
                <td class="text-end fw-semibold subtotal-cell align-middle">0.00 €</td>
                <td><button type="button" class="btn btn-sm btn-outline-danger" onclick="removeLinea(this)"><i class="bi bi-x"></i></button></td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>
    </div>
  </div>

  <div class="col-lg-4">
    <div class="card">
      <div class="card-header py-3"><i class="bi bi-calculator me-2"></i>Totales</div>
      <div class="card-body">
        <div class="mb-3">
          <label class="form-label">IVA %</label>
          <select name="iva_pct" class="form-select" id="ivaPct" onchange="recalcTotales()">
            <option value="0">0% (Exento)</option>
            <option value="4">4%</option>
            <option value="10">10%</option>
            <option value="21" selected>21%</option>
          </select>
        </div>
        <div class="mb-3">
          <label class="form-label">IRPF %</label>
          <select name="irpf_pct" class="form-select" id="irpfPct" onchange="recalcTotales()">
            <option value="0" selected>0%</option>
            <option value="7">7%</option>
            <option value="15">15%</option>
            <option value="19">19%</option>
          </select>
        </div>
        <hr>
        <div class="d-flex justify-content-between mb-1">
          <span class="text-muted small">Base imponible</span><span id="resBase" class="fw-semibold">0.00 €</span>
        </div>
        <div class="d-flex justify-content-between mb-1">
          <span class="text-muted small">IVA</span><span id="resIva" class="fw-semibold">0.00 €</span>
        </div>
        <div class="d-flex justify-content-between mb-1">
          <span class="text-muted small">IRPF (−)</span><span id="resIrpf" class="fw-semibold text-danger">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>
    <div class="card mt-3">
      <div class="card-body">
        <label class="form-label">Notas</label>
        <textarea name="notas" class="form-control" rows="3"></textarea>
        <div class="mt-3">
          <label class="form-label">Etiquetas</label>
          <input type="text" name="etiquetas" class="form-control" placeholder="Ej: deducible, proveedor habitual, trimestre 1">
          <div class="form-text">Separa varias etiquetas con comas.</div>
        </div>
      </div>
    </div>

    <div class="card mt-3">
      <div class="card-body">
        <label class="form-label"><i class="bi bi-paperclip me-1"></i>Adjuntar factura</label>
        <input type="file" name="archivo_factura" class="form-control" accept=".pdf,.png,.jpg,.jpeg">
        <div class="form-text">Opcional — PDF o imagen de la factura.</div>
      </div>
    </div>

    <div class="d-grid gap-2 mt-3">
      <button type="submit" class="btn btn-primary"><i class="bi bi-check-lg me-1"></i>Registrar factura</button>
      <a href="{{ url_for('facturas.recibidas') }}" class="btn btn-outline-secondary">Cancelar</a>
    </div>
  </div>
</div>
</form>
{% endblock %}

{% block extra_scripts %}
<script>
function addLinea() {
  const tbody = document.getElementById('lineasBody');
  const fila = tbody.querySelector('.linea-row').cloneNode(true);
  fila.querySelectorAll('input').forEach(i => { if (i.name !== 'descuento_pct[]') i.value = i.name === 'cantidad[]' ? 1 : 0; });
  fila.querySelector('.subtotal-cell').textContent = '0.00 €';
  tbody.appendChild(fila);
  fila.querySelectorAll('.linea-num').forEach(i => i.addEventListener('input', recalcTotales));
}
function removeLinea(btn) {
  if (document.querySelectorAll('.linea-row').length > 1) { btn.closest('tr').remove(); recalcTotales(); }
}
function recalcTotales() {
  let base = 0;
  document.querySelectorAll('.linea-row').forEach(row => {
    const cant = parseFloat(row.querySelector('[name="cantidad[]"]').value) || 0;
    const precio = parseFloat(row.querySelector('[name="precio_unitario[]"]').value) || 0;
    const dto = parseFloat(row.querySelector('[name="descuento_pct[]"]').value) || 0;
    const sub = cant * precio * (1 - dto / 100);
    row.querySelector('.subtotal-cell').textContent = sub.toFixed(2) + ' €';
    base += sub;
  });
  const iva = base * (parseFloat(document.getElementById('ivaPct').value) || 0) / 100;
  const irpf = base * (parseFloat(document.getElementById('irpfPct').value) || 0) / 100;
  document.getElementById('resBase').textContent = base.toFixed(2) + ' €';
  document.getElementById('resIva').textContent = iva.toFixed(2) + ' €';
  document.getElementById('resIrpf').textContent = irpf.toFixed(2) + ' €';
  document.getElementById('resTotal').textContent = (base + iva - irpf).toFixed(2) + ' €';
}
document.querySelectorAll('.linea-num').forEach(i => i.addEventListener('input', recalcTotales));
recalcTotales();
</script>
{% endblock %}
