{% extends "base.html" %}
{% load static %}

{% block title %}Edit Purchase Order {{ po.po_number }}{% endblock %}

{% block content %}
<div class="container mt-4">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h2>Edit Purchase Order: {{ po.po_number }}</h2>
        <div>
            <a href="{% url 'purchase_order_detail' po.id %}" class="btn btn-outline-secondary">
                <i class="bi bi-arrow-left"></i> Back to Details
            </a>
        </div>
    </div>

    <form method="POST" id="po-edit-form">
        {% csrf_token %}
        
        <!-- Main PO Information -->
        <div class="card mb-4">
            <div class="card-header">
                <h5 class="mb-0">Purchase Order Information</h5>
            </div>
            <div class="card-body">
                <div class="row">
                    
                    <div class="col-md-6 mb-3">
                        <label for="{{ form.order_date.id_for_label }}" class="form-label">Order Date</label>
                        {{ form.order_date }}
                        {% if form.order_date.errors %}
                            <div class="invalid-feedback d-block">
                                {{ form.order_date.errors }}
                            </div>
                        {% endif %}
                    </div>
                    <div class="col-md-6 mb-3">
                        <label for="{{ form.status.id_for_label }}" class="form-label">Status</label>
                        {{ form.status }}
                        {% if form.status.errors %}
                            <div class="invalid-feedback d-block">
                                {{ form.status.errors }}
                            </div>
                        {% endif %}
                    </div>
                </div>
                <div class="row">
                    <div class="col-md-6 mb-3">
                        <label for="{{ form.job.id_for_label }}" class="form-label">Project</label>
                        {{ form.project }}
                        {% if form.project.errors %}
                            <div class="invalid-feedback d-block">
                                {{ form.project.errors }}
                            </div>
                        {% endif %}
                    </div>

                    <div class="col-md-6 mb-3">
                        <label for="{{ form.warehouse.id_for_label }}" class="form-label">Warehouse*</label>
                        {{ 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">
                        <label for="{{ form.supplier.id_for_label }}" class="form-label">Supplier</label>
                        {{ form.supplier }}
                        {% if form.supplier.errors %}
                            <div class="invalid-feedback d-block">
                                {{ form.supplier.errors }}
                            </div>
                        {% endif %}
                    </div>
                    
                </div>
            </div>
        </div>

        <!-- PO Items Formset -->
        <div class="card mb-4">
            
            <div class="card-body">
                {{ formset.management_form }}
                <div class="table-responsive">
                    <table class="table" id="items-table">
                        <thead>
                            <tr>
                                <th>Product</th>
                                <th>Price</th>
                                <th>Quantity</th>
                                <th>Total</th>
                                <th>Action</th>
                            </tr>
                        </thead>
                        <tbody id="formset-body">
                            {% for item_form in formset %}
                            <tr class="form-row">
                                <td>
                                    {{ item_form.product }}
                                    {% if item_form.product.errors %}
                                        <div class="invalid-feedback d-block">
                                            {{ item_form.product.errors }}
                                        </div>
                                    {% endif %}
                                </td>
                               
                                <td>
                                    {{ item_form.price }}
                                    {% if item_form.price.errors %}
                                        <div class="invalid-feedback d-block">
                                            {{ item_form.price.errors }}
                                        </div>
                                    {% endif %}
                                </td>
                                <td>
                                    {{ item_form.quantity }}
                                    {% if item_form.quantity.errors %}
                                        <div class="invalid-feedback d-block">
                                            {{ item_form.quantity.errors }}
                                        </div>
                                    {% endif %}
                                </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 item_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>
            </div>
        </div>

        <div class="d-flex justify-content-end gap-2">
            {% if po.status != 'completed' %}
            <button type="submit" class="btn btn-success">
                <i class="bi bi-save"></i> Save Changes
            </button>
            {% else %}
                <p class="text-muted">This Purchase Order is completed and cannot be edited.</p>
            {% endif %}
            <a href="{% url 'purchase_order_detail' po.id %}" class="btn btn-secondary">
                Cancel
            </a>
        </div>
    </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>
<style>
    /* Add this to your existing styles */
    select.bg-warning {
        background-color: #fff3cd !important;
        font-weight: bold;
    }
</style>
{% endblock %}