@component('components.widget', ['class' => 'box-primary'])
    <table class="table table-bordered table-striped hide-footer" style="width: 100%;" id="shipping-product-table">
        <thead>
        <tr>
            <th>@lang('sale.product')</th>
            <th>{{__("lang_v1.location_from")}}</th>
            <th>{{__('tpsTransfer::lang.transfer_qty')}}</th>
            <th>{{__('tpsTransfer::lang.committed')}}</th>
            <th>{{__('tpsTransfer::lang.unit_price_before_shipping')}}</th>
            <th>{{__('tpsTransfer::lang.total_price_before_shipping')}}</th>
            <th>{{__('tpsTransfer::lang.shipping_ratio')}}</th>
            <th>{{__('tpsTransfer::lang.shipping_value_unit')}}</th>
            <th>{{__('tpsTransfer::lang.unit_price_after_shipping')}}</th>
            <th>{{__('tpsTransfer::lang.total_price_after_shipping')}}</th>
        </tr>
        </thead>
    </table>
@endcomponent
@component('components.widget', ['class' => 'box-primary'])
    <div class="row">
        <div class="col-md-4">
            <div class="form-group">
                {!! Form::label('shipping_details', __('sale.shipping_details'). ' :') !!}
                {!! Form::text('shipping_details',null, ['class' => 'form-control','placeholder' => __('sale.shipping_details')]); !!}
            </div>
        </div>
        <div class="col-md-4">
            <div class="form-group">
                {!! Form::label('shipping_method', __('tpsTransfer::lang.shipping_method')).':' !!}
                {!!Form::select('shipping_method', $shippingMethods, $setting['shippingMethod'] ?? null, ['id' => 'shipping_method', 'class' => 'form-control', 'style' => 'width:100%']); !!}
            </div>
        </div>
        <div class="col-md-4">
            <div class="form-group">
                {!! Form::label('shipping_charges', __('tpsTransfer::lang.additional_shipping_charges')).':' !!}
                {!! Form::number('shipping_charges',null, ['id' => 'shipping_charges', 'class' => 'form-control','placeholder' => __('tpsTransfer::lang.additional_shipping_charges')]); !!}
            </div>
        </div>
    </div>
    <div class="row">
        <div class="col-md-4"></div>
        <div class="col-md-4">
            <div class="form-group">
                {!! Form::label('additional_expense_name', __('lang_v1.additional_expense_name')) !!}
            </div>
            <div class="form-group">
                {!! Form::text('additional_expense_key_1',null, ['id' => 'additional_expense_key_1', 'class' => 'form-control','placeholder' => __('lang_v1.additional_expense_name')]); !!}
            </div>
            <div class="form-group">
                {!! Form::text('additional_expense_key_2',null, ['id' => 'additional_expense_key_2', 'class' => 'form-control','placeholder' => __('lang_v1.additional_expense_name')]); !!}
            </div>
            <div class="form-group">
                {!! Form::text('additional_expense_key_3',null, ['id' => 'additional_expense_key_3', 'class' => 'form-control','placeholder' => __('lang_v1.additional_expense_name')]); !!}
            </div>
            <div class="form-group">
                {!! Form::text('additional_expense_key_4',null, ['id' => 'additional_expense_key_4', 'class' => 'form-control','placeholder' => __('lang_v1.additional_expense_name')]); !!}
            </div>
        </div>
        <div class="col-md-4">
            <div class="form-group">
                {!! Form::label('additional_expense_amount', __('sale.amount')) !!}
            </div>
            <div class="form-group">
                {!! Form::text('additional_expense_value_1',0, ['id' => 'additional_expense_value_1', 'class' => 'form-control','placeholder' => __('sale.amount')]); !!}
            </div>
            <div class="form-group">
                {!! Form::text('additional_expense_value_2',0, ['id' => 'additional_expense_value_2', 'class' => 'form-control','placeholder' => __('sale.amount')]); !!}
            </div>
            <div class="form-group">
                {!! Form::text('additional_expense_value_3',0, ['id' => 'additional_expense_value_3', 'class' => 'form-control','placeholder' => __('sale.amount')]); !!}
            </div>
            <div class="form-group">
                {!! Form::text('additional_expense_value_4',0, ['id' => 'additional_expense_value_4', 'class' => 'form-control','placeholder' => __('sale.amount')]); !!}
            </div>
        </div>
    </div>
