{% extends "base.html" %}
{% set active_page = "credentials" %}
{% set can_create = current_user.has_permission('credentials.create') %}
{% set can_edit = current_user.has_permission('credentials.edit') %}
{% set can_delete = current_user.has_permission('credentials.edit') %}
{% set category_labels = dict(categories) %}
{% block page_title %}Zugangsdaten{% endblock %}
{% block page_sub %}<div class="topbar-sub">{{ credentials|length }} Zugangsdaten</div>{% endblock %}

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

<div class="section-head">
  <div>
    <h2 style="font-size:16px;">Zugangsdaten</h2>
    <div class="hint">Können mehreren Switchen zugleich zugeordnet werden.</div>
  </div>
  {% if can_create %}
  <button type="button" class="btn btn-primary" data-open-modal="addCredentialModal">
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><path d="M12 5v14M5 12h14"/></svg>
    Neue Zugangsdaten
  </button>
  {% 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="credentialSearch" placeholder="Zugangsdaten durchsuchen…" oninput="filterTable('credentialSearch','credentialsTable')">
    </div>
  </div>
  <div style="overflow-x:auto;">
  <table class="data-table" id="credentialsTable" data-sortable>
    <thead><tr>
      <th data-sort-key="name">Name</th>
      <th data-sort-key="username">Username</th>
      <th data-sort-key="category">Kategorie</th>
      <th data-sort-key="usage">Verwendet von</th>
      <th style="width:1%;">Aktionen</th>
    </tr></thead>
    <tbody>
      {% for c in credentials %}
      {% set usage_total = c['switch_count'] + c['device_count'] %}
      <tr data-sort-name="{{ c['name']|lower }}" data-sort-username="{{ c['username']|lower }}" data-sort-category="{{ c['category'] }}" data-sort-usage="{{ usage_total }}">
        <td class="cell-name">{{ c['name'] }}</td>
        <td class="mono">{{ c['username'] }}</td>
        <td>{{ category_labels.get(c['category'], c['category']) }}</td>
        <td class="text-dim">
          {% if usage_total == 0 %}—{% else %}
            {% if c['switch_count'] %}{{ c['switch_count'] }} Switch{{ 'e' if c['switch_count'] != 1 else '' }}{% endif %}
            {% if c['switch_count'] and c['device_count'] %}, {% endif %}
            {% if c['device_count'] %}{{ c['device_count'] }} Gerät{{ 'e' if c['device_count'] != 1 else '' }}{% endif %}
          {% endif %}
        </td>
        <td>
          <div class="row-actions">
            {% if can_edit %}
            <button class="icon-btn" title="Bearbeiten"
                    onclick="openEditCredentialModal({{ c['id'] }}, '{{ c['name'] }}', '{{ c['username'] }}', '{{ c['category'] }}')">
              <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 can_delete %}
            <form method="post" data-confirm="Zugangsdaten „{{ c['name'] }}“ wirklich löschen?">
              <input type="hidden" name="delete_credential" value="{{ c['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 Zugangsdaten vorhanden.</td></tr>
      {% endfor %}
    </tbody>
  </table>
  </div>
</div>

{% if can_create %}
<div class="modal-overlay" id="addCredentialModal">
  <div class="modal" style="max-width:1000px;">
    <form method="post" onsubmit="return validateCredentialForm(this, 'add');">
      <div class="modal-header">
        <h3>Neue Zugangsdaten</h3>
        <button type="button" class="modal-close" data-close-modal>&times;</button>
      </div>
      <div class="modal-body">
        <input type="hidden" name="add_credential" value="1">
        <div class="field"><label>Name</label>
          <input type="text" name="name" required placeholder="z.B. Standard-Switch-Login">
        </div>
        <div class="field"><label>Username</label>
          <input type="text" name="username" required placeholder="z.B. admin">
        </div>
        <div class="field"><label>Kategorie {{ hi.hint_icon("Bestimmt u.a., ob diese Zugangsdaten unter „Wartung“ für Bulk-Updates nutzbar sind.", "Kategorie") }}</label>
          <select name="category">
            {% for key, label in categories %}
            <option value="{{ key }}">{{ label }}</option>
            {% endfor %}
          </select>
        </div>
        <div class="field"><label>Passwort</label>
          <input type="password" id="password_add" name="password" required>
        </div>
        <div class="field"><label>Passwort bestätigen</label>
          <input type="password" id="password_confirm_add" name="password_confirm" required>
          <div class="invalid-feedback">Passwörter stimmen nicht überein!</div>
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-close-modal>Abbrechen</button>
        <button type="submit" class="btn btn-primary">Anlegen</button>
      </div>
    </form>
  </div>
</div>
{% endif %}

{% if can_edit %}
<div class="modal-overlay" id="editCredentialModal">
  <div class="modal" style="max-width:380px;">
    <form method="post" onsubmit="return validateCredentialForm(this, 'edit');">
      <input type="hidden" name="edit_credential" value="1">
      <input type="hidden" name="credential_id" id="edit_cred_id">
      <div class="modal-header">
        <h3>Zugangsdaten bearbeiten</h3>
        <button type="button" class="modal-close" data-close-modal>&times;</button>
      </div>
      <div class="modal-body">
        <div class="field"><label>Name</label>
          <input type="text" name="name" id="edit_cred_name" required>
        </div>
        <div class="field"><label>Username</label>
          <input type="text" name="username" id="edit_cred_username" required>
        </div>
        <div class="field"><label>Kategorie</label>
          <select name="category" id="edit_cred_category">
            {% for key, label in categories %}
            <option value="{{ key }}">{{ label }}</option>
            {% endfor %}
          </select>
        </div>
        <div class="field"><label>Neues Passwort</label>
          <input type="password" id="password_edit" name="password" placeholder="Nur bei Änderung ausfüllen">
        </div>
        <div class="field"><label>Passwort bestätigen</label>
          <input type="password" id="password_confirm_edit" name="password_confirm" placeholder="Bestätigen">
          <div class="invalid-feedback">Passwörter stimmen nicht überein!</div>
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-close-modal>Abbrechen</button>
        <button type="submit" class="btn btn-primary">Speichern</button>
      </div>
    </form>
  </div>
</div>
{% endif %}

{% endblock %}

{% block scripts %}
<script>
function openEditCredentialModal(id, name, username, category) {
    document.getElementById("edit_cred_id").value = id;
    document.getElementById("edit_cred_name").value = name;
    document.getElementById("edit_cred_username").value = username;
    document.getElementById("edit_cred_category").value = category;
    document.getElementById("password_edit").value = "";
    document.getElementById("password_confirm_edit").value = "";
    PoeUI.openModal("editCredentialModal");
}

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 validateCredentialForm(form, id) {
    const pass = document.getElementById("password_" + id);
    const confirm = document.getElementById("password_confirm_" + id);
    if (!pass || !confirm) return true;
    if (pass.value || confirm.value || id === "add") {
        if (pass.value !== confirm.value) {
            confirm.classList.add("is-invalid");
            return false;
        }
    }
    confirm.classList.remove("is-invalid");
    return true;
}
</script>
{% endblock %}
