<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Helium Output</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;
        }
        .container {
            display: flex;
            justify-content: space-between;
            gap: 20px;
        }
        .table-container {
            width: 48%;
            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%;
            border-collapse: collapse;
            margin-top: 20px;
        }
        th, td {
            padding: 12px;
            text-align: left;
            border-bottom: 1px solid #ddd;
        }
        th {
            background-color: #007bff;
            color: white;
            font-weight: bold;
        }
        tr:hover {
            background-color: #f1f1f1;
        }
        .actions button {
            margin: 2px;
            padding: 5px 10px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
        }
        .edit-btn-two {
            background-color: #28a745;
            color: white;
        }
        .delete-btn-two {
            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 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;
        }
        .checkbox-container {
            display: flex;
            align-items: center;
            margin-bottom: 15px;
        }
        .checkbox-container input[type="checkbox"] {
            width: auto;
            margin-right: 10px;
            margin-bottom: 0;
        }
        .input-with-label {
            display: flex;
            align-items: center;
            margin-bottom: 15px;
        }
        .input-with-label label {
            width: 120px;
            margin-bottom: 0;
            margin-right: 10px;
        }
        .input-with-label input {
            flex: 1;
            margin-bottom: 0;
        }
        .number-input-container {
            display: flex;
            align-items: center;
            margin-bottom: 15px;
        }
        .number-input-container label {
            width: 120px;
            margin-bottom: 0;
            margin-right: 10px;
            font-weight: bold;
        }
        .number-input-container input {
            width: 80px;
            margin-bottom: 0;
        }
    </style>
</head>
<body>

    <div class="d-flex justify-content-start mb-2">
        <!-- "Go to Clients" button at top-left -->
        <a href="{% url 'clients_list' %}" class="btn btn-outline-primary">
            &#8678; Go to Clients
        </a>
    </div>

    <h2>LHe Dewar Output</h2>

    <div class="table-container">
        <button class="add-row-btn" id="add-row-two">Add Output</button>
        <table id="table-two">
        <thead>
            <tr>
                <th>#</th>
                <th>ID</th>
                <th>Institute</th>
                <th>Client</th>
                <th>Date</th>
                <th>Warm</th>
                <th>LHe Delivery</th>
                <th>Vor</th>
                <th>Nach</th>
                <th>LHe Output</th>
                <th>Notes</th>
                <th>Actions</th>
            </tr>
        </thead>
        <tbody>
            {% for entry in entries_table2 %}
            <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.date }}</td>
                <td>{{ entry.is_warm|yesno:"Yes,No" }}</td>
                <td>{{ entry.lhe_delivery }}</td>
                <td>{% if entry.vor is not None %}{{ entry.vor|floatformat:1 }}{% endif %}</td>
                <td>{% if entry.nach is not None %}{{ entry.nach|floatformat:1 }}{% endif %}</td>
                <td>{% if entry.lhe_output is not None %}{{ entry.lhe_output|floatformat:1 }}{% endif %}</td>
                <td>{{ entry.notes }}</td>
                <td class="actions">
                    <button class="edit-btn-two">Edit</button>
                    <button class="delete-btn-two">Delete</button>
                </td>
            </tr>
            {% endfor %}
        </tbody>
    </table>
    </div>

    <!-- Add Entry Popup -->
    <div id="add-popup-two" class="popup">
    <span class="close-btn">&times;</span>
    <h3>LHe Dewar Output</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 (will be populated based on institute) -->
    <label for="add-client-id">Client:</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">
    
    <!-- Changed from checkbox to number input -->
    <div class="number-input-container">
        <label for="add-is-warm">Warm:</label>
        <input type="number" id="add-is-warm" min="0" max="1" step="1" value="0">
    </div>
    
    <div class="input-with-label">
        <label for="add-lhe-delivery">LHe Anlieferung:</label>
        <input type="text" id="add-lhe-delivery" placeholder="Enter delivery amount">
    </div>
    
    <div class="input-with-label">
        <label for="add-vor">Vor:</label>
        <input type="number" id="add-vor" step="0.1">
    </div>

    <div class="input-with-label">
        <label for="add-nach">Nach:</label>
        <input type="number" id="add-nach" step="0.1">
    </div>

    <div class="input-with-label">
        <label for="add-lhe-output">LHe Ausgabe:</label>
        <input type="number" id="add-lhe-output" readonly>
    </div>
    
    <label for="add-notes">Notes:</label>
    <textarea id="add-notes" placeholder="Additional notes"></textarea>
    
    <div class="popup-buttons">
        <button class="save-btn" id="save-add-two">Save</button>
        <button class="cancel-btn" id="cancel-add-two">Cancel</button>
        <button class="help-btn">Help</button>
    </div>
