
<script src="{{ asset('admintheme/assets/js/moment.min.js') }}"></script>
<script src="{{ asset('admintheme/assets/js/daterangepicker.min.js') }}"></script>
<script>
    var canEdit = @can('order_product_edit') true @else false @endcan;
    var canDelete = @can('order_product_delete') true @else false @endcan;
</script>


<script>        
    function initializeInvoiceDatePicker(invoiceDate = null) {
        const dateFormat = "{{ config('constant.js_date_format.date') }}";
        $('#invoice_date').daterangepicker({
            locale: { format: dateFormat },
            singleDatePicker: true,
            autoUpdateInput: true,
            autoApply: true,
            startDate:  invoiceDate ? moment(invoiceDate) : moment(),
            maxDate: moment(), 
        });

        order.invoice_date = invoiceDate ? moment(invoiceDate).format(dateFormat) : moment().format(dateFormat);
    }
</script>

<script>
var order = {
    products: [],
    labour_bhada: 0.00,
    gadi_bhada: 0.00,
    //is_round_off: 0,
    sub_total: 0.00,
    //round_off_amount: 0,    
    grand_total: 0.00,
    invoice_date: null,
    remark: null,
};
var rowIndex;

$(document).ready(function() {
    
    @if(isset($orderData))        
        order = {
            products: @json($orderData['products']),
            labour_bhada: parseFloat("{{ $orderData['labour_bhada'] }}"),
            gadi_bhada: parseFloat("{{ $orderData['gadi_bhada'] }}"),
            sub_total: parseFloat("{{ $orderData['sub_total'] }}"),            
            grand_total: parseFloat("{{ $orderData['grand_total'] }}"),
            invoice_date: "{{ $orderData['invoice_date'] }}", 
            remark: "{{ $orderData['remark'] }}",
            customer_id: parseInt("{{ $orderData['customer_id'] }}")
        };
        
        $('#labour_bhada').val(order.labour_bhada.toFixed(2));
        $('#gadi_bhada').val(order.gadi_bhada.toFixed(2));
        // $('#is_round_off').val(order.is_round_off);
        $('#sub_total').html("₹ "+ order.sub_total);
        $('#grand_total').html("₹ "+ order.grand_total);        
        $('#remark').val(order.remark);        
        
        initializeInvoiceDatePicker(order.invoice_date);        
        $("#customer_id").val(order.customer_id).trigger('change');        
        displayOrder();
    @endif

    if (!order.invoice_date) {
        initializeInvoiceDatePicker();
    }

    $("#customer_id").change(function (e) {
        e.preventDefault();
        order.customer_id = parseInt($(this).val());
    });

    $("#product_id").change(function (e) {
        e.preventDefault();
        order.product_id = parseInt($(this).val());
        order.product_name = $(this).find("option:selected").text();
    });

    $('#invoice_date').on('change', function() {
        const dateFormat = "{{ config('constant.js_date_format.date') }}";
        order.invoice_date = moment($(this).val()).format(dateFormat); // Format it as needed
    });

    $("#dispatch_place").change(function (e) {
        e.preventDefault();
        order.dispatch_place = parseInt($(this).val());
    });

    /*
    $("#is_round_off").change(function (e) {
        e.preventDefault();
        order.is_round_off = this.checked ? 1 : 0;
        calculateGrandTotal();
    });
    */

    $("#labour_bhada").on("input", function (e) {
        e.preventDefault();
        updateLabourBhadaPrice();
        calculateGrandTotal();
    });

    $("#remark").on("input", function (e) {
        e.preventDefault();
        order.remark = $(this).val();        
    });

    $("#gadi_bhada").on("input", function (e) {
        e.preventDefault();
        updateGadiBhadaPrice();
        calculateGrandTotal();
    });
   
    $("#price").on('input', function(e) {
        e.preventDefault();
        updateProductPrice();
    });

    $("#product_id").on('change', function(e) {   
        e.preventDefault();
        getStockAvailability();
        // validateStockAvailability();    
        updateProductPrice();        
    }); 

    $("#quantity").on('input', function(e) {  
        e.preventDefault(); 
        // validateStockAvailability();    
        updateProductPrice();        
    });

    $("#dispatch_place").on('change', function(e) {   
        e.preventDefault();
        // validateStockAvailability();    
        updateProductPrice();        
    });

    // Event handler for adding a product
    $(document).on('click', '#addProductBtn', function (e){
        e.preventDefault();
        var productRecord = createProductRecord();  
        if (!validateProductForm(productRecord)) {
            order.products.push(productRecord);
            updateOrderDetails();
        }
    });

    // Event handler for editing a product
    $(document).on('click', '.edit-product', function (e){
        e.preventDefault();
        rowIndex = $(this).attr('data-index');
        var productToEdit = order.products[rowIndex];
        $("#customer_id").val(productToEdit.customer_id);
        $("#product_id").val(productToEdit.product_id);                 
        $("#product_id").val(productToEdit.product_id).trigger('change');
        $("#dispatch_place").val(productToEdit.dispatch_place).trigger('change');
        $("#quantity").val(productToEdit.quantity);
        $("#original_quantity").val(productToEdit.quantity);
        $("#price").val(productToEdit.price);
        $("#total_price").val(productToEdit.total_price);
        $("#addProductBtn").replaceWith('<button type="button" id="editProductBtn" class="add_invoiceBtn btn btn-success"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20" fill="none"><path fill-rule="evenodd" clip-rule="evenodd" d="M19.4137 4.80283C17.4341 6.78244 12.7877 11.4279 11.6545 12.5574C11.4096 12.8013 11.1181 12.9941 10.8053 13.1198C9.89647 13.4969 7.67942 14.3666 7.02762 14.4104C6.63934 14.4364 6.2585 14.293 5.98288 14.0174C5.70726 13.7418 5.56387 13.361 5.58994 12.9727C5.6337 12.3209 6.50339 10.1057 6.87398 9.20061C7.00341 8.87937 7.19616 8.58792 7.44105 8.34396L15.1975 0.586619C15.5727 0.211369 16.083 0 16.6137 0C17.1445 0 17.6547 0.211369 18.03 0.586619L19.4137 1.9703C19.7889 2.34555 20.0003 2.85581 20.0003 3.38656C20.0003 3.91731 19.7889 4.42758 19.4137 4.80283ZM6.98945 13.0108C7.62635 12.9308 9.4877 12.1542 10.2699 11.8292C10.2727 11.8283 10.2754 11.8274 10.2773 11.8264C10.4235 11.7678 10.5557 11.6802 10.6665 11.5694L10.6675 11.5685C11.8025 10.439 16.4471 5.7945 18.4257 3.81489C18.5393 3.70129 18.6036 3.54765 18.6036 3.38656C18.6036 3.22548 18.5393 3.07184 18.4257 2.95824L17.0421 1.57456C16.9285 1.46096 16.7748 1.39671 16.6137 1.39671C16.4526 1.39671 16.299 1.46096 16.1854 1.57456L8.42806 9.33191C8.31632 9.44271 8.2288 9.57586 8.17013 9.72205L8.16827 9.72578C7.84703 10.5098 7.06952 12.373 6.98945 13.0108Z" fill="#fff"></path><path fill-rule="evenodd" clip-rule="evenodd" d="M17.5683 5.65973C17.8402 5.93255 17.8402 6.37485 17.5683 6.64767C17.2955 6.9205 16.8532 6.9205 16.5803 6.64767L13.3521 3.4194C13.0793 3.14658 13.0793 2.70428 13.3521 2.43146C13.6249 2.15957 14.0672 2.15957 14.34 2.43146L17.5683 5.65973Z" fill="#fff"></path><path fill-rule="evenodd" clip-rule="evenodd" d="M11.8691 11.3592C12.1419 11.6311 12.1419 12.0743 11.8691 12.3462C11.5972 12.619 11.154 12.619 10.8821 12.3462L7.65384 9.1179C7.38101 8.846 7.38101 8.40278 7.65384 8.13089C7.92573 7.85806 8.36895 7.85806 8.64085 8.13089L11.8691 11.3592Z" fill="#fff"></path><path fill-rule="evenodd" clip-rule="evenodd" d="M6.75078 1.84277C7.13627 1.84277 7.44914 2.15564 7.44914 2.54113C7.44914 2.92662 7.13627 3.23949 6.75078 3.23949H3.49178C2.33437 3.23949 1.39671 4.17715 1.39671 5.33456V16.5083C1.39671 17.0642 1.61739 17.5968 2.01034 17.9897C2.40328 18.3827 2.93589 18.6033 3.49178 18.6033H15.5966C16.1525 18.6033 16.6851 18.3827 17.0781 17.9897C17.471 17.5968 17.6917 17.0642 17.6917 16.5083V13.2493C17.6917 12.8638 18.0046 12.5509 18.3901 12.5509C18.7755 12.5509 19.0884 12.8638 19.0884 13.2493V16.5083C19.0884 17.4347 18.7206 18.3221 18.066 18.9776C17.4105 19.6322 16.5231 20 15.5966 20H3.49178C2.5653 20 1.67792 19.6322 1.02239 18.9776C0.367801 18.3221 0 17.4347 0 16.5083V5.33456C0 3.40616 1.56339 1.84277 3.49178 1.84277H6.75078Z" fill="#fff"></path></svg></button>');
    });     
    
    $(document).on('click', '#editProductBtn', function (e){
        e.preventDefault();
        var productRecord = createProductRecord();  
        $("#original_quantity").val(0);

        // Append order_product_id if the product exists in the database
        if (order.products[rowIndex] && order.products[rowIndex].order_product_id) {
            productRecord.order_product_id = order.products[rowIndex].order_product_id;
        }
        
        if (!validateProductForm(productRecord)) {
            order.products[rowIndex] = productRecord;
            updateOrderDetails();            
            $("#editProductBtn").replaceWith('<button type="button" class="add_invoiceBtn btn btn-success addProductBtn" id="addProductBtn"><i class="fas fa-plus"></i></button>');
        }
    });

    if (!order.deleted_products) {
        order.deleted_products = [];
    }

    $(document).on('click', '.delete-product', function (e) {
        e.preventDefault();
        swal({
        title: "{{ trans('messages.deletetitle') }}",
        text: "{{ trans('messages.areYouSure') }}",
        icon: 'warning',
        buttons: {
        confirm: 'Yes, delete it',
        cancel: 'No, cancel',
        },
        dangerMode: true,
        }).then((willDelete) => {
            if (willDelete) {               
                var rowIndex = $(this).attr('data-index');
                var productToDelete = order.products[rowIndex];
                if ('order_product_id' in productToDelete) {                        
                    order.deleted_products.push(productToDelete.order_product_id); 
                }

                var rowToDelete = $("#orderProductTable tbody tr").eq(rowIndex);
                rowToDelete.remove();                
                order.products.splice(rowIndex, 1);
                updateOrderDetails();
            }
        });
    });

    $(document).on('submit', '#SaveInvoiceForm', function (e) {
        e.preventDefault();
        $("#SaveInvoiceForm button[type=submit]").prop('disabled',true);
        showLoader();
        
        if (order.products.length <= 0) {
            hideLoader();
            $("#SaveInvoiceForm button[type=submit]").prop('disabled', false);
            swal("Empty Invoice", "Please enter products in the invoice.", "error");
            return;
        }
        else{
            var formAction = $(this).attr('action');  
            const finalInvoiceData = {
                labour_bhada: order.labour_bhada,
                gadi_bhada: order.gadi_bhada,
                // is_round_off: order.is_round_off,
                sub_total: order.sub_total,
                // round_off_amount: order.round_off_amount,
                grand_total: order.grand_total,
                invoice_date: order.invoice_date,
                remark: order.remark,
                customer_id: order.customer_id,
                deleted_products: order.deleted_products ?? null,
                products: order.products.map(product => ({
                    product_id: product.product_id,
                    quantity: product.quantity,
                    price: product.price,
                    total_price: product.total_price,
                    dispatch_place: product.dispatch_place,
                    order_product_id: product.order_product_id
                }))
            }; 

            var requestType = 'POST';
            @if(isset($order))
            requestType = 'PUT';
            @endif

            $.ajax({
                url: formAction,
                type: requestType,
                data: finalInvoiceData,
                headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                },
                success: function (response) {
                    hideLoader();
                    var alertType = response['alert-type'];
                    var message = response['message'];
                    var title = "{{ trans('quickadmin.order.order') }}";
                    $('#SaveInvoiceForm')[0].reset();
                    $('#orderProductTable tbody').empty();  
                    $('#grand_total').html("");  
                    $('#sub_total').html("");  
                    var select2Element = $('#customer_id');
                    select2Element.val('').trigger('change.select2');

                    clearForm();
                    
                    if(response.creditLimitWarning){
                        swal({
                            title: response.creditLimitWarning.title,
                            text: response.creditLimitWarning.message,
                            icon: response.creditLimitWarning.alertType,
                            buttons: {
                            confirm: 'OK',
                        },
                        closeOnClickOutside: false,
                        }).then((confirm) => {
                            if (confirm) {
                                // window.location.replace(response.redirectUrl);
                                swal({
                                    title: response.invoiceNumber,
                                    text: message,
                                    icon: alertType,
                                    buttons: {
                                    confirm: 'OK',
                                },
                                closeOnClickOutside: false,
                                }).then((confirm) => {
                                    if (confirm) {
                                        window.location.replace(response.redirectUrl);
                                    }
                                });
                            }
                        });    
                    }else{
                        swal({
                            title: response.invoiceNumber,
                            text: message,
                            icon: alertType,
                            buttons: {
                            confirm: 'OK',
                        },
                        closeOnClickOutside: false,
                        }).then((confirm) => {
                            if (confirm) {
                                window.location.replace(response.redirectUrl);
                            }
                        });
                    }
                          
                    $("#SaveInvoiceForm button[type=submit]").prop('disabled',false);
                },
                error: function (xhr) {
                    hideLoader();
                    var errors= xhr.responseJSON.errors;
                    console.log(xhr);
                    $("#SaveInvoiceForm button[type=submit]").prop('disabled',false);
                    for (const elementId in errors) {
                        //$("#"+elementId).addClass('is-invalid');
                        var errorHtml = '<div><span class="error text-danger">'+errors[elementId]+'</span></div>';
                        $(errorHtml).insertAfter($("#"+elementId).parent());
                    }

                    var mainError = xhr.responseJSON;
                    var alertType = mainError['alert-type'];
                    var message = mainError['message'] ?? 'Oops, Something Went Wrong!';
                    var title = mainError['title'] ?? "{{ trans('quickadmin.order.order') }}";        
                    swal(title, message, 'error');                                        
                }
            });
        }
    });

});

