{% extends 'base.html' %}
{% block title %}Nuevo asiento manual{% endblock %}

{% block extra_head %}
<style>
.linea-row td { vertical-align: middle; }
.cuenta-input { font-family: monospace; font-size: .9rem; }
</style>
{% endblock %}

{% block content %}
<div class="d-flex align-items-center mb-4">
  <a href="{{ url_for('cuentas.asientos') }}" class="btn btn-outline-secondary btn-sm me-3">
    <i class="bi bi-arrow-left"></i>
  </a>
  <div>
    <h4 class="fw-bold mb-0" style="color:#0f2744">
      <i class="bi bi-journal-plus me-2" style="color:#fbbf24"></i>Nuevo asiento manual
    </h4>
    <p class="text-muted mb-0 mt-1" style="font-size:.82rem">El asiento debe cuadrar (suma Debe = suma Haber).</p>
  </div>
</div>

{% 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="form-asiento">
<div class="row">
  <div class="col-lg-8">

    <div class="card mb-4">
      <div class="card-header">Cabecera del asiento</div>
      <div class="card-body row g-3">
        <div class="col-md-4">
          <label class="form-label">Fecha <span class="text-danger">*</span></label>
          <input type="date" name="fecha" class="form-control" value="{{ hoy }}" required>
        </div>
        <div class="col-md-8">
          <label class="form-label">Descripción <span class="text-danger">*</span></label>
          <input type="text" name="descripcion" class="form-control" required placeholder="Concepto del asiento...">
        </div>
      </div>
    </div>

    <div class="card mb-4">
      <div class="card-header d-flex align-items-center justify-content-between">
        <span>Líneas del asiento</span>
        <span id="balance-badge" class="badge bg-secondary">Debe: 0,00 · Haber: 0,00</span>
      </div>
      <div class="table-responsive">
        <table class="table mb-0" id="tabla-lineas">
          <thead>
            <tr>
              <th style="width:110px">Cuenta</th>
              <th>Nombre cuenta</th>
              <th>Concepto línea</th>
              <th class="text-end" style="width:120px">Debe</th>
              <th class="text-end" style="width:120px">Haber</th>
              <th style="width:44px"></th>
            </tr>
          </thead>
          <tbody id="lineas-body">
            <!-- filas dinámicas -->
          </tbody>
        </table>
      </div>
      <div class="card-footer">
        <button type="button" class="btn btn-outline-secondary btn-sm" onclick="addLinea()">
          <i class="bi bi-plus-lg me-1"></i>Añadir línea
        </button>
      </div>
    </div>

    <div class="d-flex gap-2">
      <button type="submit" class="btn btn-primary" id="btn-guardar">
        <i class="bi bi-check2 me-1"></i>Registrar asiento
      </button>
      <a href="{{ url_for('cuentas.asientos') }}" class="btn btn-outline-secondary">Cancelar</a>
    </div>
  </div>

  <div class="col-lg-4">
    <div class="card">
      <div class="card-header">Cuentas frecuentes</div>
      <div class="card-body p-0">
        <table class="table table-sm mb-0" style="font-size:.8rem">
          <thead><tr><th>Código</th><th>Cuenta</th></tr></thead>
          <tbody>
            {% set frecuentes = ['430','400','472','477','473','4751','476','570','572','640','642','700','705','600','621','622','623','624','625','627','628','629','681','682'] %}
            {% for c in cuentas %}
              {% if c.codigo in frecuentes %}
              <tr>
                <td><a href="#" class="font-monospace fw-bold text-decoration-none" style="color:#fbbf24" onclick="insertCodigo('{{ c.codigo }}');return false">{{ c.codigo }}</a></td>
                <td class="text-muted">{{ c.nombre[:35] }}{% if c.nombre|length > 35 %}…{% endif %}</td>
              </tr>
              {% endif %}
            {% endfor %}
          </tbody>
        </table>
      </div>
    </div>
  </div>
</div>
</form>

<script>
const CUENTAS = {{ cuentas | tojson }};
const cuentaMap = {};
CUENTAS.forEach(c => cuentaMap[c.codigo] = c.nombre);

let rowIdx = 0;
let _lastFocused = null;

function addLinea(codigo='', debe='', haber='', concepto='') {
  const tbody = document.getElementById('lineas-body');
  const tr = document.createElement('tr');
  tr.className = 'linea-row';
  tr.dataset.idx = rowIdx;
  tr.innerHTML = `
    <td>
      <input type="text" name="cuenta_codigo[]" class="form-control form-control-sm cuenta-input"
             value="${codigo}" placeholder="ej. 430"
             oninput="resolverNombre(this)" onfocus="_lastFocused=this" autocomplete="off">
    </td>
    <td>
      <span class="nombre-cuenta text-muted" style="font-size:.82rem">${codigo ? (cuentaMap[codigo] || '') : ''}</span>
    </td>
    <td>
      <input type="text" name="concepto_linea[]" class="form-control form-control-sm"
             value="${concepto}" placeholder="Descripción línea...">
    </td>
    <td>
      <input type="number" name="debe[]" class="form-control form-control-sm text-end"
             value="${debe}" step="0.01" min="0" placeholder="0.00" oninput="calcBalance()">
    </td>
    <td>
      <input type="number" name="haber[]" class="form-control form-control-sm text-end"
             value="${haber}" step="0.01" min="0" placeholder="0.00" oninput="calcBalance()">
    </td>
    <td>
      <button type="button" class="btn btn-sm btn-outline-danger" onclick="this.closest('tr').remove();calcBalance()">
        <i class="bi bi-x"></i>
      </button>
    </td>`;
  tbody.appendChild(tr);
  rowIdx++;
  calcBalance();
}

function resolverNombre(inp) {
  const codigo = inp.value.trim().toUpperCase();
  const span = inp.closest('tr').querySelector('.nombre-cuenta');
  span.textContent = cuentaMap[codigo] || (codigo ? '?' : '');
}

function insertCodigo(cod) {
  if (_lastFocused && _lastFocused.name === 'cuenta_codigo[]') {
    _lastFocused.value = cod;
    resolverNombre(_lastFocused);
  } else {
    addLinea(cod);
  }
  calcBalance();
}

function calcBalance() {
  let d = 0, h = 0;
  document.querySelectorAll('input[name="debe[]"]').forEach(i => d += parseFloat(i.value)||0);
  document.querySelectorAll('input[name="haber[]"]').forEach(i => h += parseFloat(i.value)||0);
  const badge = document.getElementById('balance-badge');
  badge.textContent = `Debe: ${d.toFixed(2)} · Haber: ${h.toFixed(2)}`;
  const ok = Math.abs(d - h) < 0.01;
  badge.className = 'badge ' + (ok ? 'bg-success' : 'bg-danger');
}

// Iniciar con 4 filas vacías
addLinea(); addLinea(); addLinea(); addLinea();
</script>
{% endblock %}
