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

{% block title %}Edit Sales Order {{ so.so_number }}{% endblock %}

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

    <form method="POST" id="so-edit-form">
        {% csrf_token %}
        
        <!-- Main PO Information -->
        <div class="card mb-4">
            <div class="card-header">
                <h5 class="mb-0">Sales Order Information</h5>
            </div>
            <div class="card-body">
                <div class="row">
                    <div class="col-md-4 mb-3">
                        <label for="{{ form.so_number.id_for_label }}" class="form-label">SO Number</label>
                        {{ form.so_number }}
                        {% if form.so_number.errors %}
                            <div class="invalid-feedback d-block">
                                {{ form.so_number.errors }}
                            </div>
                        {% endif %}
                    </div>
                    <div class="col-md-4 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-4 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">Job</label>
                        {{ form.job }}
                        {% if form.job.errors %}
                            <div class="invalid-feedback d-block">
                                {{ form.job.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.customer.id_for_label }}" class="form-label">Customer</label>
                        {{ form.customer }}
                        {% if form.customer.errors %}
                            <div class="invalid-feedback d-block">
                                {{ form.customer.errors }}
                            </div>
                        {% endif %}
                    </div>
                    <div class="col-md-6 mb-3">
                        <label for="{{ form.company_id.id_for_label }}" class="form-label">Company</label>                        
                        {{ form.company_id }}
                    </div>
                    
                </div>
            </div>
        </div>

        <!-- PO Items Formset -->
        <div class="card mb-4">
            <div class="card-header d-flex justify-content-between align-items-center">
                <h5 class="mb-0">Order Items</h5>
                <button type="button" class="btn btn-sm btn-primary" id="add-item">
                    <i class="bi bi-plus"></i> Add Item
                </button>
            </div>
            <div class="card-body">
                {{ formset.management_form }}
                <div class="table-responsive">
                    <table class="table" id="items-table">
                        <thead>
                            <tr>
                                <th>Product</th>
                                <th>Description</th>
                                <th>Price</th>
                                <th>Quantity</th>
                                <th>Total</th>
                                <th>Action</th>
                            </tr>
                        </thead>
                        <tbody id="items-body">
                            {% for item_form in formset %}
                            <tr class="item-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.description }}
                                    {% if item_form.description.errors %}
                                        <div class="invalid-feedback d-block">
                                            {{ item_form.description.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" readonly 
                                           value="{% if item_form.price.value and item_form.quantity.value %}{{ item_form.price.value|floatformat:2 }} × {{ item_form.quantity.value }} = {{ item_form.total.value|floatformat:2|default:'0.00' }}{% else %}0.00{% endif %}">
                                </td>
                                <td class="align-middle">
                                    {% if item_form.instance.pk %}
                                        {{ item_form.DELETE }}
                                        <label for="{{ item_form.DELETE.id_for_label }}" class="form-check-label">
                                            <i class="bi bi-trash text-danger"></i>
                                        </label>
                                    {% endif %}
                                    {% for hidden in item_form.hidden_fields %}
                                        {{ hidden }}
                                    {% endfor %}
                                </td>
                            </tr>
                            {% endfor %}
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <div class="d-flex justify-content-end gap-2">
            {% if so.status != 'completed' %}
            <button type="submit" class="btn btn-success">
                <i class="bi bi-save"></i> Save Changes
            </button>
            {% else %}
                <p class="text-muted">This Sales Order is completed and cannot be edited.</p>
            {% endif %}
            <a href="{% url 'sales_order_detail' so.id %}" class="btn btn-secondary">
                <i class="bi bi-arrow-left"></i> Cancel
            </a>
        </div>
    </form>
</div>
{% endblock %}

{% block javascript %}
<script src="{% static 'js/sales_order_form.js' %}"></script>
<script>
document.addEventListener('DOMContentLoaded', function() {
    // Calculate totals when price or quantity changes
    $('#items-body').on('input', '[id$="-price"], [id$="-quantity"]', function() {
        const row = $(this).closest('.item-row');
        const price = parseFloat(row.find('[id$="-price"]').val()) || 0;
        const quantity = parseFloat(row.find('[id$="-quantity"]').val()) || 0;
        const total = (price * quantity).toFixed(2);
        row.find('.total').val(`${price.toFixed(2)} × ${quantity} = ${total}`);
    });

    // Add new item row
    $('#add-item').click(function() {
        const formCount = $('#id_items-TOTAL_FORMS').val();
        const newRow = $('.item-row:first').clone(true);
        
        // Update all IDs/names
        newRow.find(':input').each(function() {
            const name = $(this).attr('name').replace(/-\d+-/, '-' + formCount + '-');
            const id = $(this).attr('id').replace(/-\d+-/, '-' + formCount + '-');
            $(this).attr({
                'name': name,
                'id': id
            }).val('').removeAttr('checked');
        });
        
        // Clear values
        newRow.find('[id$="-product"]').val('');
        newRow.find('[id$="-description"]').val('');
        newRow.find('[id$="-price"]').val('0.00');
        newRow.find('[id$="-quantity"]').val('1');
        newRow.find('.total').val('0.00');
        newRow.find('[id$="-DELETE"]').prop('checked', false);
        
        // Add to table
        $('#items-body').append(newRow);
        $('#id_items-TOTAL_FORMS').val(parseInt(formCount) + 1);
    });

    // Initialize totals
    $('[id$="-price"], [id$="-quantity"]').trigger('input');
});

$('#items-body').on('change', '[id$="-product"]', function() {
    const productId = $(this).val();
    const row = $(this).closest('.item-row');
    
    if (productId) {
        $.get(`/api/product-stock/${productId}/`, function(data) {
            row.find('.stock-info').remove();
            row.append(`
                <div class="stock-info text-muted small">
                    Current stock: ${data.stock}
                </div>
            `);
        });
    }
});
</script>
{% endblock %}