// Function to create product record
function createProductRecord() {
    let price = parseFloat($("#price").val());
    let total_price = parseFloat($("#total_price").val());
    return {     
        customer_id: order.customer_id,
        product_id: parseInt($("#product_id").val()), 
        product_name: $("#product_id option:selected").text(),
        brand_name:$("#product_id option:selected").attr('data-brand'),
        unit_name:$("#product_id option:selected").attr('data-unit'),
        dispatch_place: $("#dispatch_place").val(),
        quantity: parseInt($("#quantity").val()),
        price: price.toFixed(2), 
        total_price: roundTotalPrice(total_price)
    };
}

// Function to update order details after adding or editing a product
function updateOrderDetails() {
    order.sub_total = calculateSubtotal();
    $('#sub_total').html("₹ "+ order.sub_total);
    calculateGrandTotal();   
    clearForm();
    displayOrder();    
}

// Function to validate product form
function validateProductForm(productRecord) {
    var errors = {
        customer_id: "The Customer Name is required.",
        product_id: "The Product Name is required.",
        quantity: "The Quantity is required.",
        price: "The Price is required.",
        total_price: "Please fill quantity or price.",
        dispatch_place: "The Dispatch place is required."
    };

    var hasErrors = false;
    removerror();

    for (const elementId in productRecord) {
        if (!productRecord[elementId]) {
            var errorHtml = '<div><span class="error text-danger">' + errors[elementId] + '</span></div>';
            $(errorHtml).insertAfter($("#" + elementId).parent());
            hasErrors = true;
        }
    }

    return hasErrors;
}

