{% extends "base.html" %}
{% set active_page = "users" %}
{% block page_title %}Benutzer{% endblock %}
{% block page_sub %}<div class="topbar-sub">{{ users|length }} Benutzer</div>{% endblock %}

{% block content %}
{% import "_hint_icon.html" as hi %}

<div class="section-head">
  <div>
    <h2 style="font-size:16px;">Benutzer</h2>
    <div class="hint">Die Gruppe bestimmt die Rechte eines Benutzers.</div>
  </div>
  {% if current_user.has_permission('users.create') %}
  <div class="flex gap-2">
    {% if ldap_enabled %}
    <button type="button" class="btn btn-secondary" data-open-modal="ldapAddModal" onclick="resetLdapSearch();">
      <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="11" cy="11" r="8"/><path d="M21 21l-4.35-4.35"/></svg>
      Aus Active Directory hinzufügen
    </button>
    {% endif %}
    <button type="button" class="btn btn-primary" data-open-modal="userModal" onclick="document.getElementById('userForm').reset();">
      <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><path d="M12 5v14M5 12h14"/></svg>
      Neuer Benutzer
    </button>
  </div>
  {% endif %}
</div>

<div class="table-wrap">
  <div class="table-toolbar">
    <div class="search-input">
      <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><circle cx="11" cy="11" r="7"/><path d="M21 21l-4.3-4.3"/></svg>
      <input type="text" id="userSearch" placeholder="Benutzer durchsuchen…" oninput="filterTable('userSearch','usersTable')">
    </div>
  </div>
  <div style="overflow-x:auto;">
  <table class="data-table" id="usersTable" data-sortable>
    <thead><tr>
      <th data-sort-key="username">Username</th>
      <th data-sort-key="firstname">Vorname</th>
      <th data-sort-key="lastname">Nachname</th>
      <th data-sort-key="group">Gruppe</th>
      <th style="width:1%;">Aktionen</th>
    </tr></thead>
    <tbody>
      {% for u in users %}
      {% set group_label = 'Admin' if u['is_admin'] else (u['group_names'] or '') %}
      {% set is_ldap = u['auth_source'] == 'ldap' %}
      <tr data-sort-username="{{ u['username']|lower }}" data-sort-firstname="{{ (u['first_name'] or '')|lower }}" data-sort-lastname="{{ (u['last_name'] or '')|lower }}" data-sort-group="{{ group_label|lower }}">
        <td class="cell-name">
          {{ u['username'] }}
          {% if is_ldap %}<span class="pill user" style="font-size:10px; padding:2px 7px;" title="Konto stammt aus Active Directory/LDAP, Passwort wird dort verwaltet">AD</span>{% endif %}
          {% if u['is_locked'] %}<span class="pill" style="font-size:10px; padding:2px 7px; background:var(--danger-dim); color:var(--danger);" title="Login für dieses Konto ist gesperrt">Gesperrt</span>{% endif %}
          {% if u['email'] %}<div class="text-faint" style="font-size:11px;">{{ u['email'] }}</div>{% endif %}
        </td>
        <td class="text-dim">{{ u['first_name'] or '—' }}</td>
        <td class="text-dim">{{ u['last_name'] or '—' }}</td>
        <td>
          {% if u['is_admin'] %}
          <span class="pill admin">Admin</span>
          {% else %}
          <span class="text-dim">{{ u['group_names'] or '—' }}</span>
          {% endif %}
        </td>
        {% set may_touch_target = current_user.is_admin or not u['is_admin'] %}
        <td>
          <div class="row-actions">
            {% if current_user.has_permission('users.edit') and may_touch_target and not is_ldap %}
            <button class="icon-btn" title="Bearbeiten"
                    onclick="openEditModal({{ u['id'] }}, '{{ u['username'] }}', '{{ u['first_name'] or '' }}', '{{ u['last_name'] or '' }}', '{{ u['email'] or '' }}')">
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 20h9"/><path d="M16.5 3.5a2.1 2.1 0 013 3L7 19l-4 1 1-4z"/></svg>
            </button>
            {% endif %}
            {% if current_user.has_permission('users.edit') and may_touch_target %}
            <button class="icon-btn" title="Gruppe zuweisen"
                    onclick="openGroupModal({{ u['id'] }}, '{{ 'admin' if u['is_admin'] else (u['group_id'] or '') }}')">
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="18" cy="5" r="2.5"/><circle cx="6" cy="12" r="2.5"/><circle cx="18" cy="19" r="2.5"/><path d="M8.2 10.7l7.6-4.4M8.2 13.3l7.6 4.4"/></svg>
            </button>
            {% endif %}
            {% if current_user.has_permission('users.edit') and may_touch_target and u['id'] != current_user.id %}
            <form method="post" data-confirm="„{{ u['username'] }}“ wirklich {{ 'entsperren' if u['is_locked'] else 'sperren' }}?">
              <input type="hidden" name="toggle_lock" value="{{ u['id'] }}">
              <button type="submit" class="icon-btn" title="{{ 'Entsperren' if u['is_locked'] else 'Sperren' }}">
                {% if u['is_locked'] %}
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="11" width="18" height="11" rx="2"/><path d="M7 11V7a5 5 0 019.9-1"/></svg>
                {% else %}
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="11" width="18" height="11" rx="2"/><path d="M7 11V7a5 5 0 0110 0v4"/></svg>
                {% endif %}
              </button>
            </form>
            {% endif %}
            {% if current_user.has_permission('users.edit') and may_touch_target %}
            <form method="post" data-confirm="Willst du „{{ u['username'] }}“ wirklich löschen?">
              <input type="hidden" name="delete_user" value="{{ u['id'] }}">
              <button type="submit" class="icon-btn" style="color:var(--danger);" title="Löschen">
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 6h18M8 6V4a2 2 0 012-2h4a2 2 0 012 2v2m3 0l-1 14a2 2 0 01-2 2H7a2 2 0 01-2-2L4 6"/></svg>
              </button>
            </form>
            {% endif %}
          </div>
        </td>
      </tr>
      {% else %}
      <tr class="empty-row"><td colspan="5">Noch keine Benutzer vorhanden.</td></tr>
      {% endfor %}
    </tbody>
  </table>
  </div>
