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

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

    <form method="POST" id="sales-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-4">{{ form.so_number.label_tag }} {{ form.so_number }}</div>
            <div class="col-md-4">{{ form.order_date.label_tag }} {{ form.order_date }}</div>
            <div class="col-md-4">{{ form.status.label_tag }} {{ form.status }}</div>
        </div>

        <div class="row mb-3">
            
            <div class="col-md-6">{{ form.job.label_tag }} {{ form.job }}</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">{{ form.customer.label_tag }} {{ form.customer }}</div>
            <div class="col-md-6 mb-3">
                {{ form.company_id.label_tag }}
                {{ form.company_id }}
            </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>
        </table>

        <button type="button" class="btn btn-outline-primary" id="add-row">Add Another Product</button>
        <button type="submit" class="btn btn-success">Create Sales Order</button>
        <a href="{% url 'sales_order_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 customerSelect = document.getElementById('id_customer');
    const companySelect = document.getElementById('id_company_id');

    customerSelect.addEventListener('change', function() {
        const customerId = this.value;
        console.log('customer changed to ID:', customerId); // Debug log
        
        if (!customerId) {
            console.log('No customer selected, clearing companies');
            companySelect.innerHTML = '<option value="">---------</option>';
            return;
        }

        console.log('Fetching companies for customer:', customerId);
        fetch(`/accounting/get_companies_by_customer/${customerId}/`)
            .then(response => {
                console.log('Response status:', response.status); // Debug log
                if (!response.ok) {
                    throw new Error('Network response was not ok');
                }
                return response.json();
            })
            .then(data => {
                console.log('Received data:', data); // Debug log
                companySelect.innerHTML = '<option value="">---------</option>';
                data.forEach(function(company) {
                    const option = document.createElement('option');
                    option.value = company.id;
                    option.textContent = company.company_name;
                    companySelect.appendChild(option);
                });
            })
            .catch(error => {
                console.error('Error fetching companies:', error);
                companySelect.innerHTML = '<option value="">---------</option>';
            });
    });

    // Trigger change event if customer is pre-selected (for edit forms)
    if (customerSelect.value) {
        customerSelect.dispatchEvent(new Event('change'));
    }
});



$(document).ready(function() {
    const prefix = '{{ formset.prefix }}';
    const form = $('#sales-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));
        });
    }

    // 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$="-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();
});



// // Your existing supplier change handler
// $('#id_customer').change(function() {
//     const customerId = $(this).val();
//     $.ajax({
//         url: "{% url 'load_jobs_for_salesorder' %}",
//         data: {'customer_id': customerId},
//         success: function(data) {
//             const jobSelect = $('#id_job');
//             jobSelect.empty().append('<option value="">---------</option>');
//             data.forEach(job => {
//                 jobSelect.append(`<option value="${job.id}">${job.job_title}</option>`);
//             });
//         }
//     });
// });

</script>
{% endblock %}