function updateProductPrice() {
    var selectedProductId = $("#product_id").val(); 
    if (!selectedProductId) {
        // swal("Warning","Please select a product.", "warning");
        return;  
    }
    
    var selectedProduct = $("#product_id option:selected");    
    var calculationFactor = parseFloat(selectedProduct.data('calculation')) || 0;
    // var price = parseFloat($("#price").val()) || calculationFactor;
    
    var price = parseFloat($("#price").val()) || 0;
    
    var quantity = parseInt($("#quantity").val()) || 0;    
    var totalPrice = (price * calculationFactor * quantity);   
    var roundedTotalPrice = roundTotalPrice(totalPrice)
    
    $("#price").val(price);
    
    $("#total_price").val(roundedTotalPrice);
   
}

function roundTotalPrice(totalPrice){
    return Math.round(totalPrice);
}

function getStockAvailability() {
    var product_id = parseInt($("#product_id").val());   
    $(".error, .inventory-info").remove(); 
    if (!product_id) {
        return; 
    }

    $.ajax({
        url: "{{ route('orders.getStockAvailability') }}",
        type: 'POST',
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        },
        data: {
            product_id: product_id,           
        },
        success: function(response) {
            if (response.success) {                
                var stockCountString = '<div><span class="inventory-info text-danger font-weight-bold">'+response.message+'</span></div>';
                $(stockCountString).insertAfter($("#product_id").parent());
            } 
        },
        error: function(xhr) {                  
            swal("Error", "Woops, Something Went Wrong! ", "error");
        }
    });
}