</div>

    <!-- Edit Entry Popup -->
    <div id="edit-popup-two" class="popup">
    <span class="close-btn">&times;</span>
    <h3>LHe Dewar Output</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 (will be populated based on institute) -->
    <label for="edit-client-id">Client:</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">
    
    <!-- Changed from checkbox to number input -->
    <div class="number-input-container">
        <label for="edit-is-warm">Warm:</label>
        <input type="number" id="edit-is-warm" min="0" max="1" step="1" value="0">
    </div>
    
    <div class="input-with-label">
        <label for="edit-lhe-delivery">LHe Anlieferung:</label>
        <input type="text" id="edit-lhe-delivery" placeholder="Enter delivery amount">
    </div>
    
    <div class="input-with-label">
        <label for="edit-vor">Vor:</label>
        <input type="number" id="edit-vor" step="0.1">
    </div>

    <div class="input-with-label">
        <label for="edit-nach">Nach:</label>
        <input type="number" id="edit-nach" step="0.1">
    </div>

    <div class="input-with-label">
        <label for="edit-lhe-output">LHe Ausgabe:</label>
        <input type="number" id="edit-lhe-output" readonly>
    </div>

    
    <label for="edit-notes">Notes:</label>
    <textarea id="edit-notes" placeholder="Additional notes"></textarea>
    
    <div class="popup-buttons">
        <button class="save-btn" id="save-edit-two">Save</button>
        <button class="cancel-btn" id="cancel-edit-two">Cancel</button>
        <button class="help-btn">Help</button>
    </div>
