/**
 * Sales Orders Form JavaScript
 * Handles dynamic line items, calculations, and form interactions
 */

$(function() {
    'use strict';

    // Line item counter
    let lineItemCounter = 0;

    // Initialize Select2 for customer dropdown
    $('#customer_id').select2({
        placeholder: pageData?.labels?.selectCustomer || 'Select Customer',
        allowClear: true,
        width: '100%'
    });

    // Initialize Flatpickr for date inputs
    $('.flatpickr-date').flatpickr({
        dateFormat: 'Y-m-d',
        altInput: true,
        altFormat: 'F j, Y',
        allowInput: true
    });

    // Add line item
    $('#addLineItem').on('click', function() {
        addLineItem();
    });

    // Function to add a new line item
    function addLineItem(data = {}) {
        lineItemCounter++;
        const index = lineItemCounter;

        const row = `
            <tr class="line-item" data-index="${index}">
                <td>
                    <select class="form-select form-select-sm product-select"
                            name="line_items[${index}][product_id]"
                            data-index="${index}" required>
                        <option value="">${pageData?.labels?.selectProduct || 'Select Product'}</option>
                    </select>
                    <input type="hidden" name="line_items[${index}][product_name]" class="product-name">
                    <input type="hidden" name="line_items[${index}][product_sku]" class="product-sku">
                </td>
                <td>
                    <input type="number" step="0.01" min="0.01"
                           class="form-control form-control-sm line-quantity"
                           name="line_items[${index}][quantity]"
                           value="${data.quantity || 1}"
                           data-index="${index}" required>
                </td>
                <td>
                    <input type="number" step="0.01" min="0"
                           class="form-control form-control-sm line-unit-price"
                           name="line_items[${index}][unit_price]"
                           value="${data.unit_price || 0}"
                           data-index="${index}" required>
                </td>
                <td>
                    <select class="form-select form-select-sm tax-select"
                            name="line_items[${index}][tax_id]"
                            data-index="${index}">
                        <option value="">${pageData?.labels?.noTax || 'No Tax'}</option>
                    </select>
                    <input type="hidden" name="line_items[${index}][tax_rate]" class="tax-rate-hidden" value="0">
                </td>
                <td>
                    <input type="number" step="0.01" min="0"
                           class="form-control form-control-sm line-discount"
                           name="line_items[${index}][discount_amount]"
                           value="${data.discount_amount || 0}"
                           data-index="${index}">
                </td>
                <td>
                    <input type="text" class="form-control form-control-sm line-total"
                           value="0.00" readonly>
                    <input type="hidden" name="line_items[${index}][line_total]" class="line-total-hidden" value="0">
                </td>
                <td class="text-center">
                    <button type="button" class="btn btn-sm btn-icon btn-danger remove-line-item" data-index="${index}">
                        <i class="bx bx-trash"></i>
                    </button>
                </td>
            </tr>
        `;

        $('#lineItemsContainer').append(row);

        // Initialize tax dropdown
        initializeTaxDropdown(index, data.tax_id);

        // Initialize Select2 for the new product select
        initializeProductSelect(index, data.product_id);

        // Attach event listeners for the new row
        attachLineItemEvents(index);

        // Calculate totals
        calculateLineTotals();
    }

    // Initialize tax configuration dropdown
    function initializeTaxDropdown(index, selectedTaxId = null) {
        const $select = $(`.tax-select[data-index="${index}"]`);
        const $row = $select.closest('.line-item');

        // Populate options from window.taxConfigurations
        if (window.taxConfigurations && window.taxConfigurations.length > 0) {
            window.taxConfigurations.forEach(tax => {
                const isSelected = selectedTaxId && tax.id == selectedTaxId;
                $select.append(`<option value="${tax.id}" data-rate="${tax.rate}" ${isSelected ? 'selected' : ''}>${tax.name} (${tax.rate}%)</option>`);
            });
        }

        // Update hidden tax_rate when selection changes
        $select.on('change', function() {
            const selectedOption = $(this).find('option:selected');
            const rate = selectedOption.data('rate') || 0;
            $row.find('.tax-rate-hidden').val(rate);
            calculateLineTotal(index);
        });

        // Set initial tax rate if tax is pre-selected
        if (selectedTaxId) {
            const selectedOption = $select.find('option:selected');
            const rate = selectedOption.data('rate') || 0;
            $row.find('.tax-rate-hidden').val(rate);
        }
    }

    // Initialize product select with Select2 and AJAX
    function initializeProductSelect(index, selectedProductId = null) {
        const $select = $(`.product-select[data-index="${index}"]`);

        $select.select2({
            placeholder: pageData?.labels?.searchProducts || 'Search products...',
            allowClear: true,
            width: '100%',
            ajax: {
                url: pageData?.urls?.productsSearch || '/systemcore/products/search',
                dataType: 'json',
                delay: 250,
                data: function (params) {
                    return {
                        q: params.term,
                        page: params.page || 1
                    };
                },
                processResults: function (data) {
                    return {
                        results: data.map(product => ({
                            id: product.id,
                            text: `${product.sku} - ${product.name}`,
                            product: product
                        }))
                    };
                },
                cache: true
            },
            minimumInputLength: 2,
            templateResult: formatProductResult,
            templateSelection: formatProductSelection
        });

        // Handle product selection
        $select.on('select2:select', function(e) {
            const product = e.params.data.product;
            const $row = $(this).closest('.line-item');
            const idx = $(this).data('index');

            // Populate hidden fields
            $row.find('.product-name').val(product.name);
            $row.find('.product-sku').val(product.sku);

            // Set unit price
            $row.find('.line-unit-price').val(product.selling_price || 0);

            // Set tax dropdown from product's tax configuration
            if (product.tax_id) {
                $row.find('.tax-select').val(product.tax_id).trigger('change');
            } else {
                $row.find('.tax-select').val('').trigger('change');
            }

            // Calculate line total
            calculateLineTotal(idx);
        });

        // If there's a selected product ID, load it
        if (selectedProductId) {
            // You would need an endpoint to fetch single product
            // For now, we'll just set the value
            $select.val(selectedProductId).trigger('change');
        }
    }

    // Format product result in dropdown
    function formatProductResult(product) {
        if (product.loading) {
            return product.text;
        }

        if (!product.product) {
            return product.text;
        }

        const $result = $(`
            <div class="product-result">
                <div class="fw-semibold">${product.product.name}</div>
                <div class="text-muted small">SKU: ${product.product.sku} | Price: ${product.product.selling_price}</div>
            </div>
        `);

        return $result;
    }

    // Format selected product
    function formatProductSelection(product) {
        return product.text;
    }

    // Attach event listeners to line item inputs
    function attachLineItemEvents(index) {
        const $row = $(`.line-item[data-index="${index}"]`);

        // Calculate on input change
        $row.find('.line-quantity, .line-unit-price, .line-tax-rate, .line-discount').on('input', function() {
            calculateLineTotal(index);
        });

        // Remove line item
        $row.find('.remove-line-item').on('click', function() {
            $row.remove();
            calculateLineTotals();
        });
    }

    // Calculate individual line total
    function calculateLineTotal(index) {
        const $row = $(`.line-item[data-index="${index}"]`);

        const quantity = parseFloat($row.find('.line-quantity').val()) || 0;
        const unitPrice = parseFloat($row.find('.line-unit-price').val()) || 0;
        const taxRate = parseFloat($row.find('.tax-rate-hidden').val()) || 0;
        const discountAmount = parseFloat($row.find('.line-discount').val()) || 0;

        // Calculate subtotal
        let subtotal = quantity * unitPrice;

        // Apply discount
        subtotal -= discountAmount;

        // Calculate tax
        const taxAmount = (subtotal * taxRate) / 100;

        // Calculate line total
        const lineTotal = subtotal + taxAmount;

        // Update display
        $row.find('.line-total').val(lineTotal.toFixed(2));
        $row.find('.line-total-hidden').val(lineTotal.toFixed(2));

        // Recalculate order totals
        calculateLineTotals();
    }

    // Calculate order totals
    function calculateLineTotals() {
        let subtotal = 0;
        let totalTax = 0;

        // Sum up all line items
        $('.line-item').each(function() {
            const quantity = parseFloat($(this).find('.line-quantity').val()) || 0;
            const unitPrice = parseFloat($(this).find('.line-unit-price').val()) || 0;
            const taxRate = parseFloat($(this).find('.tax-rate-hidden').val()) || 0;
            const discountAmount = parseFloat($(this).find('.line-discount').val()) || 0;

            const itemSubtotal = quantity * unitPrice;
            const itemSubtotalAfterDiscount = itemSubtotal - discountAmount;
            const itemTax = (itemSubtotalAfterDiscount * taxRate) / 100;

            subtotal += itemSubtotalAfterDiscount;
            totalTax += itemTax;
        });

        // Get additional values
        const additionalDiscount = parseFloat($('#discount_amount').val()) || 0;
        const shippingCost = parseFloat($('#shipping_cost').val()) || 0;

        // Calculate total
        const totalAmount = subtotal + totalTax - additionalDiscount + shippingCost;

        // Update display
        $('#displaySubtotal').val(subtotal.toFixed(2));
        $('#subtotal').val(subtotal.toFixed(2));
        $('#tax_amount').val(totalTax.toFixed(2));
        $('#displayTotalAmount').val(totalAmount.toFixed(2));
        $('#total_amount').val(totalAmount.toFixed(2));
    }

    // Recalculate on discount or shipping change
    $('#discount_amount, #shipping_cost').on('input', function() {
        calculateLineTotals();
    });

    // Form validation
    $('#salesOrderForm').on('submit', function(e) {
        const lineItemCount = $('.line-item').length;

        if (lineItemCount === 0) {
            e.preventDefault();
            Swal.fire({
                icon: 'warning',
                title: pageData?.labels?.warning || 'Warning',
                text: pageData?.labels?.add_at_least_one_item || 'Please add at least one item to the order',
                customClass: {
                    confirmButton: 'btn btn-primary'
                },
                buttonsStyling: false
            });
            return false;
        }

        // Check if all products are selected
        let allProductsSelected = true;
        $('.product-select').each(function() {
            if (!$(this).val()) {
                allProductsSelected = false;
                $(this).addClass('is-invalid');
            } else {
                $(this).removeClass('is-invalid');
            }
        });

        if (!allProductsSelected) {
            e.preventDefault();
            Swal.fire({
                icon: 'warning',
                title: pageData?.labels?.warning || 'Warning',
                text: pageData?.labels?.select_all_products || 'Please select a product for all line items',
                customClass: {
                    confirmButton: 'btn btn-primary'
                },
                buttonsStyling: false
            });
            return false;
        }
    });

    // Initialize with one empty line item
    addLineItem();
});