function validateStockAvailability() {
    var product_id = parseInt($("#product_id").val());
    var quantity = parseInt($("#quantity").val()) || 0; 
    var dispatch_place = $("#dispatch_place").val();
    var original_quantity = parseInt($("#original_quantity").val()) || 0; 

    // Calculate additional quantity to be added
    var additional_quantity = quantity - original_quantity;
    if (!product_id || !dispatch_place || additional_quantity <= 0) {
        return;  // No need to validate if additional quantity is 0 or negative
    }

    $.ajax({
        url: "{{ route('orders.validateStockAvailability') }}",
        type: 'POST',
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        },
        data: {
            product_id: product_id,
            quantity: additional_quantity,
            dispatch_place: dispatch_place
        },
        success: function(response) {
            if (response.available) {                
                // console.log("Stock is available.");
            } else {  
                $("#quantity").val("");  
                $("#total_price").val("");              
                swal("Insufficient Stock", "This product is out of stock at this dispatch place.", "error");
            }
        },
        error: function(xhr) {      
            $("#quantity").val("");  
            $("#total_price").val("");    
            swal("Error", "An error occurred while checking stock availability.", "error");
        }
    });
}

function displayOrder() {
    var orderTableBody = $('#orderProductTable tbody');
    orderTableBody.empty();
    if (order.products.length > 0) {        
        for (var i = 0; i < order.products.length; i++) {
            var product = order.products[i];    
            var price = parseFloat(product.price);
            var totalPrice = parseInt(product.total_price);         
            var row = '<tr data-product_id="' + product.product_id + '" >' + 
                        '<td>' + (i + 1) + '</td>' + 
                        '<td>' + product.product_name +'</td>' +
                        '<td>' + product.quantity + ' '+product.unit_name+'</td>' +
                        '<td>' + price.toFixed(2) + '</td>' +
                        '<td>' + roundTotalPrice(totalPrice) + '</td>' +
                        '<td>';                      

            if (canEdit) {
                row += '<div><a href="javascript:void(0)" class="editProduct edit-product" data-index="' + i + '" title="Edit"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20" fill="none"><path fill-rule="evenodd" clip-rule="evenodd" d="M19.4137 4.80283C17.4341 6.78244 12.7877 11.4279 11.6545 12.5574C11.4096 12.8013 11.1181 12.9941 10.8053 13.1198C9.89647 13.4969 7.67942 14.3666 7.02762 14.4104C6.63934 14.4364 6.2585 14.293 5.98288 14.0174C5.70726 13.7418 5.56387 13.361 5.58994 12.9727C5.6337 12.3209 6.50339 10.1057 6.87398 9.20061C7.00341 8.87937 7.19616 8.58792 7.44105 8.34396L15.1975 0.586619C15.5727 0.211369 16.083 0 16.6137 0C17.1445 0 17.6547 0.211369 18.03 0.586619L19.4137 1.9703C19.7889 2.34555 20.0003 2.85581 20.0003 3.38656C20.0003 3.91731 19.7889 4.42758 19.4137 4.80283ZM6.98945 13.0108C7.62635 12.9308 9.4877 12.1542 10.2699 11.8292C10.2727 11.8283 10.2754 11.8274 10.2773 11.8264C10.4235 11.7678 10.5557 11.6802 10.6665 11.5694L10.6675 11.5685C11.8025 10.439 16.4471 5.7945 18.4257 3.81489C18.5393 3.70129 18.6036 3.54765 18.6036 3.38656C18.6036 3.22548 18.5393 3.07184 18.4257 2.95824L17.0421 1.57456C16.9285 1.46096 16.7748 1.39671 16.6137 1.39671C16.4526 1.39671 16.299 1.46096 16.1854 1.57456L8.42806 9.33191C8.31632 9.44271 8.2288 9.57586 8.17013 9.72205L8.16827 9.72578C7.84703 10.5098 7.06952 12.373 6.98945 13.0108Z" fill="#000"></path><path fill-rule="evenodd" clip-rule="evenodd" d="M17.5683 5.65973C17.8402 5.93255 17.8402 6.37485 17.5683 6.64767C17.2955 6.9205 16.8532 6.9205 16.5803 6.64767L13.3521 3.4194C13.0793 3.14658 13.0793 2.70428 13.3521 2.43146C13.6249 2.15957 14.0672 2.15957 14.34 2.43146L17.5683 5.65973Z" fill="#000"></path><path fill-rule="evenodd" clip-rule="evenodd" d="M11.8691 11.3592C12.1419 11.6311 12.1419 12.0743 11.8691 12.3462C11.5972 12.619 11.154 12.619 10.8821 12.3462L7.65384 9.1179C7.38101 8.846 7.38101 8.40278 7.65384 8.13089C7.92573 7.85806 8.36895 7.85806 8.64085 8.13089L11.8691 11.3592Z" fill="#000"></path><path fill-rule="evenodd" clip-rule="evenodd" d="M6.75078 1.84277C7.13627 1.84277 7.44914 2.15564 7.44914 2.54113C7.44914 2.92662 7.13627 3.23949 6.75078 3.23949H3.49178C2.33437 3.23949 1.39671 4.17715 1.39671 5.33456V16.5083C1.39671 17.0642 1.61739 17.5968 2.01034 17.9897C2.40328 18.3827 2.93589 18.6033 3.49178 18.6033H15.5966C16.1525 18.6033 16.6851 18.3827 17.0781 17.9897C17.471 17.5968 17.6917 17.0642 17.6917 16.5083V13.2493C17.6917 12.8638 18.0046 12.5509 18.3901 12.5509C18.7755 12.5509 19.0884 12.8638 19.0884 13.2493V16.5083C19.0884 17.4347 18.7206 18.3221 18.066 18.9776C17.4105 19.6322 16.5231 20 15.5966 20H3.49178C2.5653 20 1.67792 19.6322 1.02239 18.9776C0.367801 18.3221 0 17.4347 0 16.5083V5.33456C0 3.40616 1.56339 1.84277 3.49178 1.84277H6.75078Z" fill="#000"></path></svg></a>';
            }            
           
            if (canDelete) {
                row += '<a href="javascript:void(0)" class="deleteProduct delete-product" data-index="' + i + '" title="Delete"><svg xmlns="http://www.w3.org/2000/svg" width="19" height="20" viewBox="0 0 19 20" fill="none"><path d="M9.02439 1.46341C8.06976 1.46341 7.25571 2.0732 6.95402 2.92676C6.81935 3.30778 6.40131 3.50748 6.02029 3.37281C5.63928 3.23814 5.43958 2.8201 5.57425 2.43909C6.07614 1.01911 7.43034 0 9.02439 0C10.6185 0 11.9727 1.01911 12.4746 2.43909C12.6093 2.8201 12.4096 3.23814 12.0286 3.37281C11.6475 3.50748 11.2295 3.30778 11.0948 2.92676C10.7932 2.0732 9.97902 1.46341 9.02439 1.46341Z" fill="#000"></path><path d="M0 4.63405C0 4.22994 0.3276 3.90234 0.731707 3.90234H17.3172C17.7213 3.90234 18.0489 4.22994 18.0489 4.63405C18.0489 5.03816 17.7213 5.36576 17.3172 5.36576H0.731707C0.3276 5.36576 0 5.03816 0 4.63405Z" fill="#000"></path><path d="M3.08779 7.02437C3.06091 6.62115 2.71225 6.31608 2.30904 6.34296C1.90582 6.36983 1.60074 6.7185 1.62763 7.12172L2.07977 13.9039C2.16318 15.1554 2.23055 16.1662 2.38857 16.9595C2.55286 17.7842 2.8323 18.473 3.40947 19.0129C3.98663 19.5529 4.69253 19.7859 5.52634 19.895C6.32833 19.9999 7.34147 19.9999 8.59571 19.9999H9.45308C10.7073 19.9999 11.7204 19.9999 12.5224 19.895C13.3562 19.7859 14.0622 19.5529 14.6393 19.0129C15.2165 18.473 15.4959 17.7842 15.6602 16.9595C15.8182 16.1662 15.8856 15.1554 15.969 13.9039L16.4212 7.12172C16.448 6.7185 16.1429 6.36983 15.7397 6.34296C15.3365 6.31608 14.9878 6.62115 14.961 7.02437L14.5122 13.7552C14.4246 15.0702 14.3621 15.9851 14.225 16.6735C14.0919 17.3413 13.9063 17.6948 13.6395 17.9444C13.3728 18.1938 13.0077 18.3557 12.3326 18.444C11.6366 18.535 10.7195 18.5365 9.40166 18.5365H8.64713C7.32928 18.5365 6.41215 18.535 5.71615 18.444C5.04103 18.3557 4.676 18.1938 4.40925 17.9444C4.1425 17.6948 3.95682 17.3413 3.82379 16.6735C3.68665 15.9851 3.62418 15.0702 3.53652 13.7552L3.08779 7.02437Z" fill="#000"></path><path d="M6.51247 8.78396C6.91458 8.74376 7.2731 9.03713 7.31339 9.43927L7.80119 14.3173C7.84139 14.7194 7.54802 15.078 7.14588 15.1182C6.74379 15.1584 6.38521 14.865 6.34501 14.4629L5.8572 9.58483C5.81699 9.18279 6.11036 8.82415 6.51247 8.78396Z" fill="#000"></path><path d="M12.1918 9.58483C12.232 9.18279 11.9387 8.82415 11.5365 8.78396C11.1345 8.74376 10.7758 9.03713 10.7356 9.43927L10.2478 14.3173C10.2076 14.7194 10.501 15.078 10.9031 15.1182C11.3052 15.1584 11.6637 14.865 11.704 14.4629L12.1918 9.58483Z" fill="#000"></path></svg></a></div>';
            }           


            row += '</td></tr>';            
            orderTableBody.append(row);
        }
    }
}
               
