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

{% block content %}
<div class="page-header">
    <h1>Organisationen <span style="font-size: 0.9rem; color: var(--kw-text-muted); font-weight: normal;">({{ ergebnis.gesamt }})</span></h1>
    <div class="btn-group">
        <a href="/organisationen/neu" role="button" class="btn-sm">+ Neue Organisation</a>
    </div>
</div>

<!-- Alphabet Filter -->
{% set org_filter_extra = '' %}
{% if q %}{% set org_filter_extra = org_filter_extra + '&q=' + q %}{% endif %}
{% if ort_filter %}{% set org_filter_extra = org_filter_extra + '&ort=' + ort_filter %}{% endif %}
{% if email_filter %}{% set org_filter_extra = org_filter_extra + '&email=' + email_filter %}{% endif %}
{% if plz_filter %}{% set org_filter_extra = org_filter_extra + '&plz=' + plz_filter %}{% endif %}
{% if betreuer_filter %}{% set org_filter_extra = org_filter_extra + '&betreuer=' + betreuer_filter %}{% endif %}
{% if eigentuemer_filter %}{% set org_filter_extra = org_filter_extra + '&eigentuemer=' + eigentuemer_filter %}{% endif %}
{% if gruppe_id %}{% set org_filter_extra = org_filter_extra + '&gruppe=' + gruppe_id|string %}{% endif %}
<div class="alpha-filter">
    <a href="/organisationen{% if org_filter_extra %}?{{ org_filter_extra[1:] }}{% endif %}" class="{% if not buchstabe %}active{% endif %}">Alle</a>
    {% for b in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' %}
    <a href="/organisationen?buchstabe={{ b }}{{ org_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 = [
                ('ort', 'Ort', true),
                ('email', 'E-Mail', true),
                ('telefon', 'Telefon', true),
                ('gruppe', 'Gruppe', false),
                ('plz', 'PLZ', false),
                ('webseite', 'Webseite', 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="org-spalte-cb" data-col="{{ key }}"
                       onchange="toggleOrgSpalte('{{ key }}', this.checked)"
                       style="margin: 0; width: auto; -webkit-appearance: checkbox; appearance: checkbox;">
                {{ label }}
            </label>
            {% endfor %}
        </div>
    </div>
</div>

<form method="get" action="/organisationen">
    <button type="submit" style="display:none"></button>
    {% if buchstabe %}<input type="hidden" name="buchstabe" value="{{ buchstabe }}">{% endif %}
    <table class="data-table" id="org-tabelle">
        <thead>
            <tr>
                <th style="width: 1.5rem;"></th>
                <th>Name</th>
                <th data-col="ort">Ort</th>
                <th data-col="email">E-Mail</th>
                <th data-col="telefon">Telefon</th>
                <th data-col="gruppe" style="display: none;">Gruppe</th>
                <th data-col="plz" style="display: none;">PLZ</th>
                <th data-col="webseite" style="display: none;">Webseite</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></td>
                <td>
                    <div style="display:flex; gap:3px; align-items:center;">
                        <input type="text" name="q" value="{{ q }}" placeholder="Name suchen…" style="flex:1; min-width:80px;">
                        {% if q or ort_filter or email_filter or plz_filter or betreuer_filter or eigentuemer_filter or gruppe_id %}
                        <a href="/organisationen{% 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="ort">
                    <input type="text" name="ort" value="{{ ort_filter }}" 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="gruppe" style="display:none;">
                    <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="plz" style="display:none;">
                    <input type="text" name="plz" value="{{ plz_filter or '' }}" placeholder="PLZ…">
                </td>
                <td data-col="webseite" style="display:none;"></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 %}
            {% set mitarbeiter = mitarbeiter_pro_org.get(kontakt.id, []) %}
            <!-- Org-Zeile -->
            <tr class="org-header" data-org-id="{{ kontakt.id }}" style="background: var(--kw-org-bg);">
                <td style="text-align: center; padding: 0.4rem;">
                    {% if mitarbeiter %}
                    <button type="button" id="toggle-{{ kontakt.id }}"
                            onclick="toggleOrg({{ kontakt.id }})"
                            style="padding: 0; font-size: 0.65rem; border: none; cursor: pointer; color: var(--kw-text-muted); background: none;"
                            title="Mitarbeiter ein-/ausblenden">&#x25B6;</button>
                    {% endif %}
                </td>
                <td style="font-weight: 600;">
                    <a href="/kontakte/{{ kontakt.id }}">{{ kontakt.anzeigename }}</a>
                    {% if mitarbeiter %}
                    <span style="font-size: 0.75rem; color: var(--kw-text-muted); font-weight: 400;">({{ mitarbeiter|length }} MA)</span>
                    {% 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 '-' }}</td>
                <td data-col="gruppe" style="font-size: 0.85rem; display: none;">
                    {% for kg in kontakt.gruppen %}<span class="gruppe-badge" style="background: {{ kg.gruppe.farbe }}">{{ kg.gruppe.name }}</span>{% endfor %}
                    {% if not kontakt.gruppen %}-{% endif %}
                </td>
                <td data-col="plz" style="font-size: 0.85rem; display: none;">{{ kontakt.plz or '-' }}</td>
                <td data-col="webseite" style="font-size: 0.85rem; display: none;">{% if kontakt.webseite %}<a href="{{ kontakt.webseite }}" target="_blank">{{ kontakt.webseite }}</a>{% else %}-{% endif %}</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>
            <!-- Mitarbeiter-Zeilen (standardmäßig eingeklappt) -->
            {% for ma in mitarbeiter %}
            <tr class="ma-row ma-of-{{ kontakt.id }}" style="display: none;">
                <td></td>
                <td style="padding-left: 2rem; font-size: 0.85rem;">
                    &#x1F464;
                    <a href="/kontakte/{{ ma.kontakt.id }}">{{ ma.kontakt.anzeigename }}</a>
                    {% if ma.rolle %}<span style="font-size: 0.75rem; color: var(--kw-text-muted);">· {{ ma.rolle }}</span>{% endif %}
                </td>
                <td data-col="ort" style="font-size: 0.85rem;">{{ ma.kontakt.ort or '-' }}</td>
                <td data-col="email" style="font-size: 0.85rem;">{% if ma.kontakt.email1 %}<a href="mailto:{{ ma.kontakt.email1 }}">{{ ma.kontakt.email1 }}</a>{% else %}-{% endif %}</td>
                <td data-col="telefon" style="font-size: 0.85rem;">{{ ma.kontakt.telefon or ma.kontakt.mobil or ma.kontakt.telefon_direkt or '-' }}</td>
                <td data-col="gruppe" style="font-size: 0.85rem; display: none;">
                    {% for kg in ma.kontakt.gruppen %}<span class="gruppe-badge" style="background: {{ kg.gruppe.farbe }}">{{ kg.gruppe.name }}</span>{% endfor %}
                    {% if not ma.kontakt.gruppen %}-{% endif %}
                </td>
                <td data-col="plz" style="font-size: 0.85rem; display: none;">{{ ma.kontakt.plz or '-' }}</td>
                <td data-col="webseite" style="font-size: 0.85rem; display: none;">{% if ma.kontakt.webseite %}<a href="{{ ma.kontakt.webseite }}" target="_blank">{{ ma.kontakt.webseite }}</a>{% else %}-{% endif %}</td>
                <td data-col="betreuer" style="font-size: 0.85rem; display: none;">{{ ma.kontakt.betreuer or '-' }}</td>
                <td data-col="eigentuemer" style="font-size: 0.85rem; display: none;">{{ ma.kontakt.eigentuemer or '-' }}</td>
                <td data-col="erfasst" style="font-size: 0.85rem; display: none;"></td>
            </tr>
            {% endfor %}
            {% endfor %}
        </tbody>
    </table>
