{% extends "base.html" %}

{% block title %}Lead-Verwaltung - Institutionen{% endblock %}

{% block content %}
<div class="container-fluid">
    <div class="row mb-4">
        <div class="col-md-8">
            <h1 class="h2 mb-0">
                <i class="bi bi-building"></i> Lead-Institutionen
            </h1>
        </div>
        <div class="col-md-4 text-end">
            <button class="btn btn-primary" onclick="showCreateInstitutionModal()">
                <i class="bi bi-plus-circle"></i> Neue Institution
            </button>
            <a href="{{ url_for('leads.all_contacts') }}" class="btn btn-outline-primary">
                <i class="bi bi-people"></i> Alle Kontakte
            </a>
            <a href="{{ url_for('customers.customers_licenses') }}" class="btn btn-secondary">
                <i class="bi bi-arrow-left"></i> Zurück zu Kunden
            </a>
        </div>
    </div>

    <!-- Search Bar -->
    <div class="row mb-4">
        <div class="col-md-6">
            <div class="input-group">
                <span class="input-group-text"><i class="bi bi-search"></i></span>
                <input type="text" class="form-control" id="searchInput" 
                       placeholder="Institution suchen..." onkeyup="filterInstitutions()">
            </div>
        </div>
        <div class="col-md-6 text-end">
            <a href="{{ url_for('leads.export_leads', format='excel') }}" class="btn btn-outline-success">
                <i class="bi bi-file-excel"></i> Excel Export
            </a>
            <a href="{{ url_for('leads.export_leads', format='csv') }}" class="btn btn-outline-info">
                <i class="bi bi-file-text"></i> CSV Export
            </a>
        </div>
    </div>

    <!-- Institutions Table -->
    <div class="card">
        <div class="card-body">
            <div class="table-responsive">
                <table class="table table-hover" id="institutionsTable">
                    <thead>
                        <tr>
                            <th>Institution</th>
                            <th>Anzahl Kontakte</th>
                            <th>Erstellt am</th>
                            <th>Erstellt von</th>
                            <th>Aktionen</th>
                        </tr>
                    </thead>
                    <tbody>
                        {% for institution in institutions %}
                        <tr>
                            <td>
                                <a href="{{ url_for('leads.institution_detail', institution_id=institution.id) }}" 
                                   class="text-decoration-none">
                                    <strong>{{ institution.name }}</strong>
                                </a>
                            </td>
                            <td>
                                <span class="badge bg-secondary">{{ institution.contact_count }}</span>
                            </td>
                            <td>{{ institution.created_at.strftime('%d.%m.%Y') }}</td>
                            <td>{{ institution.created_by or '-' }}</td>
                            <td>
                                <a href="{{ url_for('leads.institution_detail', institution_id=institution.id) }}" 
                                   class="btn btn-sm btn-outline-primary">
                                    <i class="bi bi-eye"></i> Details
                                </a>
                                <button class="btn btn-sm btn-outline-secondary" 
                                        onclick="editInstitution('{{ institution.id }}', '{{ institution.name }}')">
                                    <i class="bi bi-pencil"></i>
                                </button>
                            </td>
                        </tr>
                        {% endfor %}
                    </tbody>
                </table>
                {% if not institutions %}
                <div class="text-center py-4">
                    <p class="text-muted">Noch keine Institutionen vorhanden.</p>
                    <button class="btn btn-primary" onclick="showCreateInstitutionModal()">
                        <i class="bi bi-plus-circle"></i> Erste Institution anlegen
                    </button>
                </div>
                {% endif %}
            </div>
        </div>
    </div>
</div>

<!-- Create/Edit Institution Modal -->
<div class="modal fade" id="institutionModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="institutionModalTitle">Neue Institution</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form id="institutionForm">
                    <input type="hidden" id="institutionId">
                    <div class="mb-3">
                        <label for="institutionName" class="form-label">Name der Institution</label>
                        <input type="text" class="form-control" id="institutionName" required>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Abbrechen</button>
                <button type="button" class="btn btn-primary" onclick="saveInstitution()">Speichern</button>
            </div>
        </div>
    </div>
</div>

<script>
// Filter institutions
function filterInstitutions() {
    const searchTerm = document.getElementById('searchInput').value.toLowerCase();
    const rows = document.querySelectorAll('#institutionsTable tbody tr');
    
    rows.forEach(row => {
        const text = row.textContent.toLowerCase();
        row.style.display = text.includes(searchTerm) ? '' : 'none';
    });
}

// Show create institution modal
function showCreateInstitutionModal() {
    document.getElementById('institutionModalTitle').textContent = 'Neue Institution';
    document.getElementById('institutionId').value = '';
    document.getElementById('institutionName').value = '';
    new bootstrap.Modal(document.getElementById('institutionModal')).show();
}

// Edit institution
function editInstitution(id, name) {
    document.getElementById('institutionModalTitle').textContent = 'Institution bearbeiten';
    document.getElementById('institutionId').value = id;
    document.getElementById('institutionName').value = name;
    new bootstrap.Modal(document.getElementById('institutionModal')).show();
}

// Save institution
async function saveInstitution() {
    const id = document.getElementById('institutionId').value;
    const name = document.getElementById('institutionName').value.trim();
    
    if (!name) {
        alert('Bitte geben Sie einen Namen ein.');
        return;
    }
    
    try {
        const url = id 
            ? `/leads/api/institutions/${id}`
            : '/leads/api/institutions';
        const method = id ? 'PUT' : 'POST';
        
        const response = await fetch(url, {
            method: method,
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({ name: name })
        });
        
        const data = await response.json();
        
        if (data.success) {
            location.reload();
        } else {
            alert('Fehler: ' + (data.error || 'Unbekannter Fehler'));
        }
    } catch (error) {
        alert('Fehler beim Speichern: ' + error.message);
    }
}
</script>
{% endblock %}