// Function to clear the form fields
function clearForm() {
    $("#quantity, #price, #total_price").val("");
    $(".is-invalid").removeClass("is-invalid");
    $(".error").remove();
    $(".inventory-info").remove();

    var select2ElementProduct = $('#product_id');
    select2ElementProduct.val(null).trigger('change');

    var select2ElementPlace = $('#dispatch_place');
    select2ElementPlace.val(null).trigger('change');
}

function removerror(){
    $(".error.text-danger").remove();
    $(".is-invalid").removeClass("is-invalid");
}

function updateLabourBhadaPrice() {
    var labour_bhada = parseFloat($("#labour_bhada").val()) || 0.00;
    order.labour_bhada = labour_bhada;    
}

function updateGadiBhadaPrice() {
    var gadi_bhada = parseFloat($("#gadi_bhada").val()) || 0.00;
    order.gadi_bhada = gadi_bhada;    
}

function calculateAmount() {
    var quantity = parseFloat($("#quantity").val()) || 0;
    var price = parseFloat($("#price").val()) || 0;
    var total_price = (quantity * price).toFixed(2);
    $("#total_price").val(total_price);
}

function calculateSubtotal() {
    let subtotal = 0.00;    
    for (const product of order.products) {
        let totalPrice = parseFloat(product.total_price);        
        subtotal += totalPrice || 0.00; 
    }        
    return parseFloat(subtotal.toFixed(2)); 
}

function calculateGrandTotal() {
    var subTotal = calculateSubtotal();
    var labour_bhada = parseFloat(order.labour_bhada) || 0.00;
    var gadi_bhada = parseFloat(order.gadi_bhada) || 0.00;
    /*
    var isRoundOff = parseInt(order.is_round_off) || 0 ; 

    if (isRoundOff) {        
        var roundedSubtotal = Math.round(subTotal);        
        $("#round_off_amount").text(roundedSubtotal);
        order.round_off_amount = roundedSubtotal;
    } else {
        $("#round_off_amount").text("0");
        order.round_off_amount = 0;
    }
    var grandTotal = labour_bhada + gadi_bhada + (isRoundOff ? roundedSubtotal : subTotal);
    */

    var grandTotal = labour_bhada + gadi_bhada + subTotal;
    order.grand_total = grandTotal;
    // var showGrandTotal = isRoundOff ? grandTotal : grandTotal.toFixed(2)
    $('#grand_total').html("₹ "+ grandTotal);     
}

</script>