{% extends "base.html" %}
{% block title %}Create Purchase Order{% endblock %}

{% block content %}
<div class="container mt-4">
    <h2>Create Purchase Order</h2>

    <form method="POST" id="purchase-order-form">
        {% csrf_token %}
        <!-- Render ALL management form fields -->
        {{ formset.management_form }}
        
        <!-- Your existing form fields -->
        <div class="row mb-3">
            <div class="col-md-6">{{ form.order_date.label_tag }} {{ form.order_date }}</div>
            <div class="col-md-6">{{ form.status.label_tag }} {{ form.status }}</div>
        </div>

        <div class="row mb-3">
            
          
            <div class="col-md-6 mb-3">{{ form.project.label_tag }} {{ form.project  }}</div>
            <div class="col-md-6 mb-3">
                {{ form.warehouse.label_tag }}
                {{ form.warehouse }}
                {% if form.warehouse.errors %}
                    <div class="invalid-feedback d-block">
                        {{ form.warehouse.errors }}
                    </div>
                {% endif %}
            </div>
            <div class="col-md-6 mb-3">{{ form.supplier.label_tag }} {{ form.supplier }}</div>
            <div class="col-md-6 mb-3">
              
            </div>
        </div>

        <hr>
        
        <h4>Order Items</h4>
        <table class="table table-bordered" id="items-table">
            <thead>
                <tr>
                    <th>Product</th>
                    <th>Price</th>
                    <th>Quantity</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.price }}</td>
                    <td>{{ form.quantity }}</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>
                    <!-- Include all hidden fields -->
                    {% for hidden in form.hidden_fields %}
                        {{ hidden }}
                    {% endfor %}
                </tr>
                {% endfor %}
            </tbody>
           <tfoot class="table-light">
                <tr>
                    
                    <td colspan="3" class="text-end"><strong>Grand Total:</strong></td>
                    <td><input type="text" class="form-control" id="total-amount" readonly value="0.00"></td>
                </tr>
            </tfoot>
        </table>
        <button type="button" class="btn btn-outline-primary" id="add-row">Add Another Product</button>

        <hr>
       <button type="submit" class="btn btn-success">Create Purchase Order</button>
        <a href="{% url 'purchase_order_list' %}" class="btn btn-secondary">Cancel</a>
    </form>
</div>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>

// Function to calculate total amount
$(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$="-price"]').val()) || 0;
            const quantity = parseFloat(row.find('[id$="-quantity"]').val()) || 0;
            row.find('.total-field').val((price * quantity).toFixed(2));
        });
        calculateTotalAmount();
    }

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

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

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

function calculateTotalAmount() {
    let total = 0;
    document.querySelectorAll('.form-row').forEach(row => {
        // const price = parseFloat(row.querySelector('[id$="-price"]').value) || 0;
        // const qty = parseFloat(row.querySelector('[id$="-quantity"]').value) || 0;
        total += parseFloat(row.querySelector('.total-field').value) || 0;
    });

    // const paid = parseFloat(document.getElementById('paid-amount').value) || 0;
    // const remaining = total - paid;

    document.getElementById('total-amount').value = total.toFixed(2);
    // document.getElementById('remaining-amount').value = remaining.toFixed(2);
}

// Bind to product price and quantity changes
document.addEventListener('input', function (e) {
    if (e.target.matches('[id$="-price"], [id$="-quantity"], #paid-amount')) {
        calculateTotalAmount();
    }
});

// Also call it on load to initialize values
calculateTotalAmount();




</script>
{% endblock %}