</div>

<div class="modal-overlay" id="userModal">
  <div class="modal" style="max-width:1000px;">
    <form method="post" id="userForm">
      <div class="modal-header">
        <h3>Neuen Benutzer anlegen</h3>
        <button type="button" class="modal-close" data-close-modal>&times;</button>
      </div>
      <div class="modal-body">
        <div class="field"><label>Vorname</label><input type="text" name="first_name"></div>
        <div class="field"><label>Name</label><input type="text" name="last_name"></div>
        <div class="field"><label>Username</label><input type="text" name="username" required></div>
        <div class="field"><label>E-Mail</label><input type="email" name="email" placeholder="optional — ermöglicht Login per E-Mail"></div>
        <div class="field"><label>Passwort</label><input type="password" name="password" required></div>
        <div class="field">
          <label>Gruppe</label>
          <select name="group_id">
            {% for g in all_groups %}<option value="{{ g['id'] }}" {% if g['is_default'] %}selected{% endif %}>{{ g['name'] }}</option>{% endfor %}
            {% if current_user.is_admin %}<option value="admin">Admin</option>{% endif %}
          </select>
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-close-modal>Abbrechen</button>
        <button type="submit" name="add_user" value="1" class="btn btn-primary">Anlegen</button>
      </div>
    </form>
  </div>
</div>

<div class="modal-overlay" id="editModal">
  <div class="modal">
    <form method="post" id="editForm">
      <input type="hidden" name="user_id" id="edit_user_id">
      <div class="modal-header">
        <h3>Benutzer bearbeiten</h3>
        <button type="button" class="modal-close" data-close-modal>&times;</button>
      </div>
      <div class="modal-body">
        <div class="field"><label>Vorname</label><input type="text" name="first_name" id="edit_first_name"></div>
        <div class="field"><label>Name</label><input type="text" name="last_name" id="edit_last_name"></div>
        <div class="field"><label>Username</label><input type="text" name="username" id="edit_username" required></div>
        <div class="field"><label>E-Mail</label><input type="email" name="email" id="edit_email" placeholder="optional — ermöglicht Login per E-Mail"></div>
        <div class="field"><label>Neues Passwort</label>
          <input type="password" name="new_password" placeholder="Nur bei Änderung ausfüllen">
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-close-modal>Abbrechen</button>
        <button type="submit" name="edit_user" value="1" class="btn btn-primary">Speichern</button>
      </div>
    </form>
  </div>
</div>

{% if ldap_enabled %}
<div class="modal-overlay" id="ldapAddModal">
  <div class="modal">
    <form method="post" id="ldapAddForm">
      <input type="hidden" name="ldap_username" id="ldap_add_username">
      <div class="modal-header">
        <h3>Aus Active Directory hinzufügen</h3>
        <button type="button" class="modal-close" data-close-modal>&times;</button>
      </div>
      <div class="modal-body">
        <div class="field">
          <label>Suche</label>
          <input type="text" id="ldapSearchInput" placeholder="Name, Benutzername oder UPN eingeben …" autocomplete="off">
          <div class="field-hint" id="ldapSearchStatus">Mindestens 2 Zeichen eingeben.</div>
        </div>
        <div id="ldapSearchResults" style="max-height:240px; overflow-y:auto; display:flex; flex-direction:column; gap:4px;"></div>
        <div class="field" id="ldapAddGroupField" style="display:none;">
          <label>Gruppe für <span id="ldapAddSelectedName"></span></label>
          <select name="group_id" id="ldapAddGroupSelect">
            {% for g in all_groups %}<option value="{{ g['id'] }}" {% if g['is_default'] %}selected{% endif %}>{{ g['name'] }}</option>{% endfor %}
            {% if current_user.is_admin %}<option value="admin">Admin</option>{% endif %}
          </select>
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-close-modal>Abbrechen</button>
        <button type="submit" name="ldap_add_user" value="1" class="btn btn-primary" id="ldapAddSubmit" disabled>Hinzufügen</button>
      </div>
    </form>
  </div>