@endcomponent
@component('components.widget', ['class' => 'box-primary', 'title' => __('purchase.add_payment')])
    <div class="box-body payment_row">
        <div class="row">
            <div class="col-md-12">
                <strong>@lang('lang_v1.advance_balance'):</strong> <span id="advance_balance_text">0</span>
                {!! Form::hidden('advance_balance', null, ['id' => 'advance_balance', 'data-error-msg' => __('lang_v1.required_advance_balance_not_available')]); !!}
            </div>
        </div>
        @include('sale_pos.partials.payment_row_form', ['row_index' => 0, 'show_date' => true])
        <hr>
        <div class="row">
            <div class="col-sm-12">
                <div class="pull-right"><strong>@lang('purchase.payment_due'):</strong> <span id="payment_due">0.00</span></div>
            </div>
        </div>
        <br>
        <div class="row">
            <div class="col-sm-12">
{{--                <button type="button" id="submit_purchase_form" class="btn btn-primary pull-right btn-flat">@lang('messages.save')</button>--}}
            </div>
        </div>
    </div>
@endcomponent
<script type="text/javascript">
    let tpsShippingCalculation = new Object();

    $(document).ready(function () {
        __select2($('.select2'));
        // autoChangeDataTable();

        // Handle form submission event
        $('#add_product_modal_buttom').on('click', function (e) {
            // Prevent actual form submission
            e.preventDefault();

            // Send selected rows to products datatable
            reloadProductDatatable(temp_rows_selected)
            temp_rows_selected = [];
            // Hide add product modal
            $("#add_product").modal('hide');
        });
    });

    //change shipping method or value
    $(document).on('change', '#shipping_method, #shipping_charges',function () {
        if(($('#shipping_method').val() ) && ($('#shipping_charges').val() != '')){
            $('#shipping_method').attr('readonly', true).css("cursor", "not-allowed").find("option").prop("hidden", true);
            $('#shipping_charges').attr('readonly', true);

            $('#shipping-product-table').DataTable({
                processing: true,
                serverSide: true,
                scrollY: "130vh",
                scrollX: true,
                scrollCollapse: true,
                ajax: {
                    url: '{{action('\Modules\AdvancedTransfer\Http\Controllers\TpsPrepareStockController@addShippingTable')}}',
                    type: "POST",
                    data: {
                        tpsData: {!! json_encode($tpsData, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP) !!},
                        shipping_method: $('#shipping_method').val(),
                        shipping_charges: $('#shipping_charges').val(),
                    },
                },
                aaSorting: [],
                columns: [
                    {data: "products_name", name: "products.name"},
                    {data: "from_location_name", name: "business_locations.name"},
                    {data: "transfer_quantity", name: "nst_prepare_products.transfer_quantity"},
                    {data: "committed_qty_display", name: "committed_qty_display", orderable: false, searchable: false},
                    {data: "purchase_price", name: "purchase_lines.purchase_price"},
                    {data: "total_price_before_shipping", name: "total_price"},
                    {data: "shipping_ratio", name: "shipping_ratio"},
                    {data: "shipping_value_per_unit", name: "shipping_value_per_unit"},
                    {data: "unit_price_after_shipping", name: "unit_price_after_shipping"},
                    {data: "total_price_after_shipping", name: "total_price_after_shipping"},
                ],
                lengthMenu: [[10, 25, 50, 200, 500], [10, 25, 50, 200, 500]],
                pageLength: 10,
                searchDelay: 10,
                rowCallback: function (row, data) {
                    // write old inputs
                    if(tpsShippingCalculation[data['id']]){
                        if(tpsShippingCalculation[data['id']]['shipping_ratio']){
                            $(row).find('.shipping_ratio').val(tpsShippingCalculation[data['id']]['shipping_ratio']);
                        }
                        if(tpsShippingCalculation[data['id']]['value_per_unit']){
                            $(row).find('#shipping_value_per_unit_'+data['id']).html(tpsShippingCalculation['value_per_unit']);
                        }
                    }else{
                        tpsShippingCalculation[data['id']] = {};
                        tpsShippingCalculation[data['id']]['shipping_ratio'] = $(row).find('.shipping_ratio').val();
                        tpsShippingCalculation[data['id']]['value_per_unit'] = $(row).find('.shipping_value_per_unit').html();
                        tpsShippingCalculation[data['id']]['unit_price_after_shipping'] = $(row).find('.unit_price_after_shipping').html();
                    }
                },
            });
        }
    });

    $(document).on('change', '.shipping_ratio',function () {
        id = $(this).attr('data-id');
        if(!tpsShippingCalculation[id]){
            tpsShippingCalculation[id] = {};
        }
        tpsShippingCalculation[id]['shipping_ratio'] = parseFloat($(this).val())

        // Sum all shipping ratio to prevent over 100%
        let totalShippingRatio = 0;
        $.each(tpsShippingCalculation, function (key, valueObj) {
            totalShippingRatio += parseFloat(valueObj['shipping_ratio']);
        });
        if (totalShippingRatio > 100) {
            toastr.error('{{__('tpsTransfer::lang.sum_of_shipping_ratios_are_more_than_100')}}');
        }

        ratio = parseFloat($(this).val())
        shipping_value = parseFloat($('#shipping_charges').val())
        transfer_quantity = parseInt($(this).attr('data-transfer-quantity'))
        purchase_price = parseFloat($(this).attr('data-purchase-price'))
        total_transfer_quantity = parseInt($(this).attr('data-total-transfer-quantity'))

        value_per_unit = ((shipping_value * (ratio / 100)).toFixed(2)) /  transfer_quantity;
        tpsShippingCalculation[id]['value_per_unit'] = value_per_unit
        tpsShippingCalculation[id]['unit_price_after_shipping'] = purchase_price + value_per_unit;

        $('#shipping_value_per_unit_'+id).html(value_per_unit);
        $('#unit_price_after_shipping_'+id).html(purchase_price + value_per_unit);
        $('#total_price_after_shipping_'+id).html( (purchase_price + value_per_unit) * transfer_quantity);
    });

    $(document).on("click", "#confirm_shipping_modal_button", function (e) {
        // Prevent actual form submission
        e.preventDefault();
        let shipping_method = $('#shipping_method').val();

        // Sum all shipping ratio to prevent over 100%
        let totalShippingRatio = 0;
        $.each(tpsShippingCalculation, function (key, valueObj) {
            totalShippingRatio += parseFloat(valueObj['shipping_ratio']);
        });
        if (shipping_method !== 'as_charge' && totalShippingRatio !== 100) {
            toastr.error('{{__('tpsTransfer::lang.sum_of_shipping_ratios_not_equal_100')}}');
            return;
        }

        $.blockUI({ message: '{{__('tpsTransfer::lang.preparing_data')}}' });

        $('#shipping-product-table').DataTable().page.len( -1 ).ajax.reload( function() { //todo need testing
            $.blockUI({ message: '{{__('tpsTransfer::lang.inserting_data')}}' });

            // Send data by ajax to server side to start auto process and return with products and qty
            $.ajax({
                type: 'PUT',
                url: '{{action('\Modules\AdvancedTransfer\Http\Controllers\TpsPrepareStockController@storeShipping')}}',
                data: {
                    data: $('#add_shipping_table_form').serialize(),
                    tpsShippingCalculation: tpsShippingCalculation,
                    from_location_id: $('#from_location_id').val(),
                    to_location_id: $('#to_location_id').val(),
                },
                beforeSend: function() {
                    requestWaitingMessage()
                    $.blockUI({ message: $('#block-waiting-div') });
                    $("#add_shipping").modal('hide');
                },
                success: function(r) {
                    // console.log('success')
                    if((r.status) && (r.status == 'success')){
                        $.unblockUI();
                        if(r.redirect){
                            window.location.href = r.redirect;
                        }
                    }else{
                        $.unblockUI();
                        toastr.error('{{__('tpsTransfer::lang.an_error_has_been_occurred')}}');
                        return;
                    }
                    return
                },
                error: function(xhr) { // if error occurred
                    $.unblockUI();
                    toastr.error('{{__('tpsTransfer::lang.an_error_has_been_occurred')}}');
                    return;
                }
            });
        })
    });

    function autoChangeDataTable() {
        $('#shipping-product-table').DataTable().ajax.reload();
    }
</script>