{% extends "base.html" %}

{% block title %}MeinAntrag{% endblock %}

{% block content %}
<section id="hero-spot" class="hero-spot">
    <h1>MeinAntrag</h1>
    <h2>Erstelle einfach Vorlagen für Anfragen oder Anträge an die Karlsruher Stadtverwaltung zu deinem persönlichen Thema und schicke diese direkt an eine Stadtratsfraktion!</h2>
</section>

<section id="tutorial" class="tutorial">

  <ul id="project-site" class="tutorial-list wrapper active">
    <li class="question">

        <form id="meinantragForm">
            <div id="inputFields">
                <li>
                    <h4>Fraktion auswählen</h4>
                    <p>Wähle die Fraktion, an die der Antrag gerichtet ist:</p>
                    <select class="form-select" id="party" name="party_id" required>
                        <option value="">Fraktion auswählen...</option>
                        <option value="SPD">SPD</option>
                        <option value="GRÜNEN">GRÜNEN</option>
                        <option value="CDU">CDU</option>
                        <option value="FDP/FW">FDP/FW</option>
                        <option value="Volt">Volt</option>
                        <option value="DIE LINKE">DIE LINKE</option>
                        <option value="KAL">KAL</option>
                    </select>
                </li>
                
                <li>
                    <h4>Dein Anliegen beschreiben</h4>
                    <p>Beschreibe hier, welche Anfrage oder Antrag du an die Stadtverwaltung stellen möchtest:</p>
                    <textarea class="form-control" id="anliegen" name="anliegen" rows="5" required></textarea>
                </li>
                
                <li>
                    <button type="submit" class="btn btn-primary">
                        <span class="btn-text">Antrag generieren</span>
                        <span class="loading" role="status" style="display: none;">...</span>
                    </button>
                </li>
            </div>
            
            <div id="resultFields" style="display: none;">
                <li>
                    <p><a href="#" id="backLink">← Zurück zum Formular</a></p>
		    <br><br>
                </li>
                
                <li>
                    <h4>Antragstitel</h4>
                    <p></p>
                    <input type="text" class="form-control" id="antragstitel" name="antragstitel">
                </li>
                
                <li>
                    <h4>Forderung</h4>
                    <p></p>
                    <textarea class="form-control" id="forderung" name="forderung" rows="5"></textarea>
                </li>
                
                <li>
                    <h4>Begründung/Sachverhalt</h4>
                    <p></p>
                    <textarea class="form-control" id="begruendung" name="begruendung" rows="8"></textarea>
                </li>
                
                <li>
                    <h4>Aktionen</h4>
                    <p>Du kannst den Antrag jetzt per E-Mail senden oder als Word-Datei herunterladen:</p>
                    <button type="button" class="btn btn-primary" id="mailBtn">
                        <span id="mailBtnText">Mail an Fraktion senden</span>
                    </button>
                    <button type="button" class="btn btn-primary" id="wordBtn">
                        Word-Datei herunterladen
                    </button>
                </li>
            </div>
        </form>


      </p>
    </li>
  </ul>

</section>
{% endblock %}