</div>
{% endif %}

<div class="modal-overlay" id="groupModal">
  <div class="modal" style="max-width:380px;">
    <form method="post" id="groupForm">
      <input type="hidden" name="user_id" id="group_user_id">
      <div class="modal-header">
        <h3>Gruppe zuweisen</h3>
        <button type="button" class="modal-close" data-close-modal>&times;</button>
      </div>
      <div class="modal-body">
        <div class="field">
          <label>Gruppe {{ hi.hint_icon("Ersetzt die bisherige Gruppen-/Rollenzuordnung dieses Benutzers.", "Gruppe") }}</label>
          <select name="group_id" id="group_select">
            <option value="">Keine Gruppe</option>
            {% for g in all_groups %}<option value="{{ g['id'] }}">{{ g['name'] }}</option>{% endfor %}
            {% if current_user.is_admin %}<option value="admin">Admin</option>{% endif %}
          </select>
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-close-modal>Abbrechen</button>
        <button type="submit" name="assign_group" value="1" class="btn btn-primary">Speichern</button>
      </div>
    </form>
  </div>
</div>

{% endblock %}

{% block scripts %}
<script>
function filterTable(inputId, tableId) {
    const q = document.getElementById(inputId).value.trim().toLowerCase();
    document.querySelectorAll(`#${tableId} tbody tr`).forEach(row => {
        if (row.classList.contains("empty-row")) return;
        row.style.display = row.innerText.toLowerCase().includes(q) ? "" : "none";
    });
}

function openEditModal(userId, username, firstName, lastName, email) {
    document.getElementById("edit_user_id").value = userId;
    document.getElementById("edit_username").value = username;
    document.getElementById("edit_first_name").value = firstName;
    document.getElementById("edit_last_name").value = lastName;
    document.getElementById("edit_email").value = email || "";
    document.querySelector("#editForm input[name='new_password']").value = "";
    PoeUI.openModal("editModal");
}
function openGroupModal(userId, groupChoice) {
    document.getElementById("group_user_id").value = userId;
    document.getElementById("group_select").value = groupChoice || "";
    PoeUI.openModal("groupModal");
}

{% if ldap_enabled %}
function resetLdapSearch() {
    document.getElementById("ldapSearchInput").value = "";
    document.getElementById("ldapSearchResults").innerHTML = "";
    document.getElementById("ldapSearchStatus").textContent = "Mindestens 2 Zeichen eingeben.";
    document.getElementById("ldapAddGroupField").style.display = "none";
    document.getElementById("ldap_add_username").value = "";
    document.getElementById("ldapAddSubmit").disabled = true;
}

(function () {
    var input = document.getElementById("ldapSearchInput");
    var results = document.getElementById("ldapSearchResults");
    var status = document.getElementById("ldapSearchStatus");
    if (!input) return;
    var debounceTimer = null;

    input.addEventListener("input", function () {
        var q = input.value.trim();
        clearTimeout(debounceTimer);
        if (q.length < 2) {
            results.innerHTML = "";
            status.textContent = "Mindestens 2 Zeichen eingeben.";
            return;
        }
        status.textContent = "Suche …";
        debounceTimer = setTimeout(function () {
            fetch("{{ url_for('users_ldap_search') }}?q=" + encodeURIComponent(q))
                .then(function (r) { return r.json(); })
                .then(function (data) {
                    if (!Array.isArray(data)) {
                        status.textContent = data.error || "Fehler bei der Suche.";
                        return;
                    }
                    results.innerHTML = "";
                    if (!data.length) {
                        status.textContent = "Keine Treffer (oder bereits lokal bekannt).";
                        return;
                    }
                    status.textContent = data.length + " Treffer:";
                    data.forEach(function (u) {
                        var full = [u.first_name, u.last_name].filter(Boolean).join(" ");
                        var row = document.createElement("button");
                        row.type = "button";
                        row.className = "btn btn-secondary btn-sm";
                        row.style.textAlign = "left";
                        row.style.justifyContent = "flex-start";
                        row.textContent = u.username + (full ? " — " + full : "") + (u.email ? " (" + u.email + ")" : "");
                        row.addEventListener("click", function () {
                            document.getElementById("ldap_add_username").value = u.username;
                            document.getElementById("ldapAddSelectedName").textContent = u.username;
                            document.getElementById("ldapAddGroupField").style.display = "";
                            document.getElementById("ldapAddSubmit").disabled = false;
                        });
                        results.appendChild(row);
                    });
                })
                .catch(function () { status.textContent = "Fehler bei der Suche."; });
        }, 300);
    });
})();
{% endif %}
</script>
{% endblock %}
