{% extends 'base.html' %}
{% load help_tags %}
{% block title %}{{ title }}{% endblock %}
{% block content %}
<nav aria-label="breadcrumb">
  <ol class="breadcrumb">
    <li class="breadcrumb-item"><a href="{% url 'stiftung:dashboard' %}">Dashboard</a></li>
    <li class="breadcrumb-item"><a href="{% url 'stiftung:unterstuetzungen_all' %}">Unterstützungen</a></li>
    <li class="breadcrumb-item active" aria-current="page">{{ title }}</li>
  </ol>
</nav>

<div class="row">
  <div class="col-lg-8">
    <div class="card shadow">
      <div class="card-header bg-primary text-white">
        <h5 class="mb-0">{{ title }}</h5>
      </div>
      <div class="card-body">
        <form method="post">
          {% csrf_token %}
          
          <!-- Basic Information -->
          <div class="row mb-4">
            <div class="col-md-6 mb-3">
              <label class="form-label" for="{{ form.destinataer.id_for_label }}">{{ form.destinataer.label }}</label>
              {{ form.destinataer }}
              {% if form.destinataer.errors %}
                <div class="text-danger">{{ form.destinataer.errors }}</div>
              {% endif %}
            </div>
            <div class="col-md-6 mb-3">
              <label class="form-label" for="{{ form.konto.id_for_label }}">{{ form.konto.label }}</label>
              {{ form.konto }}
              {% if form.konto.errors %}
                <div class="text-danger">{{ form.konto.errors }}</div>
              {% endif %}
            </div>
          </div>

          <!-- Payment Details -->
          <div class="row mb-4">
            <div class="col-md-3 mb-3">
              <label class="form-label" for="{{ form.betrag.id_for_label }}">{{ form.betrag.label }}</label>
              {{ form.betrag }}
              {% if form.betrag.errors %}
                <div class="text-danger">{{ form.betrag.errors }}</div>
              {% endif %}
            </div>
            <div class="col-md-3 mb-3">
              <label class="form-label" for="{{ form.faellig_am.id_for_label }}">{{ form.faellig_am.label }}</label>
              {{ form.faellig_am }}
              {% if form.faellig_am.errors %}
                <div class="text-danger">{{ form.faellig_am.errors }}</div>
              {% endif %}
            </div>
            <div class="col-md-3 mb-3">
              <label class="form-label" for="{{ form.status.id_for_label }}">{{ form.status.label }}</label>
              {{ form.status }}
              {% if form.status.errors %}
                <div class="text-danger">{{ form.status.errors }}</div>
              {% endif %}
            </div>
            <div class="col-md-3 mb-3">
              <div class="form-check mt-4">
                {{ form.ist_wiederkehrend }}
                <label class="form-check-label" for="{{ form.ist_wiederkehrend.id_for_label }}">
                  {{ form.ist_wiederkehrend.label }}
                </label>
                {% if form.ist_wiederkehrend.help_text %}
                  <div class="form-text">{{ form.ist_wiederkehrend.help_text }}</div>
                {% endif %}
              </div>
            </div>
          </div>

          <!-- Recurring Payment Settings (initially hidden) -->
          <div id="recurring-fields" style="display: none;" class="mb-4">
            <div class="alert alert-info">
              <i class="fas fa-info-circle me-2"></i>
              <strong>Wiederkehrende Zahlung:</strong> Diese Einstellungen werden nur für automatisch wiederkehrende Zahlungen verwendet.
            </div>
            <div class="row">
              <div class="col-md-6 mb-3">
                <label class="form-label" for="{{ form.intervall.id_for_label }}">{{ form.intervall.label }}</label>
                {{ form.intervall }}
                {% if form.intervall.errors %}
                  <div class="text-danger">{{ form.intervall.errors }}</div>
                {% endif %}
              </div>
              <div class="col-md-6 mb-3">
                <label class="form-label" for="{{ form.letzte_zahlung_am.id_for_label }}">{{ form.letzte_zahlung_am.label }}</label>
                {{ form.letzte_zahlung_am }}
                {% if form.letzte_zahlung_am.help_text %}
                  <div class="form-text">{{ form.letzte_zahlung_am.help_text }}</div>
                {% endif %}
                {% if form.letzte_zahlung_am.errors %}
                  <div class="text-danger">{{ form.letzte_zahlung_am.errors }}</div>
                {% endif %}
              </div>
            </div>
          </div>

          <!-- Bank Transfer Information -->
          <h6 class="text-muted mb-3"><i class="fas fa-university me-2"></i>Überweisungsdaten</h6>
          <div class="row mb-4">
            <div class="col-md-6 mb-3">
              <label class="form-label" for="{{ form.empfaenger_iban.id_for_label }}">{{ form.empfaenger_iban.label }}</label>
              {{ form.empfaenger_iban }}
              {% if form.empfaenger_iban.errors %}
                <div class="text-danger">{{ form.empfaenger_iban.errors }}</div>
              {% endif %}
            </div>
            <div class="col-md-6 mb-3">
              <label class="form-label" for="{{ form.empfaenger_name.id_for_label }}">{{ form.empfaenger_name.label }}</label>
              {{ form.empfaenger_name }}
              {% if form.empfaenger_name.errors %}
                <div class="text-danger">{{ form.empfaenger_name.errors }}</div>
              {% endif %}
            </div>
          </div>

          <div class="row mb-4">
            <div class="col-md-8 mb-3">
              <label class="form-label" for="{{ form.verwendungszweck.id_for_label }}">{{ form.verwendungszweck.label }}</label>
              {{ form.verwendungszweck }}
              {% if form.verwendungszweck.errors %}
                <div class="text-danger">{{ form.verwendungszweck.errors }}</div>
              {% endif %}
            </div>
            <div class="col-md-4 mb-3">
              <label class="form-label" for="{{ form.beschreibung.id_for_label }}">{{ form.beschreibung.label }}</label>
              {{ form.beschreibung }}
              {% if form.beschreibung.errors %}
                <div class="text-danger">{{ form.beschreibung.errors }}</div>
              {% endif %}
            </div>
          </div>

          <div class="d-flex justify-content-between">
            <a href="{% url 'stiftung:unterstuetzungen_all' %}" class="btn btn-secondary">
              <i class="fas fa-arrow-left me-2"></i>Zurück
            </a>
            <button type="submit" class="btn btn-primary">
              <i class="fas fa-save me-2"></i>Speichern
            </button>
          </div>
        </form>
      </div>
    </div>
  </div>
  
  <!-- Sidebar mit Hilfe -->
  <div class="col-lg-4">
    {% help_box 'unterstuetzung_new' user %}
  </div>
