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

{% block topbar_actions %}
<a href="{{ url_for('proveedores.nuevo') }}" class="btn btn-primary btn-sm">
  <i class="bi bi-plus-lg"></i> Nuevo proveedor
</a>
{% endblock %}

{% block content %}
<div class="card">
  <div class="card-header py-3 d-flex align-items-center justify-content-between">
    <span><i class="bi bi-truck me-2"></i>Listado de proveedores</span>
    <form class="d-flex gap-2" method="get">
      <input type="search" name="q" value="{{ buscar }}" class="form-control form-control-sm" placeholder="Buscar...">
      <button class="btn btn-sm btn-outline-secondary">Buscar</button>
      {% if buscar %}<a href="{{ url_for('proveedores.lista') }}" class="btn btn-sm btn-outline-secondary">✕</a>{% endif %}
    </form>
  </div>
  <div class="table-responsive">
    <table class="table table-hover mb-0">
      <thead>
        <tr>
          <th>Nombre</th>
          <th>NIF/CIF</th>
          <th>Email</th>
          <th>Teléfono</th>
          <th class="text-end">Total facturado</th>
          <th class="text-end">Pendiente</th>
          <th></th>
        </tr>
      </thead>
      <tbody>
        {% for p in proveedores %}
        <tr>
          <td>
            <a href="{{ url_for('proveedores.detalle', id=p.id) }}" class="fw-semibold text-decoration-none text-dark">
              {{ p.nombre }}
            </a>
            {% if p.ciudad %}<div class="text-muted" style="font-size:.78rem">{{ p.ciudad }}</div>{% endif %}
          </td>
          <td class="text-muted small">{{ p.nif or '—' }}</td>
          <td class="small">{{ p.email or '—' }}</td>
          <td class="small">{{ p.telefono or '—' }}</td>
          <td class="text-end fw-semibold small">{{ "%.2f"|format(stats[p.id].total) }} €</td>
          <td class="text-end small {% if stats[p.id].pendiente > 0 %}text-danger fw-semibold{% else %}text-muted{% endif %}">
            {{ "%.2f"|format(stats[p.id].pendiente) }} €
          </td>
          <td class="text-end">
            <a href="{{ url_for('proveedores.editar', id=p.id) }}" class="btn btn-outline-secondary btn-action">
              <i class="bi bi-pencil"></i>
            </a>
            <form method="post" action="{{ url_for('proveedores.eliminar', id=p.id) }}" class="d-inline"
                  onsubmit="return confirm('¿Eliminar proveedor?')">
              <button class="btn btn-outline-danger btn-action"><i class="bi bi-trash"></i></button>
            </form>
          </td>
        </tr>
        {% else %}
        <tr><td colspan="7" class="text-center text-muted py-4">
          {% if buscar %}Sin resultados para "{{ buscar }}"{% else %}No hay proveedores registrados{% endif %}
        </td></tr>
        {% endfor %}
      </tbody>
    </table>
  </div>
</div>
{% endblock %}
