{% extends "base.html" %}
{% block content %}
<div class="level">
    <div class="level-left"><h1 class="title is-3">Verträge</h1></div>
    <div class="level-right">
        <a class="button is-primary" href="{{ url_for('contracts.neu') }}">+ Neuer Vertrag</a>
    </div>
</div>

<div class="box">
    {% if contracts %}
    <table class="table is-fullwidth is-hoverable is-striped" id="contracts-table">
        <thead>
            <tr>
                <th>Vertrag</th>
                <th>Belegnummer</th>
                <th>Beleg-Datum</th>
                <th>Laufzeit</th>
                <th>Status</th>
                <th>Aktion</th>
            </tr>
        </thead>
        <tbody>
            {% for c in contracts %}
            <tr id="contract-row-{{ c.id }}">
                <td><strong>{{ c.name }}</strong></td>
                <td><code>{{ c.belegnummer or '–' }}</code></td>
                <td>{{ c.beleg_datum.strftime('%d.%m.%Y') if c.beleg_datum else '–' }}</td>
                <td>
                    {{ c.laufzeit_start.strftime('%d.%m.%Y') if c.laufzeit_start else '?' }}
                    – {{ c.laufzeit_ende.strftime('%d.%m.%Y') if c.laufzeit_ende else '?' }}
                </td>
                <td>
                    <span class="tag {{ 'is-success' if c.status == 'Angenommen' else 'is-warning' if c.status == 'Zur Prüfung' else 'is-light' }}">
                        {{ c.status }}
                    </span>
                </td>
                <td>
                    <a class="button is-small is-link" href="{{ url_for('contracts.detail', contract_id=c.id) }}">Öffnen</a>
                    <button class="button is-small is-light" onclick="openEditModal({{ c.id }})" title="Bearbeiten">✏️</button>
                </td>
            </tr>
            {% endfor %}
        </tbody>
    </table>
    {% else %}
    <p class="has-text-centered has-text-grey is-size-5">Noch keine Verträge angelegt.</p>
    {% endif %}
</div>

<!-- Edit Modal -->
<div class="modal" id="edit-modal">
    <div class="modal-background" onclick="closeEditModal()"></div>
    <div class="modal-card">
        <header class="modal-card-head">
            <p class="modal-card-title" id="edit-modal-title">Vertrag bearbeiten</p>
            <button class="delete" onclick="closeEditModal()" aria-label="close"></button>
        </header>
        <section class="modal-card-body">
            <form id="edit-form">
                <div class="field">
                    <label class="label is-small">Belegnummer</label>
                    <div class="control"><input class="input is-small" name="belegnummer" id="edit-belegnummer"></div>
                </div>
                <div class="field">
                    <label class="label is-small">Beleg-Datum</label>
                    <div class="control"><input class="input is-small" type="date" name="beleg_datum" id="edit-beleg-datum"></div>
                </div>
                <div class="field">
                    <label class="label is-small">Laufzeit Start</label>
                    <div class="control"><input class="input is-small" type="date" name="laufzeit_start" id="edit-laufzeit-start"></div>
                </div>
                <div class="field">
                    <label class="label is-small">Laufzeit Ende</label>
                    <div class="control"><input class="input is-small" type="date" name="laufzeit_ende" id="edit-laufzeit-ende"></div>
                </div>
                <div class="field">
                    <label class="label is-small">Status</label>
                    <div class="control">
                        <div class="select is-small">
                            <select name="status" id="edit-status">
                                <option value="NEU">NEU</option>
                                <option value="Zur Prüfung">Zur Prüfung</option>
                                <option value="Angenommen">Angenommen</option>
                            </select>
                        </div>
                    </div>
                </div>
            </form>
        </section>
        <footer class="modal-card-foot">
            <button class="button is-info" onclick="saveEdit()">Speichern</button>
            <button class="button" onclick="closeEditModal()">Abbrechen</button>
        </footer>
    </div>
</div>

<script>
var editContractId = null;

function openEditModal(id) {
    editContractId = id;
    var row = document.getElementById('contract-row-' + id);
    var cells = row.querySelectorAll('td');
    document.getElementById('edit-modal-title').textContent = cells[0].textContent.trim();
    document.getElementById('edit-belegnummer').value = cells[1].textContent.trim() === '–' ? '' : cells[1].textContent.trim();
    var belegDatum = cells[2].textContent.trim();
    document.getElementById('edit-beleg-datum').value = belegDatum !== '–' ? toDateInput(belegDatum) : '';
    var laufzeit = cells[3].textContent.trim().split('–');
    document.getElementById('edit-laufzeit-start').value = laufzeit[0] && laufzeit[0].trim() !== '?' ? toDateInput(laufzeit[0].trim()) : '';
    document.getElementById('edit-laufzeit-ende').value = laufzeit[1] && laufzeit[1].trim() !== '?' ? toDateInput(laufzeit[1].trim()) : '';
    var statusTag = row.querySelector('.tag');
    document.getElementById('edit-status').value = statusTag.textContent.trim();
    document.getElementById('edit-modal').classList.add('is-active');
}

function closeEditModal() {
    document.getElementById('edit-modal').classList.remove('is-active');
    editContractId = null;
}

function toDateInput(ddmm) {
    var parts = ddmm.split('.');
    if (parts.length === 3) return parts[2] + '-' + parts[1] + '-' + parts[0];
    return '';
}

function saveEdit() {
    var form = document.getElementById('edit-form');
    var data = new FormData(form);
    data.append('contract_id', editContractId);
    fetch('/contracts/' + editContractId + '/update', {
        method: 'POST',
        headers: {'X-Requested-With': 'XMLHttpRequest'},
        body: data
    }).then(function(r) {
        if (r.ok) location.reload();
        else alert('Fehler beim Speichern');
    });
}
</script>
{% endblock %}
