{% extends 'base.html' %}
{% block content %}
  <div style="display:flex;justify-content:space-between;align-items:center;">
    <h2>Users</h2>
    <a href="{{ url_for('user_new') }}" class="btn-primary">New User</a>
  </div>
  
  <!-- Live Search -->
  <div class="card" style="margin-top:8px; margin-bottom:8px;">
    <input type="text" id="user-search" placeholder="🔍 Search users by name, email, role, company, phone, address..." 
           style="width: 100%; padding: 12px; border: 1px solid #ddd; border-radius: 8px; font-size: 14px; box-sizing: border-box;">
  </div>
  
  <div class="card" style="margin-top:8px; overflow:auto">
    <table class="table" id="users-table">
      <thead><tr><th>Name</th><th>Email</th><th>Role</th><th>Company</th><th>Phone</th><th>Address</th><th>Tax</th><th>Bank</th><th>Reports To</th><th>Created</th><th>Actions</th></tr></thead>
      <tbody>
        {% for u in users %}
        <tr>
          <td>{{ u.name }}</td>
          <td>{{ u.email }}</td>
          <td>{{ u.role|capitalize }}</td>
          <td>{{ u.company_name or '-' }}</td>
          <td>{{ u.phone or '-' }}</td>
          <td>
            {{ (u.address_line1 or '') ~ (' ' ~ u.address_line2 if u.address_line2 else '') ~ ', ' ~ (u.city or '') ~ ', ' ~ (u.state or '') ~ ' ' ~ (u.postal_code or '') ~ ', ' ~ (u.country or '') }}
          </td>
          <td>{{ (u.gst_vat or '-') ~ (' / ' ~ u.pan_tax_id if u.pan_tax_id else '') }}</td>
          <td>{{ (u.bank_account_name or '-') ~ (' #' ~ u.bank_account_number if u.bank_account_number else '') ~ (' ' ~ u.bank_ifsc_swift if u.bank_ifsc_swift else '') }}</td>
          <td>
            {% if u.parent_id %}
              {% set mgr = (users | selectattr('id', 'equalto', u.parent_id) | list | first) %}
              {{ mgr.name if mgr else '-' }}
            {% else %}-{% endif %}
          </td>
          <td>{{ u.created_at.strftime('%Y-%m-%d') }}</td>
          <td>
            <a href="{{ url_for('user_edit', user_id=u.id) }}" class="btn-secondary" style="padding: 4px 8px; font-size: 12px;">Edit</a>
          </td>
        </tr>
        {% else %}
          <tr><td colspan="11" class="muted">No users yet.</td></tr>
        {% endfor %}
      </tbody>
    </table>
  </div>
  
  <script>
    document.addEventListener('DOMContentLoaded', function() {
      initLiveSearch('user-search', 'users-table');
    });
  </script>
{% endblock %}