</div>

<script>
function toggleRecurringFields() {
    const recurringCheckbox = document.getElementById('{{ form.ist_wiederkehrend.id_for_label }}');
    const recurringFields = document.getElementById('recurring-fields');
    const intervalField = document.getElementById('{{ form.intervall.id_for_label }}');
    
    console.log('toggleRecurringFields called', {
        checkbox: !!recurringCheckbox,
        checked: recurringCheckbox ? recurringCheckbox.checked : 'N/A',
        fieldsDiv: !!recurringFields,
        intervalField: !!intervalField
    });
    
    if (recurringCheckbox && recurringFields) {
        if (recurringCheckbox.checked) {
            recurringFields.style.display = 'block';
            if (intervalField) {
                intervalField.required = true;
            }
            console.log('Showing recurring fields');
        } else {
            recurringFields.style.display = 'none';
            if (intervalField) {
                intervalField.required = false;
                intervalField.value = '';
            }
            console.log('Hiding recurring fields');
        }
    } else {
        console.error('Could not find required elements for recurring fields toggle');
    }
}

function updateDestinataerInfo() {
    const destinataerSelect = document.getElementById('{{ form.destinataer.id_for_label }}');
    const ibanField = document.getElementById('{{ form.empfaenger_iban.id_for_label }}');
    const nameField = document.getElementById('{{ form.empfaenger_name.id_for_label }}');
    
    if (destinataerSelect.value) {
        // Fetch IBAN and name information via AJAX
        fetch(`/api/destinataer/${destinataerSelect.value}/info/`, {
            method: 'GET',
            headers: {
                'X-Requested-With': 'XMLHttpRequest',
                'X-CSRFToken': document.querySelector('[name=csrfmiddlewaretoken]').value
            },
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                // Update IBAN field if it's empty
                if (!ibanField.value && data.iban) {
                    ibanField.value = data.iban;
                }
                // Update name field if it's empty
                if (!nameField.value && data.name) {
                    nameField.value = data.name;
                }
            } else {
                console.error('Error fetching destinataer info:', data.error);
            }
        })
        .catch(error => {
            console.error('Error:', error);
        });
    } else {
        // Clear fields when no destinataer is selected
        if (!ibanField.value) ibanField.value = '';
        if (!nameField.value) nameField.value = '';
    }
}

// Initialize the form
document.addEventListener('DOMContentLoaded', function() {
    console.log('Initializing form...');
    
    // Get form elements
    const destinataerSelect = document.getElementById('{{ form.destinataer.id_for_label }}');
    const recurringCheckbox = document.getElementById('{{ form.ist_wiederkehrend.id_for_label }}');
    const recurringFields = document.getElementById('recurring-fields');
    const intervalField = document.getElementById('{{ form.intervall.id_for_label }}');
    
    console.log('Form elements found:', {
        destinataerSelect: !!destinataerSelect,
        recurringCheckbox: !!recurringCheckbox,
        recurringFields: !!recurringFields,
        intervalField: !!intervalField
    });
    
    // Add event listeners
    if (destinataerSelect) {
        destinataerSelect.addEventListener('change', updateDestinataerInfo);
    }
    
    if (recurringCheckbox) {
        recurringCheckbox.addEventListener('change', function() {
            console.log('Recurring checkbox changed:', this.checked);
            toggleRecurringFields();
        });
        
        // Initialize state
        toggleRecurringFields();
    }
});
</script>
{% endblock %}

