{% extends 'base.html' %}
{% block content %}
<div class="toolbar">
  <div>
    <h1>{{ t('ldap.title') }}</h1>
    <p class="muted">{{ t('ldap.description') }}</p>
  </div>
  <div class="toolbar-actions">
    <a class="button button-secondary" href="/users">{{ t('ldap.back_to_users') }}</a>
  </div>
</div>

<form method="post" action="/settings/ldap-search" class="panel">
  <label>{{ t('ldap.search_label') }}
    <input type="text" name="ldap_query" value="{{ query }}" placeholder="{{ t('ldap.search_placeholder') }}">
  </label>
  <div class="toolbar-actions">
    <button type="submit">🔎 {{ t('ldap.query') }}</button>
    <a class="button button-secondary" href="/settings/ldap-search?show_all=1">{{ t('ldap.show_all') }}</a>
  </div>
  <p class="muted">{{ t('ldap.search_help') }}</p>
</form>

{% if loaded %}
<form method="post" action="/settings/ldap-search/import" class="panel">
  <div class="toolbar">
    <h2>{{ t('ldap.users_found', count=results|length) }}</h2>
    <div class="toolbar-actions">
      <button type="submit">＋ {{ t('ldap.save_selected') }}</button>
    </div>
  </div>
  <div class="table-scroll">
    <table class="data-table">
      <thead><tr>
        <th class="selection-column" data-no-filter="1"><input type="checkbox" id="select-all-ldap"></th>
        <th>{{ t('ldap.username') }}</th>
        <th>{{ t('ldap.display_name') }}</th>
        <th>{{ t('ldap.email') }}</th>
        <th>{{ t('ldap.status') }}</th>
        <th>{{ t('ldap.dn') }}</th>
      </tr></thead>
      <tbody>
      {% for item in results %}
        <tr>
          <td class="selection-column"><input type="checkbox" class="ldap-select" name="usernames" value="{{ item.username }}" {% if item.existing and item.existing_source != 'ldap' %}disabled{% endif %}></td>
          <td>{{ item.username }}</td>
          <td>{{ item.display_name }}</td>
          <td>{{ item.email }}</td>
          <td>{% if item.existing %}{{ t('ldap.exists') }}{% else %}{{ t('ldap.can_save') }}{% endif %}</td>
          <td>{{ item.dn }}</td>
        </tr>
      {% endfor %}
      </tbody>
    </table>
  </div>
</form>
<script>
(() => {
  const all = document.getElementById('select-all-ldap');
  const boxes = [...document.querySelectorAll('.ldap-select:not(:disabled)')];
  all?.addEventListener('change', () => boxes.forEach(box => box.checked = all.checked));
})();
</script>
{% endif %}
{% endblock %}