</form>

{% set extra = '' %}
{% 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 plz_filter %}{% set extra = extra + '&plz=' + plz_filter %}{% endif %}
{% if betreuer_filter %}{% set extra = extra + '&betreuer=' + betreuer_filter %}{% endif %}
{% if eigentuemer_filter %}{% set extra = extra + '&eigentuemer=' + eigentuemer_filter %}{% endif %}
{% if gruppe_id %}{% set extra = extra + '&gruppe=' + gruppe_id|string %}{% endif %}
{% if buchstabe %}{% set extra = extra + '&buchstabe=' + buchstabe %}{% endif %}
{% with seite=ergebnis.seite, seiten=ergebnis.seiten, base_url='/organisationen', extra_params=extra %}
{% include "components/pagination.html" %}
{% endwith %}

<script>
var ORG_SPALTEN_DEFAULT = ['ort', 'email', 'telefon'];

function getOrgSpalten() {
    try {
        var gespeichert = localStorage.getItem('org_spalten');
        if (gespeichert) return JSON.parse(gespeichert);
    } catch(e) {}
    return ORG_SPALTEN_DEFAULT;
}

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

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

function setOrgExpanded(orgId, expanded) {
    document.querySelectorAll('.ma-of-' + orgId).forEach(function(r) {
        r.style.display = expanded ? '' : 'none';
    });
    var btn = document.getElementById('toggle-' + orgId);
    if (btn) btn.innerHTML = expanded ? '&#x25BC;' : '&#x25B6;';
}

function toggleOrg(orgId) {
    var first = document.querySelector('.ma-of-' + orgId);
    setOrgExpanded(orgId, first && first.style.display === 'none');
}

document.addEventListener('DOMContentLoaded', function() {
    var aktive = getOrgSpalten();
    document.querySelectorAll('.org-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">&#x1F3E2;</div>
    <p>Keine Organisationen gefunden.</p>
    <a href="/organisationen/neu" role="button" class="btn-sm">Erste Organisation anlegen</a>
</div>
{% endif %}
{% endblock %}