</div>

    
    <script>
        $(document).ready(function () {
            // Store all client options for both dropdowns
            const allClientOptions = $('#add-client-id').html();
            const allEditClientOptions = $('#edit-client-id').html();
            function calculateAddOutput() {
                let vor = parseFloat($('#add-vor').val()) || 0;
                let nach = parseFloat($('#add-nach').val()) || 0;

                let output = nach - vor;

                if (output < 0) output = 0;

                $('#add-lhe-output').val(output.toFixed(1));
            }

            $('#add-vor, #add-nach').on('input', calculateAddOutput);
            function calculateEditOutput() {
                let vor = parseFloat($('#edit-vor').val()) || 0;
                let nach = parseFloat($('#edit-nach').val()) || 0;

                let output = nach - vor;

                if (output < 0) output = 0;

                $('#edit-lhe-output').val(output.toFixed(1));
            }

            $('#edit-vor, #edit-nach').on('input', calculateEditOutput);
            // 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 handle warm field change and control LHe Anlieferung field
            function handleWarmFieldChange(warmField, deliveryField) {
                const warmValue = parseInt(warmField.val());
                
                // Ensure value is only 0 or 1
                if (warmValue !== 0 && warmValue !== 1) {
                    warmField.val(0);
                }
                
                // If warm is 1, set delivery to 0 and disable it
                if (parseInt(warmField.val()) === 1) {
                    deliveryField.val('0');
                    deliveryField.prop('disabled', true);
                    deliveryField.prop('readonly', true);
                } else {
                    deliveryField.prop('disabled', false);
                    deliveryField.prop('readonly', false);
                }
            }

            // Initialize warm field handlers for add popup
            $('#add-is-warm').on('change input', function() {
                handleWarmFieldChange($(this), $('#add-lhe-delivery'));
            });
            
            // Initialize warm field handlers for edit popup
            $('#edit-is-warm').on('change input', function() {
                handleWarmFieldChange($(this), $('#edit-lhe-delivery'));
            });

            // 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);
            });

            // Open Add Popup for Table 2
            $('#add-row-two').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-is-warm').val('0');
                $('#add-lhe-delivery').val('');
                $('#add-lhe-delivery').prop('disabled', false);
                $('#add-lhe-delivery').prop('readonly', false);
                $('#add-lhe-output').val('');
                $('#add-notes').val('');
                
                // Apply initial warm field logic
                handleWarmFieldChange($('#add-is-warm'), $('#add-lhe-delivery'));
                
                $('#add-popup-two').fadeIn();
            });

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

            // Save Add Entry
            $('#save-add-two').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 warm field
                const warmValue = parseInt($('#add-is-warm').val());
                if (warmValue !== 0 && warmValue !== 1) {
                    alert('Warm field must be 0 or 1');
                    return;
                }

                let formData = {
                'client_id': clientId,
                'date': $('#add-date').val(),
                'is_warm': warmValue,
                'lhe_delivery': $('#add-lhe-delivery').val(),

                // ✅ NEW: send vor/nach to backend
                'vor': $('#add-vor').val(),
                'nach': $('#add-nach').val(),

                // ❌ DO NOT send lhe_output anymore (backend should compute it)
                // 'lhe_output': $('#add-lhe-output').val(),

                'notes': $('#add-notes').val(),
                'csrfmiddlewaretoken': '{{ csrf_token }}'
                };
                // Validate date format
                if (!formData.date) {
                    alert('Please select a date');
                    return;
                }

                // Validate LHe Output is a number
               const vorVal = $('#add-vor').val();
                const nachVal = $('#add-nach').val();

                if (vorVal !== "" && isNaN(parseFloat(vorVal))) {
                alert('Vor must be a valid number');
                return;
                }
                if (nachVal !== "" && isNaN(parseFloat(nachVal))) {
                alert('Nach must be a valid number');
                return;
                }

                $.ajax({
                    url: '/add-entry/SecondTableEntry/',
                    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-two tbody tr').length + 1}</td>
                                <td>${response.id}</td>
                                <td>${response.institute_name || ''}</td>
                                <td>${response.client_name}</td>
                                <td>${response.date || ''}</td>
                                <td>${response.is_warm ? 'Yes' : 'No'}</td>
                                <td>${response.lhe_delivery || ''}</td>
                                <td>${response.vor ?? ''}</td>
                                <td>${response.nach ?? ''}</td>
                                <td>${response.lhe_output ?? ''}</td>
                                <td>${response.notes || ''}</td>
                                <td class="actions">
                                    <button class="edit-btn-two">Edit</button>
                                    <button class="delete-btn-two">Delete</button>
                                </td>
                            </tr>
                            `;

                            $('#table-two tbody').append(newRow);
                            $('#add-popup-two').fadeOut();
                        } else {
                            alert('Error: ' + (response.message || 'Failed to add entry'));
                        }
                    },
                    error: function(xhr) {
                        alert('Error: ' + (xhr.responseJSON?.message || 'Server error'));
                    }
                });
            });

            // Open Edit Popup
            $(document).on('click', '.edit-btn-two', 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);
                $('#edit-date').val(row.find('td:eq(4)').text().trim());

                const warmValue = row.find('td:eq(5)').text().trim() === 'Yes' ? 1 : 0;
                $('#edit-is-warm').val(warmValue);

                $('#edit-lhe-delivery').val(row.find('td:eq(6)').text().trim());
                $('#edit-vor').val(row.find('td:eq(7)').text().trim());
                $('#edit-nach').val(row.find('td:eq(8)').text().trim());
                $('#edit-lhe-output').val(row.find('td:eq(9)').text().trim());
                $('#edit-notes').val(row.find('td:eq(10)').text().trim());
                
                // Apply warm field logic
                handleWarmFieldChange($('#edit-is-warm'), $('#edit-lhe-delivery'));
                
                $('#edit-popup-two').fadeIn();
            });

            // Save Edit Entry
            $('#save-edit-two').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 warm field
                const warmValue = parseInt($('#edit-is-warm').val());
                if (warmValue !== 0 && warmValue !== 1) {
                    alert('Warm field must be 0 or 1');
                    return;
                }

                let formData = {
  'id': $('#edit-id').val(),
  'client_id': clientId,
  'date': $('#edit-date').val(),
  'is_warm': warmValue,
  'lhe_delivery': $('#edit-lhe-delivery').val(),

  // ✅ NEW
  'vor': $('#edit-vor').val(),
  'nach': $('#edit-nach').val(),

  // ❌ DO NOT send lhe_output anymore
  // 'lhe_output': $('#edit-lhe-output').val(),

  'notes': $('#edit-notes').val(),
  'csrfmiddlewaretoken': '{{ csrf_token }}'
};

                // Validate inputs
                if (!formData.date) {
                    alert('Please select a date');
                    return;
                }
                if (formData.lhe_output && isNaN(parseFloat(formData.lhe_output))) {
                    alert('Please enter a valid LHe Output value');
                    return;
                }

                $.ajax({
                    url: '/update-entry/SecondTableEntry/',
                    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.institute_name || '');
                        row.find('td:eq(3)').text(response.client_name || '');
                        row.find('td:eq(4)').text(response.date || '');
                        row.find('td:eq(5)').text(response.is_warm ? 'Yes' : 'No');
                        row.find('td:eq(6)').text(response.lhe_delivery || '');
                        row.find('td:eq(7)').text(response.vor ?? '');
                        row.find('td:eq(8)').text(response.nach ?? '');
                        row.find('td:eq(9)').text(response.lhe_output ?? '');
                        row.find('td:eq(10)').text(response.notes || '');
                            $('#edit-popup-two').fadeOut();
                        } else {
                            alert('Update failed: ' + (response.message || 'Unknown error'));
                        }
                    },
                    error: function(xhr) {
                        alert('Error: ' + (xhr.responseJSON?.message || 'Server error'));
                    }
                });
            });

            // Delete Entry
            $(document).on('click', '.delete-btn-two', 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/SecondTableEntry/',
                    method: 'POST',
                    data: {
                        'id': id,
                        'csrfmiddlewaretoken': '{{ csrf_token }}'
                    },
                    success: function (response) {
                        if (response.status === 'success') {
                            row.fadeOut(300, function () { $(this).remove(); });
                        } else {
                            alert('Delete failed: ' + response.message);
                        }
                    },
                    error: function (xhr, status, error) {
                        alert('Delete failed: ' + (xhr.responseJSON?.message || 'Please try again later'));
                        console.error('Error:', error);
                    }
                });
            });
        });
    </script>
</body>
</html>