<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Helium Input</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);
            overflow-x: auto;
        }
        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;
            word-wrap: break-word;
        }
        th:nth-child(1), td:nth-child(1) { width: 3%; } /* # column */
        th:nth-child(2), td:nth-child(2) { width: 3%; } /* ID column */
        th:nth-child(3), td:nth-child(3) { width: 8%; } /* Institute */
        th:nth-child(4), td:nth-child(4) { width: 8%; } /* Client */
        th:nth-child(5), td:nth-child(5) { width: 5%; } /* Druck */
        th:nth-child(6), td:nth-child(6) { width: 5%; } /* Reinheit */
        th:nth-child(7), td:nth-child(7) { width: 5%; } /* Druckkorrektur */
        th:nth-child(8), td:nth-child(8) { width: 6%; } /* ges. Flasch. Inhalt */
        th:nth-child(9), td:nth-child(9) { width: 6%; } /* Korrig. Druck */
        th:nth-child(10), td:nth-child(10) { width: 5%; } /* Nm³ */
        th:nth-child(11), td:nth-child(11) { width: 5%; } /* L-He */
        th:nth-child(12), td:nth-child(12) { width: 5%; } /* L-He zus. */
        th:nth-child(13), td:nth-child(13) { width: 6%; } /* L-He ges. */
        th:nth-child(14), td:nth-child(14) { width: 6%; } /* Date Joined */
        th:nth-child(15), td:nth-child(15) { width: 8%; } /* Actions */
        
        .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-one {
            background-color: #28a745;
            color: white;
        }
        .delete-btn-one {
            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: 500px;
            max-height: 90vh;
            overflow-y: auto;
        }
        .popup h3 {
            margin-top: 0;
            border-bottom: 1px solid #ddd;
            padding-bottom: 10px;
        }
        .popup label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
        }
        .popup input, .popup select, .popup textarea {
            display: block;
            margin-bottom: 15px;
            width: 100%;
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
            box-sizing: border-box;
        }
        .popup textarea {
            height: 100px;
            resize: vertical;
        }
        .popup-buttons {
            display: flex;
            justify-content: flex-end;
            gap: 10px;
            margin-top: 20px;
        }
        .popup button {
            padding: 8px 16px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
        }
        .save-btn {
            background-color: #28a745;
            color: white;
        }
        .cancel-btn {
            background-color: #6c757d;
            color: white;
        }
        .help-btn {
            background-color: #17a2b8;
            color: white;
        }
        .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;
        }
        .input-with-label {
            display: flex;
            align-items: center;
            margin-bottom: 15px;
        }
        .input-with-label label {
            width: 150px;
            margin-bottom: 0;
            margin-right: 10px;
        }
        .input-with-label input {
            flex: 1;
            margin-bottom: 0;
        }
        .formula-display {
            background-color: #f8f9fa;
            border: 1px solid #dee2e6;
            border-radius: 4px;
            padding: 8px;
            margin-bottom: 15px;
            font-size: 12px;
            color: #6c757d;
            font-style: italic;
        }
        .readonly-field {
            background-color: #e9ecef;
            color: #6c757d;
        }
                /* ---- 6-month overview card ---- */
        .overview-card {
            background-color: #ffffff;
            padding: 16px 20px;
            margin: 20px 0;
            border-radius: 8px;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.08);
        }

        .overview-header {
            display: flex;
            flex-wrap: wrap;
            gap: 12px;
            align-items: flex-end;
            margin-bottom: 12px;
        }

        .overview-header label {
            font-size: 0.9rem;
            color: #555;
        }

        .overview-header select {
            padding: 6px 8px;
            border-radius: 4px;
            border: 1px solid #ccc;
        }

        .overview-header button {
            padding: 7px 14px;
            border-radius: 4px;
            border: none;
            background-color: #007bff;
            color: #fff;
            cursor: pointer;
        }

        .overview-header button:hover {
            background-color: #0056b3;
        }

        .overview-title {
            font-size: 1.1rem;
            font-weight: bold;
            margin-bottom: 8px;
            color: #333;
        }

        .overview-subtitle {
            font-size: 0.9rem;
            color: #555;
            margin-bottom: 8px;
        }

        .overview-table {
            width: 100%;
            border-collapse: collapse;
        }

        .overview-table th,
        .overview-table td {
            padding: 6px 8px;
            border-bottom: 1px solid #eee;
            font-size: 0.9rem;
        }

        .overview-table thead th {
            background-color: #007bff;
            color: #fff;
            text-align: right;
        }

        .overview-table thead th:first-child {
            text-align: left;
        }

        .overview-table tbody tr:hover {
            background-color: #f8f9ff;
        }

        .overview-table .number-cell {
            text-align: right;
        }

        .overview-table .summary-row {
            background-color: #f0f4ff;
            font-weight: bold;
        }
    </style>