{% block extra_js %}
<script>
    $(document).ready(function() {
        // Handle form submission (client-side)
        $('#meinantragForm').on('submit', function(e) {
            e.preventDefault();

            const partyId = $('#party').val() || '';
            const anliegen = $('#anliegen').val() || '';

            if (!anliegen.trim()) {
                alert('Bitte geben Sie ein Anliegen ein.');
                return;
            }

            // Show loading state
            const $button = $(this).find('button[type="submit"]');
            const $btnText = $button.find('.btn-text');
            const $loading = $button.find('.loading');
            $button.prop('disabled', true);
            $btnText.text('Generiere Antrag');
            $loading.css('display', 'inline');

            // Prepare form data as URL-encoded
            const formData = new URLSearchParams();
            formData.append('anliegen', anliegen);
            if (partyId) {
                formData.append('party_id', partyId);
            }

            // Send request to generate text
            fetch('/api/generate-antrag', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                },
                body: formData.toString()
            })
            .then(response => {
                if (!response.ok) {
                    return response.json().then(err => {
                        throw new Error(err.error || 'Fehler beim Generieren des Antrags');
                    });
                }
                return response.json();
            })
            .then(data => {
                if (data.success) {
                    // Fill in the result fields
                    $('#antragstitel').val(data.title || '');
                    $('#forderung').val(data.demand || '');
                    $('#begruendung').val(data.justification || '');
                    
                    // Store party name and email body for mail button
                    $('#resultFields').data('party-name', data.party_name || '');
                    $('#resultFields').data('email-body', data.email_body || '');
                    
                    // Update mail button text
                    if (data.party_name) {
                        $('#mailBtnText').text('Mail an ' + data.party_name + ' senden');
                    }
                    
                    // Hide input fields and show result fields
                    $('#inputFields').hide();
                    $('#resultFields').show();
                } else {
                    throw new Error(data.error || 'Fehler beim Generieren des Antrags');
                }

                // Reset button state
                $button.prop('disabled', false);
                $btnText.text('Antrag generieren');
                $loading.css('display', 'none');
            })
            .catch(error => {
                console.error('Error:', error);
                alert('Fehler beim Generieren des Antrags: ' + error.message);
                
                // Reset button state
                $button.prop('disabled', false);
                $btnText.text('Antrag generieren');
                $loading.css('display', 'none');
            });
        });

        // Handle back link click
        $('#backLink').on('click', function(e) {
            e.preventDefault();
            $('#resultFields').hide();
            $('#inputFields').show();
        });

        // Mail-Kontakte für Fraktionen
        const partyContacts = {
            'SPD': 'spd@karlsruhe.de',
            'GRÜNEN': 'gruene@karlsruhe.de',
            'CDU': 'cdu@karlsruhe.de',
            'FDP/FW': 'fdp@karlsruhe.de',
            'Volt': 'volt@karlsruhe.de',
            'DIE LINKE': 'dielinke@karlsruhe.de',
            'KAL': 'kal@karlsruhe.de'
        };

        // Handle mail button click
        $('#mailBtn').on('click', function() {
            const partyName = $('#resultFields').data('party-name') || '';
            const email = partyContacts[partyName] || '';
            const subject = encodeURIComponent($('#antragstitel').val() || '');
            const emailBody = $('#resultFields').data('email-body') || '';
            
            const bodyEncoded = encodeURIComponent(emailBody);
            
            // Open mail client
            if (email) {
                window.location.href = `mailto:${email}?subject=${subject}&body=${bodyEncoded}`;
            } else {
                alert('Keine E-Mail-Adresse für diese Fraktion hinterlegt.');
            }
        });

        // Function to create a valid filename from title
        function createFilename(title) {
            if (!title || !title.trim()) {
                return 'antrag.docx';
            }
            
            // Remove or replace special characters
            let filename = title
                .trim()
                .toLowerCase()
                .replace(/[ä]/g, 'ae')
                .replace(/[ö]/g, 'oe')
                .replace(/[ü]/g, 'ue')
                .replace(/[ß]/g, 'ss')
                .replace(/[^a-z0-9\s-]/g, '') // Remove special chars except spaces and hyphens
                .replace(/\s+/g, '_') // Replace spaces with underscores
                .replace(/_+/g, '_') // Replace multiple underscores with single
                .replace(/^_+|_+$/g, ''); // Remove leading/trailing underscores
            
            // Limit length to 100 characters
            if (filename.length > 100) {
                filename = filename.substring(0, 100);
            }
            
            // If empty after cleaning, use default
            if (!filename) {
                return 'antrag.docx';
            }
            
            return filename + '.docx';
        }

        // Handle Word button click
        $('#wordBtn').on('click', function() {
            const title = $('#antragstitel').val() || '';
            const demand = $('#forderung').val() || '';
            const justification = $('#begruendung').val() || '';
            const partyName = $('#resultFields').data('party-name') || '';
            
            // Prepare form data
            const formData = new URLSearchParams();
            formData.append('title', title);
            formData.append('demand', demand);
            formData.append('justification', justification);
            if (partyName) {
                formData.append('party_name', partyName);
            }
            
            // Generate filename from title
            const filename = createFilename(title);
            
            // Download Word file
            fetch('/api/generate-word', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                },
                body: formData.toString()
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error('Fehler beim Generieren der Word-Datei');
                }
                return response.blob();
            })
            .then(blob => {
                const url = window.URL.createObjectURL(blob);
                const a = document.createElement('a');
                a.href = url;
                a.download = filename;
                document.body.appendChild(a);
                a.click();
                window.URL.revokeObjectURL(url);
                document.body.removeChild(a);
            })
            .catch(error => {
                console.error('Error:', error);
                alert('Fehler beim Generieren der Word-Datei: ' + error.message);
            });
        });
    });
</script>
{% endblock %} 
