{% extends "base.html" %}
{% block title %}Personen{{ " - " + app_name() }}{% endblock %}

{% block content %}
<div class="page-header">
    <h1>Personen <span style="font-size: 0.9rem; color: var(--kw-text-muted); font-weight: normal;">({{ ergebnis.gesamt }})</span></h1>
    <div class="btn-group">
        <a href="/kontakte/neu" role="button" class="btn-sm">+ Neue Person</a>
        <a href="/kontakte/export?format=csv" role="button" class="btn-sm outline">CSV Export</a>
    </div>
</div>

<!-- Alphabet Filter -->
{% set filter_extra = '' %}
{% if sortierung and sortierung != 'nachname' %}{% set filter_extra = filter_extra + '&sortierung=' + sortierung %}{% endif %}
{% if gruppe_id %}{% set filter_extra = filter_extra + '&gruppe=' + gruppe_id|string %}{% endif %}
{% if q %}{% set filter_extra = filter_extra + '&q=' + q %}{% endif %}
{% if ort_filter %}{% set filter_extra = filter_extra + '&ort=' + ort_filter %}{% endif %}
{% if email_filter %}{% set filter_extra = filter_extra + '&email=' + email_filter %}{% endif %}
{% if position_filter %}{% set filter_extra = filter_extra + '&position=' + position_filter %}{% endif %}
{% if betreuer_filter %}{% set filter_extra = filter_extra + '&betreuer=' + betreuer_filter %}{% endif %}
{% if eigentuemer_filter %}{% set filter_extra = filter_extra + '&eigentuemer=' + eigentuemer_filter %}{% endif %}
{% if org_name_filter %}{% set filter_extra = filter_extra + '&org_name=' + org_name_filter %}{% endif %}
<div class="alpha-filter">
    <a href="/kontakte?{{ filter_extra[1:] if filter_extra else '' }}" class="{% if not buchstabe %}active{% endif %}">Alle</a>
    {% for b in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' %}
    <a href="/kontakte?buchstabe={{ b }}{{ filter_extra }}" class="{% if buchstabe == b %}active{% endif %}">{{ b }}</a>
    {% endfor %}
</div>

{% if ergebnis.kontakte %}
<!-- Spalten-Konfiguration -->
<div style="display: flex; justify-content: flex-end; margin-bottom: 0.5rem;">
    <div class="search-dropdown" style="margin-top: 0;">
        <button type="button" class="search-dropdown-toggle" id="spalten-toggle"
                style="font-size: 0.8rem; padding: 0.3rem 0.6rem;"
                onclick="var menu=this.nextElementSibling; menu.classList.toggle('open');">
            Spalten
        </button>
        <div class="search-dropdown-menu" onclick="event.stopPropagation();" style="max-height: 300px; right: 0; left: auto;">
            {% set spalten_optionen = [
                ('organisation', 'Organisation', true),
                ('ort', 'Ort', true),
                ('email', 'E-Mail', true),
                ('telefon', 'Telefon', true),
                ('mobil', 'Mobil', false),
                ('gruppe', 'Gruppe', true),
                ('position', 'Position', false),
                ('betreuer', 'Betreuer', false),
                ('eigentuemer', 'Eigentümer', false),
                ('erfasst', 'Erfasst', false),
            ] %}
            {% for key, label, default in spalten_optionen %}
            <label class="search-dropdown-item" style="display: flex; align-items: center; gap: 0.4rem; cursor: pointer; user-select: none;">
                <input type="checkbox" class="pers-spalte-cb" data-col="{{ key }}"
                       onchange="togglePersSpalte('{{ key }}', this.checked)"
                       style="margin: 0; width: auto; -webkit-appearance: checkbox; appearance: checkbox;">
                {{ label }}
            </label>
            {% endfor %}
        </div>
    </div>
</div>

<form method="get" action="/kontakte">
    <button type="submit" style="display:none"></button>
    {% if buchstabe %}<input type="hidden" name="buchstabe" value="{{ buchstabe }}">{% endif %}
    <table class="data-table" id="pers-tabelle">
        <thead>
            <tr>
                <th>Name</th>
                <th data-col="organisation">Organisation</th>
                <th data-col="ort">Ort</th>
                <th data-col="email">E-Mail</th>
                <th data-col="telefon">Telefon</th>
                <th data-col="mobil" style="display: none;">Mobil</th>
                <th data-col="gruppe">Gruppe</th>
                <th data-col="position" style="display: none;">Position</th>
                <th data-col="betreuer" style="display: none;">Betreuer</th>
                <th data-col="eigentuemer" style="display: none;">Eigentümer</th>
                <th data-col="erfasst" style="display: none;">Erfasst</th>
            </tr>
            <tr class="tbl-filter-row">
                <td>
                    <div style="display:flex; gap:3px; align-items:center;">
                        <input type="text" name="q" value="{{ q or '' }}" placeholder="Name suchen…" style="flex:1; min-width:80px;">
                        <select name="sortierung" onchange="this.form.submit()" title="Sortierung" style="flex:0 0 auto; width:auto;">
                            <option value="nachname" {% if sortierung == 'nachname' or not sortierung %}selected{% endif %}>A-Z</option>
                            <option value="ort" {% if sortierung == 'ort' %}selected{% endif %}>Ort</option>
                            <option value="aktualisiert" {% if sortierung == 'aktualisiert' %}selected{% endif %}>Datum</option>
                        </select>
                        {% if q or gruppe_id or ort_filter or email_filter or position_filter or betreuer_filter or eigentuemer_filter or org_name_filter %}
                        <a href="/kontakte{% if buchstabe %}?buchstabe={{ buchstabe }}{% endif %}" class="btn-sm outline" style="margin:0; font-size:0.7rem; padding:0.15rem 0.4rem;" title="Zurücksetzen">✕</a>
                        {% endif %}
                    </div>
                </td>
                <td data-col="organisation">
                    <input type="text" name="org_name" value="{{ org_name_filter or '' }}" placeholder="Org…">
                </td>
                <td data-col="ort">
                    <input type="text" name="ort" value="{{ ort_filter or '' }}" placeholder="Ort…">
                </td>
                <td data-col="email">
                    <input type="text" name="email" value="{{ email_filter or '' }}" placeholder="E-Mail…">
                </td>
                <td data-col="telefon"></td>
                <td data-col="mobil" style="display:none;"></td>
                <td data-col="gruppe">
                    <select name="gruppe" onchange="this.form.submit()">
                        <option value="">Alle Gruppen</option>
                        {% for g in gruppen %}
                        <option value="{{ g.id }}" {% if gruppe_id == g.id %}selected{% endif %}>{{ g.name }}</option>
                        {% endfor %}
                    </select>
                </td>
                <td data-col="position" style="display:none;">
                    <input type="text" name="position" value="{{ position_filter or '' }}" placeholder="Position…">
                </td>
                <td data-col="betreuer" style="display:none;">
                    <input type="text" name="betreuer" value="{{ betreuer_filter or '' }}" placeholder="Betreuer…">
                </td>
                <td data-col="eigentuemer" style="display:none;">
                    <input type="text" name="eigentuemer" value="{{ eigentuemer_filter or '' }}" placeholder="Eigentümer…">
                </td>
                <td data-col="erfasst" style="display:none;"></td>
            </tr>
        </thead>
        <tbody>
            {% for kontakt in ergebnis.kontakte %}
            <tr>
                <td style="font-weight: 500;"><a href="/kontakte/{{ kontakt.id }}">{{ kontakt.anzeigename }}</a></td>
                <td data-col="organisation" style="font-size: 0.85rem;">
                    {% set org = org_map.get(kontakt.id) if org_map is defined else none %}
                    {% if org %}<a href="/kontakte/{{ org.id }}">{{ org.anzeigename }}</a>
                    {% elif kontakt.firmenname %}{{ kontakt.firmenname }}
                    {% else %}-{% endif %}
                </td>
                <td data-col="ort" style="font-size: 0.85rem;">{{ kontakt.ort or '-' }}</td>
                <td data-col="email" style="font-size: 0.85rem;">{% if kontakt.email1 %}<a href="mailto:{{ kontakt.email1 }}">{{ kontakt.email1 }}</a>{% else %}-{% endif %}</td>
                <td data-col="telefon" style="font-size: 0.85rem;">{{ kontakt.telefon or kontakt.telefon_direkt or '-' }}</td>
                <td data-col="mobil" style="font-size: 0.85rem; display: none;">{{ kontakt.mobil or '-' }}</td>
                <td data-col="gruppe" style="font-size: 0.85rem;">
                    {% for kg in kontakt.gruppen %}
                    <span class="gruppe-badge" style="background: {{ kg.gruppe.farbe }}">{{ kg.gruppe.name }}</span>
                    {% endfor %}
                </td>
                <td data-col="position" style="font-size: 0.85rem; display: none;">{{ kontakt.position or '-' }}</td>
                <td data-col="betreuer" style="font-size: 0.85rem; display: none;">{{ kontakt.betreuer or '-' }}</td>
                <td data-col="eigentuemer" style="font-size: 0.85rem; display: none;">{{ kontakt.eigentuemer or '-' }}</td>
                <td data-col="erfasst" style="font-size: 0.85rem; display: none;">{{ kontakt.erfasst_am.strftime('%d.%m.%Y') if kontakt.erfasst_am else '-' }}</td>
            </tr>
            {% endfor %}
        </tbody>
    </table>
</form>

{% set extra = '' %}
{% if sortierung and sortierung != 'nachname' %}{% set extra = extra + '&sortierung=' + sortierung %}{% endif %}
{% if gruppe_id %}{% set extra = extra + '&gruppe=' + gruppe_id|string %}{% endif %}
{% if buchstabe %}{% set extra = extra + '&buchstabe=' + buchstabe %}{% endif %}
{% if q %}{% set extra = extra + '&q=' + q %}{% endif %}
{% if ort_filter %}{% set extra = extra + '&ort=' + ort_filter %}{% endif %}
{% if email_filter %}{% set extra = extra + '&email=' + email_filter %}{% endif %}
{% if position_filter %}{% set extra = extra + '&position=' + position_filter %}{% endif %}
{% if betreuer_filter %}{% set extra = extra + '&betreuer=' + betreuer_filter %}{% endif %}
{% if eigentuemer_filter %}{% set extra = extra + '&eigentuemer=' + eigentuemer_filter %}{% endif %}
{% if org_name_filter %}{% set extra = extra + '&org_name=' + org_name_filter %}{% endif %}
{% with seite=ergebnis.seite, seiten=ergebnis.seiten, base_url='/kontakte', extra_params=extra %}
{% include "components/pagination.html" %}
{% endwith %}

<script>
var PERS_SPALTEN_DEFAULT = ['organisation', 'ort', 'email', 'telefon', 'gruppe'];

function getPersSpalten() {
    try {
        var gespeichert = localStorage.getItem('pers_spalten');
        if (gespeichert) return JSON.parse(gespeichert);
    } catch(e) {}
    return PERS_SPALTEN_DEFAULT;
}

function savePersSpalten(spalten) {
    try { localStorage.setItem('pers_spalten', JSON.stringify(spalten)); } catch(e) {}
}

function togglePersSpalte(col, visible) {
    document.querySelectorAll('[data-col="' + col + '"]').forEach(function(el) {
        el.style.display = visible ? '' : 'none';
    });
    var spalten = getPersSpalten();
    if (visible && spalten.indexOf(col) < 0) spalten.push(col);
    else if (!visible) spalten = spalten.filter(function(s) { return s !== col; });
    savePersSpalten(spalten);
}

document.addEventListener('DOMContentLoaded', function() {
    var aktive = getPersSpalten();
    document.querySelectorAll('.pers-spalte-cb').forEach(function(cb) {
        var col = cb.dataset.col;
        var sichtbar = aktive.indexOf(col) >= 0;
        cb.checked = sichtbar;
        document.querySelectorAll('[data-col="' + col + '"]').forEach(function(el) {
            el.style.display = sichtbar ? '' : 'none';
        });
    });
});
</script>

{% else %}
<div class="empty-state">
    <div class="empty-state-icon">&#x1F464;</div>
    <p>Keine Personen gefunden.</p>
    <a href="/kontakte/neu" role="button" class="btn-sm">Erste Person anlegen</a>
</div>
{% endif %}
{% endblock %}
