<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Betriebskosten</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-modal/0.9.1/jquery.modal.min.js"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jquery-modal/0.9.1/jquery.modal.min.css" />
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 20px;
            background-color: #f4f4f9;
        }
        .table-container {
            width: 100%;
            background-color: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
        }
        h2 {
            text-align: center;
            color: #333;
        }
        table {
            width: 100%;
            table-layout: fixed;
            border-collapse: collapse;
        }
        th, td {
            padding: 12px;
            text-align: center;
            border-bottom: 1px solid #ddd;
        }
        th:nth-child(1), td:nth-child(1) { width: 4%; }
        th:nth-child(2), td:nth-child(2) { width: 12%; }
        th:nth-child(3), td:nth-child(3) { width: 8%; }
        th:nth-child(4), td:nth-child(4) { width: 12%; }
        th:nth-child(5), td:nth-child(5) { width: 8%; }
        th:nth-child(6), td:nth-child(6) { width: 8%; }
        th:nth-child(7), td:nth-child(7) { width: 8%; }
        th:nth-child(8), td:nth-child(8) { width: 8%; }
        th:nth-child(9), td:nth-child(9) { width: 8%; }
        th:nth-child(10), td:nth-child(10) { width: 8%; }
        th:nth-child(11), td:nth-child(11) { width: 12%; }
        th:nth-child(12), td:nth-child(12) { width: 8%; }
                
        .actions {
            white-space: nowrap; /* Prevent buttons from wrapping */
        }
        th {
            background-color: #007bff;
            color: white;
            font-weight: bold;
            position: sticky;
            top: 0;
        }
        tr:hover {
            background-color: #f1f1f1;
        }
        .actions button {
            margin: 2px;
            padding: 5px 10px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
        }
        .edit-btn {
            background-color: #28a745;
            color: white;
        }
        .delete-btn {
            background-color: #dc3545;
            color: white;
        }
        .popup {
            display: none;
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background: white;
            padding: 20px;
            border-radius: 5px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.3);
            z-index: 1000;
            width: 400px;
        }
        .popup input, .popup select, .popup textarea {
            display: block;
            margin-bottom: 10px;
            width: 100%;
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
        }
        .popup button {
            margin-top: 10px;
            padding: 8px 16px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
        }
        .close-btn {
            cursor: pointer;
            float: right;
            font-size: 18px;
            color: #333;
        }
        .add-row-btn {
            padding: 10px 20px;
            background-color: #007bff;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 16px;
            margin-bottom: 20px;
        }
        .add-row-btn:hover {
            background-color: #0056b3;
        }
        .save-btn {
            background-color: #28a745;
            color: white;
        }
        .cancel-btn {
            background-color: #6c757d;
            color: white;
        }
        .help-btn {
            background-color: #17a2b8;
            color: white;
        }
        #price-per-liter-group {
            display: none;
        }

    </style>