</head>
<body>

    <!-- This link should ONLY wrap the text below -->
    <a href="{% url 'clients_list' %}" class="btn btn-outline-primary">
        &#8678; Go to Clients
    </a>

    <!-- 6-Month overview card (OUTSIDE any <a>) -->
    <div class="overview-card">
            <div class="overview-title">Helium Input – 6 Month Overview</div>

        {% if overview %}
            <div class="overview-subtitle">
                Period:
                    <strong>
                        {{ overview.start_month }}/{{ overview.start_year }}
                        – {{ overview.end_month }}/{{ overview.end_year }}
                    </strong>
                    (selected on the main page)
            </div>

            <table class="overview-table">
                <thead>
                    <tr>
                        <th>Month</th>
                        {% for g in overview.groups %}
                            <th>{{ g.label }}</th>
                        {% endfor %}
                        <th>Month total</th>
                    </tr>
                </thead>
                <tbody>
                    {% for row in overview.rows %}
                        <tr>
                            <td>
                                {{ row.month_number }} - {{ row.month_label|slice:":3" }}
                            </td>
                            {% for value in row.values %}
                                <td class="number-cell">{{ value|floatformat:2 }}</td>
                            {% endfor %}
                            <td class="number-cell">{{ row.total|floatformat:2 }}</td>
                        </tr>
                    {% endfor %}

                    <tr class="summary-row">
                        <td>Summe</td>
                        {% for total in overview.group_totals %}
                            <td class="number-cell">{{ total|floatformat:2 }}</td>
                        {% endfor %}
                        <td class="number-cell">{{ overview.grand_total|floatformat:2 }}</td>
                    </tr>
                </tbody>
            </table>
        {% endif %}

    </div>


    <h2>Helium Input</h2>
    <div class="table-container">
        <button class="add-row-btn" id="add-row-one">Add Row</button>
        <table id="table-one">
        <colgroup>
            <col style="width: 3%">  <!-- # -->
            <col style="width: 3%">  <!-- ID -->
            <col style="width: 8%"> <!-- Institute -->
            <col style="width: 8%"> <!-- Client -->
            <col style="width: 5%"> <!-- Druck -->
            <col style="width: 5%"> <!-- Reinheit -->
            <col style="width: 5%"> <!-- Druckkorrektur -->
            <col style="width: 6%"> <!-- ges. Flasch. Inhalt -->
            <col style="width: 6%"> <!-- Korrig. Druck -->
            <col style="width: 5%"> <!-- Nm³ -->
            <col style="width: 5%"> <!-- L-He -->
            <col style="width: 5%"> <!-- L-He zus. -->
            <col style="width: 6%"> <!-- L-He ges. -->
            <col style="width: 7%"> <!-- Date -->
            <col style="width: 5%"> <!-- Month -->
            <col style="width: 8%"> <!-- Actions -->
        </colgroup>
        <thead>
            <tr>
                <th>#</th>
                <th>ID</th>
                <th>Institute</th>
                <th>Client</th>
                <th>Druck</th>
                <th>Reinheit</th>
                <th>Druckkorrektur</th>
                <th>ges. Flasch. Inhalt</th>
                <th>Korrig. Druck</th>
                <th>Nm³</th>
                <th>L-He</th>
                <th>L-He zus.</th>
                <th>L-He ges.</th>
                <th>Date</th>
                <th>Month</th>
                <th>Actions</th>
            </tr>
        </thead>
        <tbody>
            {% for entry in entries_table1 %}
                <tr data-id="{{ entry.id }}">
                    <td>{{ forloop.counter }}</td>
                    <td>{{ entry.id }}</td>
                    <td>{{ entry.client.institute.name }}</td>
                    <td>{{ entry.client.name }}</td>
                    <td>{{ entry.pressure|floatformat:2 }}</td>
                    <td>{{ entry.purity|floatformat:2 }}</td>
                    <td>{{ entry.druckkorrektur|floatformat:2 }}</td>
                    <td>{{ entry.constant_300|floatformat:2 }}</td>
                    <td>{{ entry.korrig_druck|floatformat:2 }}</td>
                    <td>{{ entry.nm3|floatformat:2 }}</td>
                    <td>{{ entry.lhe|floatformat:2 }}</td>
                    <td>{{ entry.lhe_zus|floatformat:2 }}</td>
                    <td>{{ entry.lhe_ges|floatformat:2 }}</td>
                    <td>
                        {% if entry.date %}
                            {{ entry.date|date:"d.m.Y" }}
                        {% endif %}
                    </td>
                    <td>
                        {% if entry.date %}
                            {{ entry.date|date:"m" }}   {# e.g. 01–12 #}
                        {% endif %}
                    </td>
                    <td class="actions">
                        <button class="edit-btn-one">Edit</button>
                        <button class="delete-btn-one">Delete</button>
                    </td>
                </tr>
            {% endfor %}
        </tbody>
    </table>
    </div>

    <!-- Add Popup -->
    <div id="add-popup-one" class="popup">
        <span class="close-btn">&times;</span>
        <h3>He Gas Bundle</h3>
        
        <!-- Institute Selection -->
        <label for="add-institute-id">Institute:</label>
        <select id="add-institute-id">
            <option value="">Select Institute</option>
            {% for institute in institutes %}
                <option value="{{ institute.id }}">{{ institute.name }}</option>
            {% endfor %}
        </select>
        
        <!-- Client Selection -->
        <label for="add-client-id">Kunde:</label>
        <select id="add-client-id" disabled>
            <option value="">Select Institute first</option>
            {% for client in clients %}
                <option value="{{ client.id }}" data-institute="{{ client.institute.id }}">{{ client.name }}</option>
            {% endfor %}
        </select>
        
        <label for="add-date">Date:</label>
        <input type="date" id="add-date">
        
        <!-- Manual Input Fields -->
        <div class="input-with-label">
            <label for="add-pressure">Druck:</label>
            <input type="number" id="add-pressure" placeholder="Enter pressure" step="0.01" min="0">
        </div>
        
        <div class="input-with-label">
            <label for="add-purity">Reinheit:</label>
            <input type="number" id="add-purity" placeholder="Enter purity" step="0.01" min="0" max="100">
        </div>
        
        <div class="input-with-label">
            <label for="add-druckkorrektur">Druckkorrektur:</label>
            <input type="number" id="add-druckkorrektur" placeholder="Enter Druckkorrektur" step="0.001" min="0" value="1.0">
        </div>

        <div class="input-with-label">
            <label for="add-lhe-zus">L-He zus.:</label>
            <input type="number" id="add-lhe-zus" placeholder="Enter L-He zus." step="0.001" min="0" value="0.0">
        </div>
        
        <!-- Auto-calculated Fields with Formulas -->
        <div class="input-with-label">
            <label for="add-constant-300">ges. Flasch. Inhalt:</label>
            <input type="number" id="add-constant-300" step="0.001" min="0">
        </div>
        <div class="formula-display">Editable value</div>
        <div class="formula-display">Formula: Fixed value (300)</div>
        
        <div class="input-with-label">
            <label for="add-korrig-druck">Korrig. Druck:</label>
            <input type="number" id="add-korrig-druck" step="0.000001" readonly class="readonly-field">
        </div>
        <div class="formula-display">Formula: Druck * Druckkorrektur / ((Druck * Druckkorrektur) / 2000 + 1)</div>
        
        <div class="input-with-label">
            <label for="add-nm3">Nm³:</label>
            <input type="number" id="add-nm3" step="0.000001" readonly class="readonly-field">
        </div>
        <div class="formula-display">Formula: (ges. Flasch. Inhalt * Korrig. Druck) / 1000</div>
        
        <div class="input-with-label">
            <label for="add-lhe">L-He:</label>
            <input type="number" id="add-lhe" step="0.000001" readonly class="readonly-field">
        </div>
        <div class="formula-display">Formula: Nm³ * (1 - Reinheit/100) / 0.75</div>
        
        <div class="input-with-label">
            <label for="add-lhe-ges">L-He ges.:</label>
            <input type="number" id="add-lhe-ges" step="0.000001" readonly class="readonly-field">
        </div>
        <div class="formula-display">Formula: L-He zus. + L-He</div>
        
        <div class="popup-buttons">
            <button class="save-btn" id="save-add-one">Save</button>
            <button class="cancel-btn">Cancel</button>
            <button class="help-btn">Help</button>
        </div>
    </div>

    <!-- Edit Popup -->
    <div id="edit-popup-one" class="popup">
        <span class="close-btn">&times;</span>
        <h3>He Gas Bundle</h3>
        <input type="hidden" id="edit-id">
        
        <!-- Institute Selection -->
        <label for="edit-institute-id">Institute:</label>
        <select id="edit-institute-id">
            <option value="">Select Institute</option>
            {% for institute in institutes %}
                <option value="{{ institute.id }}">{{ institute.name }}</option>
            {% endfor %}
        </select>
        
        <!-- Client Selection -->
        <label for="edit-client-id">Kunde:</label>
        <select id="edit-client-id" disabled>
            <option value="">Select Institute first</option>
            {% for client in clients %}
                <option value="{{ client.id }}" data-institute="{{ client.institute.id }}">{{ client.name }}</option>
            {% endfor %}
        </select>
        
        <label for="edit-date">Date:</label>
        <input type="date" id="edit-date">
        
        <!-- Manual Input Fields -->
        <div class="input-with-label">
            <label for="edit-pressure">Druck:</label>
            <input type="number" id="edit-pressure" placeholder="Enter pressure" step="0.01" min="0">
        </div>
        
        <div class="input-with-label">
            <label for="edit-purity">Reinheit:</label>
            <input type="number" id="edit-purity" placeholder="Enter purity" step="0.01" min="0" max="100">
        </div>
        
        <div class="input-with-label">
            <label for="edit-druckkorrektur">Druckkorrektur:</label>
            <input type="number" id="edit-druckkorrektur" placeholder="Enter Druckkorrektur" step="0.001" min="0" value="1.0">
        </div>

        <div class="input-with-label">
            <label for="edit-lhe-zus">L-He zus.:</label>
            <input type="number" id="edit-lhe-zus" placeholder="Enter L-He zus." step="0.001" min="0" value="0.0">
        </div>
        
        <!-- Auto-calculated Fields with Formulas -->
        <div class="input-with-label">
            <label for="edit-constant-300">ges. Flasch. Inhalt:</label>
            <input type="number" id="edit-constant-300" step="0.001" min="0">
        </div>
        <div class="formula-display">Formula: Fixed value (300)</div>
        
        <div class="input-with-label">
            <label for="edit-korrig-druck">Korrig. Druck:</label>
            <input type="number" id="edit-korrig-druck" step="0.000001" readonly class="readonly-field">
        </div>
        <div class="formula-display">Formula: Druck * Druckkorrektur / ((Druck * Druckkorrektur) / 2000 + 1)</div>
        
        <div class="input-with-label">
            <label for="edit-nm3">Nm³:</label>
            <input type="number" id="edit-nm3" step="0.000001" readonly class="readonly-field">
        </div>
        <div class="formula-display">Formula: (ges. Flasch. Inhalt * Korrig. Druck) / 1000</div>
        
        <div class="input-with-label">
            <label for="edit-lhe">L-He:</label>
            <input type="number" id="edit-lhe" step="0.000001" readonly class="readonly-field">
        </div>
        <div class="formula-display">Formula: Nm³ * (1 - Reinheit/100) / 0.75</div>
        
        <div class="input-with-label">
            <label for="edit-lhe-ges">L-He ges.:</label>
            <input type="number" id="edit-lhe-ges" step="0.000001" readonly class="readonly-field">
        </div>
        <div class="formula-display">Formula: L-He zus. + L-He</div>
        
        <div class="popup-buttons">
            <button class="save-btn" id="save-edit-one">Save</button>
            <button class="cancel-btn">Cancel</button>
            <button class="help-btn">Help</button>
        </div>
    </div>

    <script>
        $(document).ready(function () {
            let currentTableId = 'table-one';
            let currentModelName = 'ExcelEntry';

            // Store all client options for both dropdowns
            const allClientOptions = $('#add-client-id').html();
            const allEditClientOptions = $('#edit-client-id').html();

            // Function to filter clients based on institute selection
            function filterClients(instituteId, targetSelect, allOptions) {
                if (!instituteId) {
                    // Show only the default option if no institute selected
                    targetSelect.html('<option value="">Select Institute first</option>');
                    targetSelect.prop('disabled', true);
                } else {
                    // Restore all options first
                    targetSelect.html(allOptions);
                    
                    // Enable the dropdown
                    targetSelect.prop('disabled', false);
                    
                    // Hide all options first
                    targetSelect.find('option').hide();
                    
                    // Always show the "Select Client" option
                    targetSelect.find('option[value=""]').show().text('Select Client');
                    
                    // Show only clients from selected institute
                    const clientsFromInstitute = targetSelect.find(`option[data-institute="${instituteId}"]`);
                    if (clientsFromInstitute.length > 0) {
                        clientsFromInstitute.show();
                    } else {
                        targetSelect.html('<option value="">No clients found for this institute</option>');
                    }
                    
                    // Reset selection
                    targetSelect.val('');
                }
            }

            // Function to calculate all derived values
            function calculateDerivedValues(prefix) {
                const pressure = parseFloat($(`#${prefix}-pressure`).val()) || 0;
                const purity = parseFloat($(`#${prefix}-purity`).val()) || 0;
                const druckkorrektur = parseFloat($(`#${prefix}-druckkorrektur`).val()) || 1.0;
                const lheZus = parseFloat($(`#${prefix}-lhe-zus`).val()) || 0;
                const gesFlaschInhalt = parseFloat($(`#${prefix}-constant-300`).val()) || 300.0;
                
                // Calculate Korrig. Druck
                const korrigDruck = pressure * druckkorrektur / ((pressure * druckkorrektur) / 2000 + 1);
                $(`#${prefix}-korrig-druck`).val(korrigDruck.toFixed(2));

                // Calculate Nm³
                const nm3 = (gesFlaschInhalt * korrigDruck) / 1000;
                $(`#${prefix}-nm3`).val(nm3.toFixed(2));

                // Calculate L-He
                const lhe = nm3 * (1 - purity/100) / 0.75;
                $(`#${prefix}-lhe`).val(lhe.toFixed(2));

                // Calculate L-He ges.
                const lheGes = lheZus + lhe;
                $(`#${prefix}-lhe-ges`).val(lheGes.toFixed(2));
            }

            // Institute change handler for add popup
            $('#add-institute-id').on('change', function() {
                const instituteId = $(this).val();
                filterClients(instituteId, $('#add-client-id'), allClientOptions);
            });

            // Institute change handler for edit popup
            $('#edit-institute-id').on('change', function() {
                const instituteId = $(this).val();
                filterClients(instituteId, $('#edit-client-id'), allEditClientOptions);
            });

            // Add event listeners for calculation triggers in add popup
            $('#add-pressure, #add-purity, #add-druckkorrektur, #add-lhe-zus, #add-constant-300')
            .on('input change', function() {
                calculateDerivedValues('add');
            });
            // Add event listeners for calculation triggers in edit popup
            $('#edit-pressure, #edit-purity, #edit-druckkorrektur, #edit-lhe-zus, #edit-constant-300')
            .on('input change', function() {
                calculateDerivedValues('edit');
            });

            $('#add-row-one').on('click', function () {
                // Reset form
                $('#add-institute-id').val('');
                $('#add-client-id').html('<option value="">Select Institute first</option>');
                $('#add-client-id').prop('disabled', true);
                $('#add-date').val('');
                $('#add-pressure').val('');
                $('#add-purity').val('0.1');
                $('#add-druckkorrektur').val('1.0');
                $('#add-lhe-zus').val('0.0');
                $('#add-constant-300').val('604.00');
                $('#add-korrig-druck').val('');
                $('#add-nm3').val('');
                $('#add-lhe').val('');
                $('#add-lhe-ges').val('');
                
                $('#add-popup-one').fadeIn();
            });

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

            // Add
            $('#save-add-one').on('click', function() {
                const clientId = $('#add-client-id').val();
                const instituteId = $('#add-institute-id').val();
                
                if (!instituteId) {
                    alert('Please select an institute');
                    return;
                }
                
                if (!clientId) {
                    alert('Please select a client');
                    return;
                }

                // Validate date first
                let dateInput = $('#add-date').val();
                if (!dateInput) {
                    alert('Please select a date');
                    return;
                }

                // Validate numbers
                let pressure = parseFloat($('#add-pressure').val());
                let purity = parseFloat($('#add-purity').val());
                let druckkorrektur = parseFloat($('#add-druckkorrektur').val()) || 1.0;
                let lheZus = parseFloat($('#add-lhe-zus').val()) || 0;
                let gesFlaschInhalt = parseFloat($('#add-constant-300').val()) || 300.0;
                
                if (isNaN(pressure) || pressure < 0) {
                    alert('Please enter a valid pressure value');
                    return;
                }
                
                if (isNaN(purity) || purity < 0 || purity > 100) {
                    alert('Please enter a valid purity value (0-100)');
                    return;
                }

                if (isNaN(druckkorrektur) || druckkorrektur < 0) {
                    alert('Please enter a valid Druckkorrektur value');
                    return;
                }

                if (isNaN(lheZus) || lheZus < 0) {
                    alert('Please enter a valid L-He zus. value');
                    return;
                }

                // Calculate final values
                calculateDerivedValues('add');
                
                const korrigDruck = parseFloat($('#add-korrig-druck').val()) || 0;
                const nm3 = parseFloat($('#add-nm3').val()) || 0;
                const lhe = parseFloat($('#add-lhe').val()) || 0;
                const lheGes = parseFloat($('#add-lhe-ges').val()) || 0;

                // Prepare the form data
                let formData = {
                    'client_id': clientId,
                    'date': dateInput,
                    'pressure': pressure,
                    'purity': purity,
                    'druckkorrektur': druckkorrektur,
                    'lhe_zus': lheZus,
                    'constant_300': gesFlaschInhalt,
                    'korrig_druck': korrigDruck,
                    'nm3': nm3,
                    'lhe': lhe,
                    'lhe_ges': lheGes,
                    'csrfmiddlewaretoken': '{{ csrf_token }}'
                };

                $.ajax({
                    url: '/add-entry/ExcelEntry/',
                    method: 'POST',
                    data: formData,
                    success: function(response) {
                        if (response.status === 'success') {
                            // Add the new row to the table
                            let newRow = `
                                <tr data-id="${response.id}">
                                    <td>${$('#table-one tbody tr').length + 1}</td>
                                    <td>${response.id}</td>
                                    <td>${response.institute_name || ''}</td>
                                    <td>${response.client_name}</td>
                                    <td>${response.pressure}</td>
                                    <td>${response.purity}</td>
                                    <td>${response.druckkorrektur}</td>
                                    <td>${response.constant_300}</td>
                                    <td>${response.korrig_druck}</td>
                                    <td>${response.nm3}</td>
                                    <td>${response.lhe}</td>
                                    <td>${response.lhe_zus}</td>
                                    <td>${response.lhe_ges}</td>
                                    <td>${response.date || ''}</td>
                                    <td>${response.month || ''}</td>
                                    <td class="actions">
                                        <button class="edit-btn-one">Edit</button>
                                        <button class="delete-btn-one">Delete</button>
                                    </td>
                                </tr>
                            `;
                            $('#table-one tbody').append(newRow);
                            $('#add-popup-one').fadeOut();
                        } else {
                            alert('Error: ' + (response.message || 'Failed to add entry'));
                        }
                    },
                    error: function(xhr) {
                        alert('Error: ' + (xhr.responseJSON?.message || 'Server error'));
                    }
                });
            });

            // Edit
            $(document).on('click', '.edit-btn-one', function() {
                let row = $(this).closest('tr');
                const entryId = row.data('id');
                const clientName = row.find('td:eq(2)').text().trim();
                
                // Reset edit form first
                $('#edit-institute-id').val('');
                $('#edit-client-id').html(allEditClientOptions);
                $('#edit-client-id').prop('disabled', true);
                
                // Find the client and set the institute
                const clientOptions = $('#edit-client-id option');
                let foundInstituteId = '';
                let foundClientId = '';
                
                clientOptions.each(function() {
                    if ($(this).text() === clientName) {
                        foundInstituteId = $(this).data('institute');
                        foundClientId = $(this).val();
                        return false; // break the loop
                    }
                });
                
                if (foundInstituteId) {
                    $('#edit-institute-id').val(foundInstituteId);
                    filterClients(foundInstituteId, $('#edit-client-id'), allEditClientOptions);
                    $('#edit-client-id').val(foundClientId);
                }
                
                // Set other fields
                $('#edit-id').val(entryId);
                
                // Handle date - ensure it's in correct format
                let dateText = row.find('td:eq(13)').text().trim();
                if (dateText) {
                    $('#edit-date').val(dateText);
                }
                
                $('#edit-pressure').val(row.find('td:eq(4)').text().trim());
                $('#edit-purity').val(row.find('td:eq(5)').text().trim());
                $('#edit-druckkorrektur').val(row.find('td:eq(6)').text().trim());
                $('#edit-lhe-zus').val(row.find('td:eq(11)').text().trim());
                $('#edit-constant-300').val(row.find('td:eq(7)').text().trim());
                $('#edit-korrig-druck').val(row.find('td:eq(8)').text().trim());
                $('#edit-nm3').val(row.find('td:eq(9)').text().trim());
                $('#edit-lhe').val(row.find('td:eq(10)').text().trim());
                $('#edit-lhe-ges').val(row.find('td:eq(12)').text().trim());
                
                $('#edit-popup-one').fadeIn();
            });

            // Update the save-edit-one handler
            $('#save-edit-one').on('click', function() {
                const clientId = $('#edit-client-id').val();
                const instituteId = $('#edit-institute-id').val();
                
                if (!instituteId) {
                    alert('Please select an institute');
                    return;
                }
                
                if (!clientId) {
                    alert('Please select a client');
                    return;
                }

                // Validate numbers
                let pressure = parseFloat($('#edit-pressure').val());
                let purity = parseFloat($('#edit-purity').val());
                let druckkorrektur = parseFloat($('#edit-druckkorrektur').val()) || 1.0;
                let lheZus = parseFloat($('#edit-lhe-zus').val()) || 0;
                let gesFlaschInhalt = parseFloat($('#edit-constant-300').val()) || 300.0;
                
                if (isNaN(pressure) || pressure < 0) {
                    alert('Please enter a valid pressure value');
                    return;
                }
                
                if (isNaN(purity) || purity < 0 || purity > 100) {
                    alert('Please enter a valid purity value (0-100)');
                    return;
                }

                if (isNaN(druckkorrektur) || druckkorrektur < 0) {
                    alert('Please enter a valid Druckkorrektur value');
                    return;
                }

                if (isNaN(lheZus) || lheZus < 0) {
                    alert('Please enter a valid L-He zus. value');
                    return;
                }

                // Calculate final values
                calculateDerivedValues('edit');
                
                const korrigDruck = parseFloat($('#edit-korrig-druck').val()) || 0;
                const nm3 = parseFloat($('#edit-nm3').val()) || 0;
                const lhe = parseFloat($('#edit-lhe').val()) || 0;
                const lheGes = parseFloat($('#edit-lhe-ges').val()) || 0;

                let formData = {
                    'id': $('#edit-id').val(),
                    'client_id': clientId,
                    'date': $('#edit-date').val(),
                    'pressure': pressure,
                    'purity': purity,
                    'druckkorrektur': druckkorrektur,
                    'lhe_zus': lheZus,
                    'constant_300': gesFlaschInhalt,
                    'korrig_druck': korrigDruck,
                    'nm3': nm3,
                    'lhe': lhe,
                    'lhe_ges': lheGes,
                    'csrfmiddlewaretoken': '{{ csrf_token }}'
                };

                // Validate inputs
                if (!formData.date) {
                    alert('Please select a date');
                    return;
                }

                $.ajax({
                    url: '/update-entry/ExcelEntry/',
                    method: 'POST',
                    data: formData,
                    success: function(response) {
                        if (response.status === 'success') {
                            let row = $(`tr[data-id="${response.id}"]`);
                            row.find('td:eq(2)').text(response.client_name);
                            row.find('td:eq(4)').text(response.pressure);
                            row.find('td:eq(5)').text(response.purity);
                            row.find('td:eq(6)').text(response.druckkorrektur);
                            row.find('td:eq(7)').text(response.constant_300);
                            row.find('td:eq(8)').text(response.korrig_druck);
                            row.find('td:eq(9)').text(response.nm3);
                            row.find('td:eq(10)').text(response.lhe);
                            row.find('td:eq(11)').text(response.lhe_zus);
                            row.find('td:eq(12)').text(response.lhe_ges);
                            row.find('td:eq(13)').text(response.date || '');
                            row.find('td:eq(14)').text(response.month || '');
                            $('#edit-popup-one').fadeOut();
                        } else {
                            alert('Error: ' + (response.message || 'Failed to update entry'));
                        }
                    },
                    error: function(xhr) {
                        alert('Error: ' + (xhr.responseJSON?.message || 'Server error'));
                    }
                });
            });

            // Delete
            $(document).on('click', '.delete-btn-one', function () {
                let row = $(this).closest('tr');
                let id = row.data('id');

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

                $.ajax({
                    url: `/delete-entry/${currentModelName}/`,
                    method: 'POST',
                    data: {
                        'id': id,
                        'csrfmiddlewaretoken': '{{ csrf_token }}'
                    },
                    success: function (response) {
                        if (response.status === 'success') {
                            row.fadeOut(300, function () { $(this).remove(); });
                        } else {
                            alert('Failed to delete entry: ' + response.message);
                        }
                    },
                    error: function () {
                        alert('Failed to delete entry. Please try again.');
                    }
                });
            });
        });
    </script>

</body>
</html>