{% extends "base.html" %}
{% block content %}
<div class="container mt-4">
    <h2>Material Consumption</h2>

            <form method="post" id="purchase-order-form">
                {% csrf_token %}

                <div class="card p-4 mb-4">
                    <h5>Consumption Info</h5>
                    <div class="row">
                        {% for field in form %}
                            <div class="col-md-6 mb-3">
                                {{ field.label_tag }}
                                {{ field }}
                                {% if field.errors %}
                                    <div class="text-danger">{{ field.errors }}</div>
                                {% endif %}
                            </div>
                        {% endfor %}
                    </div>
                </div>

                <div>
                    <h5>Material Items</h5>
                    {{ formset.management_form }}

                    <table class="table table-bordered" id="items-table">
                        <thead>
                            <tr>
                                <th>Product</th>
                                <th>Quantity</th>
                                <th>Unit Price</th>
                                <th>Total</th>
                                <th>Remove</th>
                            </tr>
                        </thead>
                        <tbody id="formset-body">
                            {% for form in formset %}
                                <tr class="form-row">
                                    {% for field in form.visible_fields %}
                                    {% if field.field.widget.input_type != 'checkbox' %}
                                    
                                         <td>
                                            {{ field }}
                                            {% if field.name == "product" %}
                                                <small class="text-muted stock-info" data-stock="">Available: <span class="stock-value">—</span></small>
                                            {% endif %}
                                            {% if field.errors %}
                                                <div class="text-danger small">{{ field.errors }}</div>
                                            {% endif %}
                                        </td>
                                    {% endif %}              
                                    {% endfor %}
                                        <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>
                        <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>
                </div>
                        <hr>

                <button type="submit" class="btn btn-primary">Save</button>
                <a href="{% url 'material_consumption_list' %}" class="btn btn-secondary">Cancel</a>
            </form>
        
</div>


<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
document.addEventListener('DOMContentLoaded', function () {
    const productSelects = document.querySelectorAll('select[id$="-product"]');

    productSelects.forEach(function(select) {
        select.addEventListener('change', function () {
            const productId = this.value;
            const row = this.closest('tr');
            const stockSpan = row.querySelector('.stock-value');

            if (productId) {
                fetch(`/products/get-product-stock/?product_id=${productId}`)
                    .then(response => response.json())
                    .then(data => {
                        stockSpan.textContent = data.stock;
                    });
            } else {
                stockSpan.textContent = '—';
            }
        });

        // trigger initial stock load if value is pre-selected
        if (select.value) {
            select.dispatchEvent(new Event('change'));
        }
    });
});



// 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$="-unit_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$="-unit_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$="-unit_price"], [id$="-quantity"], #paid-amount')) {
        calculateTotalAmount();
    }
});

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

</script>
{% endblock %}