</head>
<body>

    <a href="{% url 'clients_list' %}" class="btn btn-outline-primary">
        &#8678; Go to Clients
    </a>

    <h2>Betriebskosten</h2>
    <div class="table-container">
        <div style="margin-bottom:20px;">
            <label><strong>Personalkosten:</strong></label>
            <input id="personalkosten"
                type="number"
                step="0.01"
                value="{{ summary.personalkosten }}"
                style="width:200px;">
        </div>

        <table style="margin-bottom:20px;">
            <tr>
                <td>Instandhaltung</td>
                <td>{{ summary.instandhaltung|floatformat:2 }} €</td>
            </tr>
            <tr>
                <td>Verflüssigungskosten L-He</td>
                <td>{{ verfluessigungskosten_lhe|floatformat:6 }} €/L-He</td>
            </tr>
            <tr>
                <td>Heliumkosten</td>
                <td>{{ summary.heliumkosten|floatformat:2 }} €</td>
            </tr>
            <tr>
                <td>Bezugskosten -GasHe</td>
                <td>{{ summary.bezugskosten_gashe|floatformat:2 }} €/m³</td>
            </tr>
            <tr>
                <td>Umlage Personal</td>
                <td id="umlage-personal">{{ summary.umlage_personal|floatformat:2 }} €</td>
            </tr>
        </table>

        <button class="add-row-btn" id="add-row-btn">Add Row</button>
            <table id="betriebskosten-table">
        <thead>
            <tr>
                <th>#</th>
                <th>Gegenstand</th>
                <th>Zahlungsdatum</th>
                <th>Firma</th>
                <th>Kostentyp</th>
                <th>Gasvolumen (m³)</th>
                <th>Gasvolumen (Liter)</th>
                <th>Preis pro m³ (€)</th>
                <th>Preis pro Liter (€)</th>
                <th>Betrag (€)</th>
                <th>Beschreibung</th>
                <th>Actions</th>
            </tr>
        </thead>

        <tbody>
            {% for item in items %}
            <tr data-id="{{ item.id }}">
                <td>{{ forloop.counter }}</td>
                <td>{{ item.gegenstand }}</td>
                <td>{{ item.buchungsdatum|date:"Y-m-d" }}</td>
                <td>{{ item.rechnungsnummer }}</td>
                <td>{{ item.get_kostentyp_display }}</td>

                <td>{{ item.gas_volume|default_if_none:"-" }}</td>
                <td>{% if item.gas_volume %}{{ item.gas_volume_liter|floatformat:2 }}{% else %}-{% endif %}</td>
                <td>{% if item.price_per_m3 %}{{ item.price_per_m3|floatformat:2 }}{% else %}-{% endif %}</td>
                <td>{% if item.price_per_liter %}{{ item.price_per_liter|floatformat:2 }}{% else %}-{% endif %}</td>

                <td>{{ item.betrag }}</td>
                <td>{{ item.beschreibung|default:"" }}</td>
                <td class="actions">
                    <button class="edit-btn">Edit</button>
                    <button class="delete-btn">Delete</button>
                </td>
            </tr>
            {% empty %}
            <tr>
                <td colspan="12" style="text-align:center; padding:20px;">
                    No entries found
                </td>
            </tr>
            {% endfor %}
        </tbody>
    </table>

    </div>

    <!-- Add Popup -->
    <div id="add-popup" class="popup">
        <span class="close-btn">&times;</span>
        <h3>Betriebskosten Eintrag</h3>

        <label for="add-gegenstand">Gegenstand:</label>
        <input type="text" id="add-gegenstand" required>
        
        <label for="add-buchungsdatum">Zahlungsdatum:</label>
        <input type="date" id="add-buchungsdatum" required>
        
        <label for="add-rechnungsnummer">Firma:</label>
        <input type="text" id="add-rechnungsnummer" required>
        
        <label for="add-kostentyp">Kostentyp:</label>
        <select id="add-kostentyp" required onchange="toggleGasVolume('add')">
            <option value="" selected disabled>Bitte auswählen</option>
            <option value="sach">Sach</option>
            <option value="helium">Helium</option></select>
        
        <div id="add-gas-volume-group" style="display: none;">
            <label for="add-gas-volume">Gasvolumen (m³):</label>
            <input type="number" id="add-gas-volume" step="0.01" min="0" oninput="calculateHelium('add')">

            <label for="add-gas-volume-liter">Gasvolumen (Liter):</label>
            <input type="text" id="add-gas-volume-liter" readonly>
        </div>
        
        <label for="add-betrag">Betrag (€):</label>
        <input type="number" id="add-betrag" step="0.01" min="0" required oninput="calculateHelium('add')">
        
        <div id="add-price-per-liter-group" style="display: none;">
            <label for="add-price-per-m3">Preis pro Liter (m³) (€) (auto):</label>
            <input type="text" id="add-price-per-m3" readonly>

            <label for="add-price-per-liter">Preis (Liter) (€):</label>
            <input type="text" id="add-price-per-liter" readonly>
        </div>
        
        <label for="add-beschreibung">Beschreibung:</label>
        <textarea id="add-beschreibung" placeholder="Optionale Beschreibung"></textarea>
        
        <div class="popup-buttons">
            <button class="save-btn" id="save-add">Save</button>
            <button class="cancel-btn">Cancel</button>
            <button class="help-btn">Help</button>
        </div>
    </div>

    <!-- Edit Popup -->
    <div id="edit-popup" class="popup">
        <span class="close-btn">&times;</span>
        <h3>Betriebskosten Eintrag</h3>
        <input type="hidden" id="edit-id">

        <label for="edit-gegenstand">Gegenstand:</label>
        <input type="text" id="edit-gegenstand" required>
        
        <label for="edit-buchungsdatum">Zahlungsdatum:</label>
        <input type="date" id="edit-buchungsdatum" required>
        
        <label for="edit-rechnungsnummer">Firma:</label>
        <input type="text" id="edit-rechnungsnummer" required>
        
        <label for="edit-kostentyp">Kostentyp:</label>
        <select id="edit-kostentyp" required onchange="toggleGasVolume('edit')">
            <option value="" selected disabled>Bitte auswählen</option>
            <option value="sach">Sach</option>
            <option value="helium">Helium</option></select>
        
        <div id="edit-gas-volume-group" style="display: none;">
            <label for="edit-gas-volume">Gasvolumen (m³):</label>
            <input type="number" id="edit-gas-volume" step="0.01" min="0" oninput="calculateHelium('edit')">

            <label for="edit-gas-volume-liter">Gasvolumen (Liter) (auto):</label>
            <input type="text" id="edit-gas-volume-liter" readonly>
        </div>
        
        <label for="edit-betrag">Betrag (€):</label>
        <input type="number" id="edit-betrag" step="0.01" min="0" required oninput="calculateHelium('edit')">
        
        <div id="edit-price-per-liter-group" style="display: none;">
            <label for="edit-price-per-m3">Preis pro Liter (m³) (€) (auto):</label>
            <input type="text" id="edit-price-per-m3" readonly>

            <label for="edit-price-per-liter">Preis (Liter) (€) (auto):</label>
            <input type="text" id="edit-price-per-liter" readonly>
        </div>
        
        <label for="edit-beschreibung">Beschreibung:</label>
        <textarea id="edit-beschreibung" placeholder="Optionale Beschreibung"></textarea>
        
        <div class="popup-buttons">
            <button class="save-btn" id="save-edit">Save</button>
            <button class="cancel-btn">Cancel</button>
            <button class="help-btn">Help</button>
        </div>
    </div>

    <script>
        $(document).ready(function () {
            // Open add popup
            $('#add-row-btn').on('click', function () {
                // Reset fields so the placeholder "Gegenstand" is shown
                $('#add-popup input, #add-popup textarea').val('');
                $('#add-kostentyp').val('');
                toggleGasVolume('add');
                calculateHelium('add');
                $('#add-popup').fadeIn();
            });

            // Close popups
            $('.close-btn, .cancel-btn').on('click', function () {
                $('.popup').fadeOut();
            });

            // Add new entry
            $('#save-add').on('click', function() {
                const formData = {
                    'gegenstand': $('#add-gegenstand').val(),
                    'buchungsdatum': $('#add-buchungsdatum').val(),
                    'rechnungsnummer': $('#add-rechnungsnummer').val(),
                    'kostentyp': $('#add-kostentyp').val(),
                    'gas_volume': $('#add-gas-volume').val(),
                    'betrag': $('#add-betrag').val(),
                    'beschreibung': $('#add-beschreibung').val(),
                    'csrfmiddlewaretoken': '{{ csrf_token }}'
                };

                // Validate required fields
                if (!formData.gegenstand || !formData.buchungsdatum || !formData.rechnungsnummer || !formData.kostentyp || !formData.betrag) {

                    alert('Bitte füllen Sie alle erforderlichen Felder aus');
                    return;
                }

                $.ajax({
                    url: "{% url 'betriebskosten_create' %}",
                    method: 'POST',
                    data: formData,
                    success: function(response) {
                        if (response.status === 'success') {
                            // Add the new row to the table
                            const newRow = `
                                <tr data-id="${response.id}">
                                    <td>${$('#betriebskosten-table tbody tr').length + 1}</td>
                                    <td>${response.gegenstand || ''}</td>
                                    <td>${response.buchungsdatum}</td>
                                    <td>${response.rechnungsnummer}</td>
                                    <td>${response.kostentyp_display}</td>
                                    <td>${response.gas_volume_m3 || '-'}</td>
                                    <td>${response.gas_volume_liter || '-'}</td>
                                    <td>${response.price_per_m3 || '-'}</td>
                                    <td>${response.price_per_liter || '-'}</td>
                                    <td>${response.betrag}</td>
                                    <td>${response.beschreibung || ''}</td>
                                    <td class="actions">
                                        <button class="edit-btn">Edit</button>
                                        <button class="delete-btn">Delete</button>
                                    </td>
                                </tr>
                                `;
                            $('#betriebskosten-table tbody').append(newRow);
                            $('#add-popup').fadeOut();
                            $('#add-popup input, #add-popup select, #add-popup textarea').val('');
                        } else {
                            alert('Error: ' + (response.message || 'Failed to add entry'));
                        }
                    },
                    error: function(xhr) {
                        alert('Error: ' + (xhr.responseJSON?.message || 'Server error'));
                    }
                });
            });

            // Edit entry
            $(document).on('click', '.edit-btn', function() {
                const row = $(this).closest('tr');
                const id = row.data('id');
                
                // Fill the edit form with current data
                $('#edit-id').val(id);
                $('#edit-gegenstand').val(row.find('td:eq(1)').text());
                $('#edit-buchungsdatum').val(row.find('td:eq(2)').text());
                $('#edit-rechnungsnummer').val(row.find('td:eq(3)').text());

                const kostentypText = row.find('td:eq(4)').text();
                // Set kostentyp based on display text
              
                const kostentypMap = {
                    'Sach': 'sach',
                    'Sachkosten': 'sach',
                    
                    'Helium': 'helium'
                };
                $('#edit-kostentyp').val(kostentypMap[kostentypText] || '');
                
                $('#edit-gas-volume').val(row.find('td:eq(5)').text() === '-' ? '' : row.find('td:eq(5)').text());
                $('#edit-betrag').val(row.find('td:eq(6)').text());
                $('#edit-beschreibung').val(row.find('td:eq(7)').text());
                
                // Show/hide gas volume based on kostentyp
                toggleGasVolume('edit');
                calculateHelium('edit');
                
                $('#edit-popup').fadeIn();
            });

            // Save edit
            $('#save-edit').on('click', function() {
                const formData = {
                    'id': $('#edit-id').val(),
                    'gegenstand': $('#edit-gegenstand').val(),
                    'buchungsdatum': $('#edit-buchungsdatum').val(),
                    'rechnungsnummer': $('#edit-rechnungsnummer').val(),
                    'kostentyp': $('#edit-kostentyp').val(),
                    'gas_volume': $('#edit-gas-volume').val(),
                    'betrag': $('#edit-betrag').val(),
                    'beschreibung': $('#edit-beschreibung').val(),
                    'csrfmiddlewaretoken': '{{ csrf_token }}'
                };

                // Validate required fields
                if (!formData.buchungsdatum || !formData.rechnungsnummer || !formData.kostentyp || !formData.betrag) {
                    alert('Bitte füllen Sie alle erforderlichen Felder aus');
                    return;
                }

                $.ajax({
                    url: "{% url 'betriebskosten_create' %}",
                    method: 'POST',
                    data: formData,
                    success: function(response) {
                        if (response.status === 'success') {
                            // Update the row in the table
                            const row = $(`tr[data-id="${response.id}"]`);
                            row.find('td:eq(1)').text(response.gegenstand || '');
                            row.find('td:eq(2)').text(response.buchungsdatum);
                            row.find('td:eq(3)').text(response.rechnungsnummer);
                            row.find('td:eq(4)').text(response.kostentyp_display);
                            row.find('td:eq(5)').text(response.gas_volume_m3 || '-');
                            row.find('td:eq(6)').text(response.gas_volume_liter || '-');
                            row.find('td:eq(7)').text(response.price_per_m3 || '-');
                            row.find('td:eq(8)').text(response.price_per_liter || '-');
                            row.find('td:eq(9)').text(response.betrag);
                            row.find('td:eq(10)').text(response.beschreibung || '');
                            
                            $('#edit-popup').fadeOut();
                            $('#betriebskosten-table tbody tr').each(function(index) {
                                $(this).find('td:first').text(index + 1);
                            });
                        } else {
                            alert('Error: ' + (response.message || 'Failed to update entry'));
                        }
                    },
                    error: function(xhr) {
                        alert('Error: ' + (xhr.responseJSON?.message || 'Server error'));
                    }
                });
            });

            // Delete entry
            $(document).on('click', '.delete-btn', function () {
                const row = $(this).closest('tr');
                const id = row.data('id');
                if (!id) {
                    alert("Invalid entry ID. Cannot delete this row.");
                    return;
}

                if (!confirm('Are you sure you want to delete this entry?')) return;

                $.ajax({
                    url: "{% url 'betriebskosten_delete' %}",
                    method: 'POST',
                    data: {
                        'id': id,
                        'csrfmiddlewaretoken': '{{ csrf_token }}'
                    },
                    success: function (response) {
                        if (response.status === 'success') {
                            row.fadeOut(300, function () { $(this).remove(); });
                            // Update row numbers
                            $('#betriebskosten-table tbody tr').each(function(index) {
                                $(this).find('td:first').text(index + 1);
                            });
                        } else {
                            alert('Failed to delete entry: ' + response.message);
                        }
                    },
                    error: function () {
                        alert('Failed to delete entry. Please try again.');
                    }
                });
            });
        });

        // Toggle helium-only fields based on Kostentyp
        function toggleGasVolume(type) {
            const kostentyp = $(`#${type}-kostentyp`).val();
            const gasVolumeGroup = $(`#${type}-gas-volume-group`);
            const priceGroup = $(`#${type}-price-per-liter-group`);

            if (kostentyp === 'helium') {
                gasVolumeGroup.show();
                priceGroup.show();
                calculateHelium(type);
            } else {
                gasVolumeGroup.hide();
                priceGroup.hide();

                // reset helium-only fields
                $(`#${type}-gas-volume`).val('');
                $(`#${type}-gas-volume-liter`).val('');
                $(`#${type}-price-per-m3`).val('');
                $(`#${type}-price-per-liter`).val('');
            }
        }

        // Helium calculations (all auto/read-only fields)
        // Liter = m³ / 0.75
        // Preis/m³ = Betrag / m³
        // Preis/Liter = Betrag / Liter
        function calculateHelium(type) {
            const kostentyp = $(`#${type}-kostentyp`).val();
            const m3 = parseFloat($(`#${type}-gas-volume`).val()) || 0;
            const betrag = parseFloat($(`#${type}-betrag`).val()) || 0;

            if (kostentyp !== 'helium') return;

            if (m3 > 0) {
                const liters = m3 / 0.75;
                $(`#${type}-gas-volume-liter`).val(liters.toFixed(2));

                if (betrag > 0) {
                    const priceM3 = betrag / m3;
                    const priceLiter = betrag / liters;

                    $(`#${type}-price-per-m3`).val(priceM3.toFixed(2));
                    $(`#${type}-price-per-liter`).val(priceLiter.toFixed(2));
                } else {
                    $(`#${type}-price-per-m3`).val('');
                    $(`#${type}-price-per-liter`).val('');
                }
            } else {
                $(`#${type}-gas-volume-liter`).val('');
                $(`#${type}-price-per-m3`).val('');
                $(`#${type}-price-per-liter`).val('');
            }
        }
            $('#personalkosten').on('change', function () {
        $.ajax({
            url: "{% url 'update_personalkosten' %}",
            method: "POST",
            data: {
                personalkosten: $(this).val(),
                csrfmiddlewaretoken: "{{ csrf_token }}"
            },
            success: function(response) {
                if (response.status === "success") {
                    $('#umlage-personal').text(
                        parseFloat(response.umlage_personal).toFixed(2) + " €"
                    );
                } else {
                    alert(response.message || "Failed to save Personalkosten");
                }
            },
            error: function(xhr) {
                alert(xhr.responseJSON?.message || "Server error while saving Personalkosten");
            }
        });
    });


    </script>
</body>
</html>