{% extends "base.html" %}

{% load static %}

{% block content %}

<div class="container mt-5">
  <h2 class="mb-4">Create Disassembly Process</h2>

  <form method="post"  id="purchase-order-form" novalidate>
    {% csrf_token %}
    {{ formset.management_form }}
    <div class="row mb-3">
      <div class="col-md-4">
        <label for="id_scrap_engine" class="form-label">Scrap Product*</label>
        {{ form.scrap_engine }}
      </div>
      <div class="col-md-4">
        <label for="id_quantity_used" class="form-label">Quantity Used*</label>
        {{ form.quantity_used }}
      </div>
      <div class="col-md-4">
        <label for="id_processing_cost" class="form-label">Processing Cost</label>
        {{ form.processing_cost }}
      </div>
    </div>

    <div class="row mb-4">
      <div class="col-md-4">
        <label for="id_job" class="form-label">Job (optional)</label>
        {{ form.job }}
      </div>
    </div>

    <hr>
    <h5>Finished Products</h5>

    

    <table class="table table-bordered" id="items-table">
      <thead >
        <tr>
          <th>Product</th>
          <th>Quantity</th>
          <th>Price</th>
          <th>Total</th>
          <th>Remove</th>
        </tr>
      </thead>
      <tbody id="formset-body">
        {% for form in formset %}
        <tr  class="form-row">
          <td>{{ form.product }}</td>
          <td>{{ form.quantity }}</td>
          <td>{{ form.cost_allocated }}</td>
          <td><input type="text" class="form-control total-field" readonly></td>
          <td><button type="button" class="btn btn-danger btn-sm remove-row">×</button></td>
          {% for hidden in form.hidden_fields %}
                        {{ hidden }}
                    {% endfor %}
        </tr>
        {% endfor %}
      </tbody>
    </table>

    <div class="d-flex gap-2 mt-3">
      <button type="button" id="add-row" class="btn btn-outline-primary">Add Another Product</button>
      <button type="submit" class="btn btn-success">Create Disassembly</button>
      <a href="{% url 'disassembly_list' %}" class="btn btn-secondary">Cancel</a>
    </div>
  </form>

</div>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
  // document.addEventListener("DOMContentLoaded", function () {
  //   document.getElementById("add-row").addEventListener("click", function () {
  //     let formIdx = document.querySelectorAll("#product-items tr").length;
  //     let emptyForm = "{{ formset.empty_form.as_table|escapejs }}".replace(/__prefix__/g, formIdx);
  //     const row = document.createElement('tr');
  //     row.innerHTML = emptyForm;
  //     document.querySelector("#product-items").appendChild(row);
  //     document.querySelector('#id_' + formIdx + '-DELETE')?.closest('td')?.remove();  // Hide delete checkbox
  //   });

  //   document.addEventListener("click", function (e) {
  //     if (e.target.classList.contains("remove-row")) {
  //       e.target.closest("tr").remove();
  //     }
  //   });
  // });

  $(document).ready(function() {
    const prefix = '{{ formset.prefix }}';
    const form = $('#purchase-order-form');
    const formsetBody = $('#formset-body');
    const totalForms = $('#id_' + prefix + '-TOTAL_FORMS');
    const initialForms = $('#id_' + prefix + '-INITIAL_FORMS');
    const addRowBtn = $('#add-row');
    
    // Function to update total amounts
    function updateTotals() {
        $('.form-row').each(function() {
            const row = $(this);
            const price = parseFloat(row.find('[id$="-cost_allocated"]').val()) || 0;
            const quantity = parseFloat(row.find('[id$="-quantity"]').val()) || 0;
            row.find('.total-field').val((price * quantity).toFixed(2));
        });
        
    }

    // Add new row
    addRowBtn.click(function() {
        const formCount = parseInt(totalForms.val());
        const newRow = $('.form-row:first').clone(true);
        
        // Update all input names/ids
        newRow.find(':input').each(function() {
            const elem = $(this);
            const name = elem.attr('name');
            if (!name) return;
            
            const newName = name.replace(/-\d+-/, '-' + formCount + '-');
            elem.attr({
                'name': newName,
                'id': 'id_' + newName
            }).val('').removeAttr('checked');
        });
        
        // Clear values
        newRow.find('input[type="number"], input[type="text"]').not('.total-field').val('');
        newRow.find('.total-field').val('0.00');
        newRow.find('select').prop('selectedIndex', 0);
        
        formsetBody.append(newRow);
        totalForms.val(formCount + 1);
        updateTotals();
        
    });

    // Remove row
    $(document).on('click', '.remove-row', function() {
        const row = $(this).closest('.form-row');
        const rows = $('.form-row');
        if (rows.length > 1) {
            row.remove();
            totalForms.val(rows.length - 1);
            
            // Reindex remaining forms
            $('.form-row').each(function(i) {
                $(this).find(':input').each(function() {
                    const elem = $(this);
                    const name = elem.attr('name');
                    if (!name) return;
                    
                    const newName = name.replace(/-\d+-/, '-' + i + '-');
                    elem.attr({
                        'name': newName,
                        'id': 'id_' + newName
                    });
                });
            });
            updateTotals();
            
        }
    });

    // Update totals when values change
    $(document).on('input', '[id$="-cost_allocated"], [id$="-quantity"]', updateTotals);
    
    // Form submission handler to ensure management form is correct
    form.on('submit', function() {
        totalForms.val($('.form-row').length);
    });
    
    // Initial calculation
    updateTotals();
    
});
</script>
{% endblock %}

