{% extends "base.html" %}
{% block title %}{% if ticket %}Editar ticket{% else %}Nuevo ticket de gasto{% endif %}{% endblock %}
{% block page_title %}{% if ticket %}Editar ticket{% else %}Nuevo ticket de gasto{% endif %}{% endblock %}

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

{% block extra_head %}
<style>
  #preview-img { max-height: 200px; border-radius: 8px; border: 1px solid #e2e8f0; }
</style>
{% endblock %}

{% block content %}
<div class="row justify-content-center">
  <div class="col-lg-7">
    <div class="card">
      <div class="card-body p-4">
        <form method="post" enctype="multipart/form-data" id="form-ticket">

          <div class="row g-3 mb-3">
            <div class="col-md-6">
              <label class="form-label fw-semibold">Concepto *</label>
              <input type="text" name="concepto" class="form-control"
                     value="{{ ticket.concepto if ticket else '' }}"
                     placeholder="Ej: Comida con cliente, Parking, Material…" required autofocus>
            </div>
            <div class="col-md-6">
              <label class="form-label fw-semibold">Proveedor / Lugar</label>
              <input type="text" name="proveedor" class="form-control"
                     value="{{ ticket.proveedor if ticket and ticket.proveedor else '' }}"
                     placeholder="Nombre del comercio (opcional)">
            </div>
          </div>

          <div class="row g-3 mb-3">
            <div class="col-md-4">
              <label class="form-label fw-semibold">Fecha *</label>
              <input type="date" name="fecha" class="form-control"
                     value="{{ ticket.fecha if ticket else hoy }}" required>
            </div>
            <div class="col-md-4">
              <label class="form-label fw-semibold">Importe total (€) *</label>
              <input type="number" name="importe" id="importe" class="form-control"
                     value="{{ ticket.importe if ticket else '0.00' }}"
                     step="0.01" min="0" required oninput="calcBase()">
              <div class="form-text">IVA ya incluido</div>
            </div>
            <div class="col-md-4">
              <label class="form-label fw-semibold">IVA incluido (%)</label>
              <select name="iva_pct" id="iva_pct" class="form-select" onchange="calcBase()">
                {% for pct in [0, 4, 10, 21] %}
                <option value="{{ pct }}"
                  {% if ticket and ticket.iva_pct == pct %}selected
                  {% elif not ticket and pct == 21 %}selected
                  {% endif %}>{{ pct }}%</option>
                {% endfor %}
              </select>
              <div class="form-text">Base: <strong id="lbl-base">—</strong></div>
            </div>
          </div>

          <div class="row g-3 mb-3">
            <div class="col-md-6">
              <label class="form-label fw-semibold">Categoría</label>
              <select name="categoria_id" class="form-select">
                <option value="">— Sin categoría —</option>
                {% for cat in categorias %}
                <option value="{{ cat.id }}"
                  {% if ticket and ticket.categoria_id == cat.id %}selected{% endif %}>
                  {{ cat.nombre }}
                </option>
                {% endfor %}
              </select>
            </div>
            <div class="col-md-6">
              <label class="form-label fw-semibold">Forma de pago</label>
              <select name="metodo_pago" class="form-select">
                {% for m in metodos %}
                <option value="{{ m }}"
                  {% if ticket and ticket.metodo_pago == m %}selected
                  {% elif not ticket and m == 'efectivo' %}selected
                  {% endif %}>{{ m | capitalize }}</option>
                {% endfor %}
              </select>
            </div>
          </div>

          <div class="mb-3">
            <label class="form-label fw-semibold">
              <i class="bi bi-paperclip me-1"></i>Adjuntar justificante
            </label>
            {% if ticket and ticket.archivo_path %}
            <div class="mb-2">
              <button type="button" class="btn btn-sm btn-outline-secondary"
                      onclick="verArchivo('{{ url_for('tickets.ver_archivo', filename=ticket.archivo_path) }}', {{ ticket.concepto | tojson }})">
                <i class="bi bi-eye me-1"></i>Ver archivo actual
              </button>
            </div>
            {% endif %}
            <input type="file" name="archivo" class="form-control" accept=".pdf,.png,.jpg,.jpeg,.webp"
                   onchange="previewImg(this)">
            <div class="form-text">PDF o imagen del ticket/recibo (opcional)</div>
            <img id="preview-img" src="" class="mt-2 d-none">
          </div>

          <div class="mb-4">
            <label class="form-label fw-semibold">Notas</label>
            <textarea name="notas" class="form-control" rows="2"
                      placeholder="Observaciones adicionales...">{{ ticket.notas if ticket and ticket.notas else '' }}</textarea>
          </div>

          <div class="d-flex gap-2">
            <button type="submit" class="btn btn-primary">
              <i class="bi bi-check-lg me-1"></i>
              {% if ticket %}Guardar cambios{% else %}Registrar ticket{% endif %}
            </button>
            <a href="{{ url_for('tickets.lista') }}" class="btn btn-outline-secondary">Cancelar</a>
          </div>
        </form>
      </div>
    </div>
  </div>
</div>
{% endblock %}

{% block extra_scripts %}
<script>
function calcBase() {
  var imp = parseFloat(document.getElementById('importe').value) || 0;
  var iva = parseFloat(document.getElementById('iva_pct').value) || 0;
  var iva_imp = imp * iva / (100 + iva);
  var base = imp - iva_imp;
  document.getElementById('lbl-base').textContent =
    base.toFixed(2) + ' € (IVA: ' + iva_imp.toFixed(2) + ' €)';
}
function previewImg(inp) {
  var img = document.getElementById('preview-img');
  if (inp.files && inp.files[0]) {
    var f = inp.files[0];
    if (f.type.startsWith('image/')) {
      img.src = URL.createObjectURL(f);
      img.classList.remove('d-none');
    } else {
      img.classList.add('d-none');
    }
  }
}
calcBase();
</script>
{% endblock %}
