{% extends "base.html" %}
{% block title %}{{ 'Nuevo empleado' if accion=='nuevo' else 'Editar empleado' }}{% endblock %}
{% block page_title %}{{ 'Nuevo empleado' if accion=='nuevo' else 'Editar empleado' }}{% endblock %}

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

{% block content %}
<div class="row g-4 justify-content-center">
  <div class="col-lg-7">

    {% if error %}
    <div class="alert alert-danger">{{ error }}</div>
    {% endif %}

    <form method="post">

      <!-- Datos personales -->
      <div class="card border-0 shadow-sm mb-4">
        <div class="card-header border-0" style="background:linear-gradient(135deg,#ecfdf5,#d1fae5)">
          <i class="bi bi-person me-2 text-success"></i>
          <span class="fw-semibold" style="color:#065f46">Datos personales</span>
        </div>
        <div class="card-body">
          <div class="row g-3">
            <div class="col-6">
              <label class="form-label">Nombre <span class="text-danger">*</span></label>
              <input type="text" name="nombre" class="form-control" required autofocus
                     value="{{ emp.nombre if emp else request.form.get('nombre','') }}">
            </div>
            <div class="col-6">
              <label class="form-label">Apellidos</label>
              <input type="text" name="apellidos" class="form-control"
                     value="{{ emp.apellidos if emp else request.form.get('apellidos','') }}">
            </div>
            <div class="col-6">
              <label class="form-label">NIF / NIE</label>
              <input type="text" name="nif" class="form-control" placeholder="12345678A"
                     value="{{ emp.nif if emp else request.form.get('nif','') }}">
            </div>
            <div class="col-6">
              <label class="form-label">Cargo / Puesto</label>
              <input type="text" name="cargo" class="form-control" placeholder="ej. Desarrollador"
                     value="{{ emp.cargo if emp else request.form.get('cargo','') }}">
            </div>
            <div class="col-6">
              <label class="form-label">Email</label>
              <input type="email" name="email" class="form-control"
                     value="{{ emp.email if emp else request.form.get('email','') }}">
            </div>
            <div class="col-6">
              <label class="form-label">Teléfono</label>
              <input type="text" name="telefono" class="form-control"
                     value="{{ emp.telefono if emp else request.form.get('telefono','') }}">
            </div>
          </div>
        </div>
      </div>

      <!-- Datos laborales -->
      <div class="card border-0 shadow-sm mb-4">
        <div class="card-header border-0" style="background:linear-gradient(135deg,#eef3ff,#e0e7ff)">
          <i class="bi bi-briefcase me-2 text-primary"></i>
          <span class="fw-semibold text-primary">Datos laborales y retribución</span>
        </div>
        <div class="card-body">
          <div class="row g-3">
            <div class="col-md-6">
              <label class="form-label fw-semibold">Salario bruto mensual (€) <span class="text-danger">*</span></label>
              <div class="input-group">
                <input type="number" name="salario_bruto" class="form-control" step="0.01" min="0"
                       id="salario_bruto"
                       value="{{ emp.salario_bruto if emp else request.form.get('salario_bruto','0') }}"
                       oninput="recalcular()">
                <span class="input-group-text">€</span>
              </div>
              <div class="form-text">Bruto mensual antes de deducciones.</div>
            </div>
            <div class="col-md-6">
              <label class="form-label">Cuenta bancaria (IBAN)</label>
              <input type="text" name="cuenta_bancaria" class="form-control"
                     placeholder="ES00 0000 0000 00 0000000000"
                     value="{{ emp.cuenta_bancaria if emp else request.form.get('cuenta_bancaria','') }}">
            </div>

            <div class="col-md-4">
              <label class="form-label">Retención IRPF (%)</label>
              <div class="input-group">
                <input type="number" name="irpf_pct" class="form-control" step="0.01" min="0" max="45"
                       id="irpf_pct"
                       value="{{ emp.irpf_pct if emp else request.form.get('irpf_pct','15.0') }}"
                       oninput="recalcular()">
                <span class="input-group-text">%</span>
              </div>
            </div>
            <div class="col-md-4">
              <label class="form-label">SS trabajador (%)</label>
              <div class="input-group">
                <input type="number" name="ss_trab_pct" class="form-control" step="0.01" min="0"
                       id="ss_trab_pct"
                       value="{{ emp.ss_trab_pct if emp else request.form.get('ss_trab_pct','6.35') }}"
                       oninput="recalcular()">
                <span class="input-group-text">%</span>
              </div>
            </div>
            <div class="col-md-4">
              <label class="form-label">SS empresa (%)</label>
              <div class="input-group">
                <input type="number" name="ss_emp_pct" class="form-control" step="0.01" min="0"
                       id="ss_emp_pct"
                       value="{{ emp.ss_emp_pct if emp else request.form.get('ss_emp_pct','29.9') }}"
                       oninput="recalcular()">
                <span class="input-group-text">%</span>
              </div>
            </div>

            <!-- Preview cálculo en tiempo real -->
            <div class="col-12">
              <div class="p-3 rounded-2" style="background:#f8fafc;border:1px solid #e2e8f0">
                <div class="small fw-semibold text-muted mb-2">Cálculo estimado mensual</div>
                <div class="row g-2 text-center" style="font-size:.85rem">
                  <div class="col">
                    <div class="text-muted">Bruto</div>
                    <div class="fw-bold" id="p_bruto">0,00 €</div>
                  </div>
                  <div class="col text-danger">
                    <div>– IRPF</div>
                    <div class="fw-bold" id="p_irpf">0,00 €</div>
                  </div>
                  <div class="col text-warning">
                    <div>– SS Trab.</div>
                    <div class="fw-bold" id="p_ss_trab">0,00 €</div>
                  </div>
                  <div class="col text-success">
                    <div class="fw-semibold">= Neto</div>
                    <div class="fw-bold fs-5" id="p_neto">0,00 €</div>
                  </div>
                  <div class="col" style="border-left:2px solid #e2e8f0">
                    <div class="text-muted">Coste empresa</div>
                    <div class="fw-bold" id="p_coste">0,00 €</div>
                  </div>
                </div>
              </div>
            </div>

            <div class="col-6">
              <label class="form-label">Fecha de alta</label>
              <input type="date" name="fecha_alta" class="form-control"
                     value="{{ emp.fecha_alta if emp else '' }}">
            </div>
            {% if accion == 'editar' %}
            <div class="col-6">
              <label class="form-label">Fecha de baja</label>
              <input type="date" name="fecha_baja" class="form-control"
                     value="{{ emp.fecha_baja or '' }}">
            </div>
            <div class="col-12">
              <div class="form-check form-switch">
                <input class="form-check-input" type="checkbox" name="activo" id="activo"
                       {{ 'checked' if emp.activo }}>
                <label class="form-check-label" for="activo">Empleado activo</label>
              </div>
            </div>
            {% endif %}

            <div class="col-12">
              <label class="form-label">Notas</label>
              <textarea name="notas" class="form-control" rows="2"
                        placeholder="Observaciones, tipo de contrato, etc.">{{ emp.notas if emp else '' }}</textarea>
            </div>
          </div>
        </div>
      </div>

      <div class="d-flex gap-2">
        <button type="submit" class="btn btn-primary">
          <i class="bi bi-check2 me-1"></i>
          {{ 'Crear empleado' if accion=='nuevo' else 'Guardar cambios' }}
        </button>
        <a href="{{ url_for('nominas.empleados') }}" class="btn btn-outline-secondary">Cancelar</a>
      </div>
    </form>
  </div>
</div>
{% endblock %}

{% block extra_scripts %}
<script>
function fmt(n) {
  return n.toFixed(2).replace('.', ',') + ' €';
}
function recalcular() {
  const bruto   = parseFloat(document.getElementById('salario_bruto').value) || 0;
  const irpf_p  = parseFloat(document.getElementById('irpf_pct').value)      || 0;
  const sst_p   = parseFloat(document.getElementById('ss_trab_pct').value)   || 0;
  const sse_p   = parseFloat(document.getElementById('ss_emp_pct').value)    || 0;
  const irpf    = bruto * irpf_p / 100;
  const ss_trab = bruto * sst_p  / 100;
  const ss_emp  = bruto * sse_p  / 100;
  const neto    = bruto - irpf - ss_trab;
  const coste   = bruto + ss_emp;
  document.getElementById('p_bruto').textContent   = fmt(bruto);
  document.getElementById('p_irpf').textContent    = fmt(irpf);
  document.getElementById('p_ss_trab').textContent = fmt(ss_trab);
  document.getElementById('p_neto').textContent    = fmt(neto);
  document.getElementById('p_coste').textContent   = fmt(coste);
}
recalcular();
</script>
{% endblock %}
