@extends('layouts.app')
@section('title', __('tpsTransfer::lang.add'))

@section('content')

    <link rel="stylesheet" href="https://cdn.datatables.net/rowgroup/1.1.4/css/rowGroup.dataTables.min.css">
    <!-- Content Header (Page header) -->
    <section class="content-header">
        <h1>@lang('lang_v1.add_stock_transfer')</h1>
        <!-- <ol class="breadcrumb">
            <li><a href="#"><i class="fa fa-dashboard"></i> Level</a></li>
            <li class="active">Here</li>
        </ol> -->
    </section>

    <!-- Main content -->
    <section class="content">
        <div class="row">
            <div class="col-md-12">
                <div class="box box-solid">
                    <div aria-expanded="true">
                        <div class="box-body">
                            <div class="col-md-3">
                                <div class="form-group">
                                    {!! Form::label('transaction_date', __('messages.date') . ':*') !!}
                                    <div class="input-group">
                                        <span class="input-group-addon">
                                            <i class="fa fa-calendar"></i>
                                        </span>
                                        {!! Form::text('transaction_date', @format_datetime('now'), ['class' => 'form-control', 'readonly', 'required']); !!}
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-3" id="from_location_filter">
                                <div class="form-group">
                                    {!! Form::label('from_location_id',  __('tpsTransfer::lang.from').__('purchase.business_location') . ':') !!}
                                    {!! Form::select('from_location_id', $fromBusinessLocations, [], ['id' => 'from_location_id', 'class' => 'form-control select2 main-inputs', 'style' => 'width:100%', 'multiple']); !!}
                                </div>
                            </div>
                            <div class="col-md-3" id="to_location_filter">
                                <div class="form-group">
                                    {!! Form::label('to_location_id',  'To '.__('purchase.business_location') . ':') !!}
                                    {!! Form::select('to_location_id', $toBusinessLocations, null, ['id' => 'to_location_id', 'class' => 'form-control select2 main-inputs', 'style' => 'width:100%']); !!}
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-md-12">
                @component('components.filters', ['title' => __('report.filters')])
                    <div class="col-md-3">
                        <div class="form-group">
                            {!! Form::label('type', __('product.product_type') . ':') !!}
                            {!! Form::select('type', ['single' => __('lang_v1.single'), 'variable' => __('lang_v1.variable'), 'combo' => __('lang_v1.combo')], null, ['class' => 'form-control select2', 'style' => 'width:100%', 'id' => 'filter_type', 'placeholder' => __('lang_v1.all')]); !!}
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="form-group">
                            {!! Form::label('filter_category_id', __('product.category') . ':') !!}
                            {!! Form::select('filter_category_id', $categories, [], ['class' => 'form-control select2 categories-select-list', 'style' => 'width:100%', 'id' => 'filter_category_id', 'placeholder' => __('lang_v1.all'), 'data-sub-id' => '#filter_sub_category_id']); !!}
                        </div>
                    </div>

                    <div class="col-md-3">
                        <div class="form-group">
                            {!! Form::label('filter_sub_category_id', __('product.sub_category') . ':') !!}
                            {!! Form::select('filter_sub_category_id', [], [], ['class' => 'form-control select2', 'style' => 'width:100%', 'id' => 'filter_sub_category_id']); !!}
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="form-group">
                            {!! Form::label('filter_brand_id', __('product.brand') . ':') !!}
                            {!! Form::select('filter_brand_id', $brands, null, ['class' => 'form-control select2', 'style' => 'width:100%', 'id' => 'filter_brand_id', 'placeholder' => __('lang_v1.all')]); !!}
                        </div>
                    </div>
                    <div class="col-md-3" id="from_location_filter">
                        <div class="form-group">
                            {!! Form::label('filter_from_location_id',  __('tpsTransfer::lang.from').__('purchase.business_location') . ':') !!}
                            {!! Form::select('filter_from_location_id', [], [], ['id' => 'filter_from_location_id', 'class' => 'form-control select2', 'style' => 'width:100%', 'multiple']); !!}
                        </div>
                    </div>
                @endcomponent
            </div>
        </div>
        @component('components.widget', ['class' => 'box-primary', 'title' => __('tpsTransfer::lang.add_products')])
            @slot('tool')
                <div class="box-tools">
                    @can('tpsTransfer.can_access_auto_add_products')
                        <span class="btn btn-warning auto_product_modal">@lang( 'product.auto_generate' )</span>
                    @endcan
                    <span class="btn btn-primary add_product_modal"><i class="fas fa-plus"></i> @lang( 'product.add_product' )</span>
                </div>
            @endslot
            <table class="table table-bordered ajax_view hide-footer display" id="product_table" style="width: 100%;">
                <thead>
                <tr>
                    <th style="width:20%">@lang('sale.product')</th>
                    <th>@lang('product.sku')</th>
                    <th>@lang('product.category')</th>
                    <th>@lang('product.brand')</th>
                    @can('view_purchase_price')
                        <th style="width:4px">@lang('tpsTransfer::lang.avg_unit_purchase_price')</th>
                    @endcan
                    <th>@lang('purchase.business_location')</th>
                    <th style="width:4px">@lang('tpsTransfer::lang.from_location_stock')</th>
                    <th style="width:4px">@lang('tpsTransfer::lang.committed')</th>
                    <th>@lang('lang_v1.stock_transfer')</th>
                    <th style="width:4px">@lang('tpsTransfer::lang.to_location_stock')</th>
                    <th>@lang('product.product_type')</th>
                    <th>@lang('messages.action')</th>
                </tr>
                </thead>
            </table>
            <div class="form-group text-center">
                <button id="saveAddProductData" class="btn btn-primary btn-flat btn-login">@lang('messages.save')</button>
            </div>
        @endcomponent
    </section>
    <!-- /.content -->

    <!-- Add Manual Product Modal -->
    <div class="modal fade" id="add_product" tabindex="-1" role="dialog">
        <div class="modal-dialog modal-xl" role="document">
            <div class="modal-content">
                {!! Form::open(['id' => 'add_product_table_form' ]) !!}
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                    <h4 class="modal-title" id="modalTitle">@lang( 'product.import_products' )</h4>
                </div>
                <div class="modal-body" id="add_product_modal_body">
                </div>
                <div class="modal-footer">
                    <div class='text-center'>
                        <span id="add_product_modal_buttom" class="btn btn-primary">@lang( 'messages.add' )</span>
                        <button type="button" class="btn btn-default" data-dismiss="modal">@lang( 'messages.close' )</button>
                    </div>
                </div>
                {!! Form::close() !!}

            </div><!-- /.modal-content -->
        </div><!-- /.modal-dialog -->
    </div>

    @can('tpsTransfer.can_access_auto_add_products')
    <!-- Auto Auto Product Modal -->
    <div class="modal fade" id="auto_product" tabindex="-1" role="dialog">
        <div class="modal-dialog modal-xl" role="document">
            <div class="modal-content">
                {!! Form::open(['url' => action('\\App\Http\Controllers\ProductController@saveQuickProduct'), 'method' => 'post', 'id' => 'add_product_table_form' ]) !!}
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                    <h4 class="modal-title" id="modalTitle">@lang( 'product.import_products' )</h4>
                </div>
                <div class="modal-body">
                    <div class="row">
                        <div class="col-md-4">
                            <div class="form-group">
                                {!! Form::label('auto_category_id', __('category.select_parent_category') . ':') !!}
                                {!! Form::select('auto_category_id', $categories, [], ['class' => 'form-control select2 categories-select-list', 'style' => 'width:100%', 'id' => 'auto_category_id', 'placeholder' => __('lang_v1.all'), 'data-sub-category' => '#auto_sub_category_id', 'data-sub-id' => '#auto_sub_category_id']); !!}
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="form-group">
                                {!! Form::label('auto_sub_category_id', __('category.category') . ':') !!}
                                {!! Form::select('auto_sub_category_id', [], [], ['class' => 'form-control select2', 'style' => 'width:100%', 'id' => 'auto_sub_category_id']); !!}
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="form-group">
                                {!!Form::label('brand_id', 'Select sub '.__('brand.brand_name'). ':') !!}
                                {!!Form::select('brand_id', $brands, null, ['id' => 'brand_id', 'class' => 'form-control select2', 'style' => 'width:100%']); !!}
                            </div>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-4">
                            <div class="form-group">
                                <label for="sel1">{{__('tpsTransfer::lang.selling_period')}}</label>
                                <input type="number" class="form-control" id="selling-period" placeholder="selling period by day(s)" value="{{$setting['sellingPeriod'] ?? null}}">
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="form-group">
                                <label for="sel1">{{__('tpsTransfer::lang.future_period')}}</label>
                                <input type="number" class="form-control" id="future-period" placeholder="future period by day(s)" value="{{$setting['futurePeriod'] ?? null}}">
                            </div>
                        </div>
                    </div>
                    <div class="float-right" style="margin: 0;"></div>

                    <div class="col-sm-12 align-right"></div>
                </div>
                <div class="modal-footer">
                    <span id="auto_product_modal_buttom" class="btn btn-primary">@lang( 'messages.add' )</span>
                    <button type="button" class="btn btn-default" data-dismiss="modal">@lang( 'messages.close' )</button>
                </div>
                {!! Form::close() !!}
            </div><!-- /.modal-content -->
        </div><!-- /.modal-dialog -->
    </div>
    @endcan
    <!-- Notes Modal -->
    <div class="modal fade" id="add_notes" role="dialog">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal">&times;</button>
                    <h4 class="modal-title">{{__('purchase.additional_notes')}}</h4>
                </div>
                <div class="modal-body">
                    <textarea rows='5' style="width:100%;" id="notes_content" name=""></textarea>
                </div>
                <div class="modal-footer">
                    <div class='text-center'>
                        <button type="button" class="btn btn-default" data-dismiss="modal">{{__('messages.close')}}}</button>
                        <button type="button" data-pvl="" data-dismiss="modal" class="btn btn-info save_notes_button" id="save_notes_button">{{__('messages.save')}}</button>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Delete Confirm Modal -->
    @if (auth()->user()->can('tpsTransfer.can_delete_nst_row'))
        <div class="modal fade" id="delete_confirm" role="dialog">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal">&times;</button>
                        <h4 class="modal-title">{{ __('tpsTransfer::lang.confirm_delete') }}</h4>
                    </div>
                    <div class="modal-body">
                        <h3>{!! __('tpsTransfer::lang.confirm_delete_message') !!}</h3>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-default" data-dismiss="modal">{{__('messages.close')}}</button>
                        <button type="button" data-pvl="" data-dismiss="modal" class="btn btn-danger confirm_delete_row_button" id="delete_row_button">{{__('messages.delete')}}</button>
                    </div>
                </div>
            </div>
        </div>
    @endif

    <!-- Product info modal -->
    <div class="modal fade" tabindex="-1" role="dialog" id="view_product_modal">
    </div>
@endsection

@section('javascript')
    <script src="https://cdn.datatables.net/rowgroup/1.1.4/js/dataTables.rowGroup.min.js"></script>
    <script src="{{ asset('js/product.js?v=' . $asset_v) }}"></script>
    <script src="{{ asset('js/opening_stock.js?v=' . $asset_v) }}"></script>
    <script type="text/javascript">
        let pvid = [];
        // let pvid = ['16-16'];

        let manualTpsData = new Object();
        let autoTpsData = new Object();
        let removedOptions = new Object();

        $(document).ready(function () {
            $.ajax({
                url: '{{action('\Modules\AdvancedTransfer\Http\Controllers\TpsAddStockController@showCategory')}}',
                dataType: "JSON",
                success: function (data) {
                    var category_list = "<option value='all' selected='selected'>" + "All" + "</option>";
                    for (i in data) {
                        category_list += "<option value=" + data[i].id + ">" + data[i].name + "</option>";
                    }
                    $("#category_id").html(category_list);
                }
            });

            product_table = $('#product_table').DataTable({
                aaSorting: [],
                rowGroup: {
                    dataSrc: function(data) {
                        return data.product+'-'+data.sku
                    },
                    startRender: function ( rows, group ) {
                        return '<a onclick="callCoreProductInfoModal(this)" data-href="'+rows.data()[0]['data-href']+'">'+group+'</a>';
                    }
                },
                endRender: null,
                dataSrc: 'company',
                processing: true,
                serverSide: true,
                scrollY: "130vh",
                scrollX: true,
                scrollCollapse: true,
                lengthMenu: [[10, 25, 50, 200, 500], [10, 25, 50, 200, 500]],
                ajax: {
                    "url": '{{action('\Modules\AdvancedTransfer\Http\Controllers\TpsAddStockController@table')}}',
                    "type": "POST",
                    "data": function (d) {
                        d.pvid = JSON.stringify(pvid);
                        d.from_location_id = $('#from_location_id').val()
                        d.to_location_id = $('#to_location_id').val()
                        d.type = $('#filter_type').val();
                        d.category_id = $('#filter_category_id').val();
                        d.sub_category_id = $('#filter_sub_category_id').val();
                        d.filter_from_location_id = $('#filter_from_location_id').val();
                        d.brand_id = $('#filter_brand_id').val();
                        d.location_id = $('#location_id').val();
                    }
                },
                columns: [
                    {data: 'productEdited', name: 'products.name', className: "clickable_td"},
                    {data: 'sku', name: 'products.sku'},
                    {data: 'category', name: 'c1.name'},
                    // {data: 'sub_category', name: 'c2.name'},
                    {data: 'brand', name: 'brands.name'},
                    @can('view_purchase_price')
                        { data: 'purchase_price', name: 'purchase_price', searchable: false, sortable: false},
                    @endcan
                    {data: 'bl_name', name: 'bl.name'},
                    {data: 'from_stock_span', name: 'vld.qty_available', searchable: false},
                    {data: 'committed_qty_display', name: 'committed_qty_display', orderable: false, searchable: false},
                    {data: 'stock_transfer', sortable: false, searchable: false, className: "clickable_td"},
                    {data: 'to_stock', name: 'to_vld.qty_available', searchable: false},
                    {data: 'type', name: 'products.type'},
                    {data: 'actions', name: 'actions', sortable: false, searchable: false, className: "clickable_td"},
                ],
                rowCallback: function (row, data) {
                    // write old inputs
                    if(manualTpsData[data['pvl']]){
                        if(manualTpsData[data['pvl']]['transfer_quantity']){
                            $(row).find('input[type="number"]').val(manualTpsData[data['pvl']]['transfer_quantity']);
                        }

                        if(manualTpsData[data['pvl']]['is_important'] == 1){
                            $(row).find('input[type="checkbox"]').prop('checked', true);
                            $(row).addClass("bg-yellow");
                        }

                        if(manualTpsData[data['pvl']]['note']){
                            if (manualTpsData[data['pvl']]['note'] != "") {
                                $(row).find('#actions_btn_'+data['pvl']).addClass("btn-success")
                            } else {
                                $(row).find('#actions_btn_'+data['pvl']).removeClass("btn-success")
                            }
                        }
                    }
                    else{
                        manualTpsData[data['pvl']] = {};
                        array = data['pvl'].split("-");
                        manualTpsData[data['pvl']]['to_location_id'] = $("#to_location_id").select2("val");

                        {{--manualTpsData[data['pvl']]['created_at'] = "{{date('Y-m-d H:i:s')}}";--}}
                        {{--manualTpsData[data['pvl']]['updated_at'] = "{{date('Y-m-d H:i:s')}}";--}}

                        manualTpsData[data['pvl']]['product_id'] = array[0];
                        manualTpsData[data['pvl']]['variation_id'] = array[1];
                        manualTpsData[data['pvl']]['from_location_id'] = array[2];
                        manualTpsData[data['pvl']]['purchase_lines_id'] = null;

                        manualTpsData[data['pvl']]['transfer_quantity'] = 0;
                        manualTpsData[data['pvl']]['is_important'] = 0;
                        manualTpsData[data['pvl']]['note'] = null;
                        manualTpsData[data['pvl']]['custom_field'] = data['custom_field'];
                    }

                    // If bpv is in autoTpsData
                    if (autoTpsData[data['pv']]) {
                        // Prevent re-calculating the need for this product after it was previously calculated
                        if(manualTpsData[data['pvl']] && parseInt(manualTpsData[data['pvl']]['transfer_quantity']) > 0){
                            return;
                        }

                        /**
                         * Quantity already in transit to the TO location
                         * (committed to other pending transfers: status prepare/receive)
                         * @type {number}
                         */
                        inTransitQty = parseInt(autoTpsData[data['pv']]['in_transit_qty']) || 0;

                        /**
                         * Effective available quantity in TO location =
                         * physical stock + quantity already in transit to it.
                         * The auto equation subtracts this from the required qty,
                         * so: transfer = required - (to_stock + in_transit).
                         * @type {number}
                         */
                        toQty = (parseInt(autoTpsData[data['pv']]['to_stock']) || 0) + inTransitQty;

                        /**
                         * Total sold in TO location from auto result
                         * @type {number}
                         */
                        sQty = parseInt(autoTpsData[data['pv']]['total_sold']);

                        /**
                         * Future Period need to cover
                         * @type {number}
                         */
                        futPerd = parseInt(autoTpsData[data['pv']]['futurePeriod']);

                        /**
                         * Selling Period
                         * @type {number}
                         */
                        slngPerd = parseInt(autoTpsData[data['pv']]['sellingPeriod']);

                        /**
                         * the untouched transfer quantity depend on needs by intervals Selling Period and Future Period
                         * @type {number}
                         */
                        cQtyUnTouched = Math.ceil( ( ( (sQty / slngPerd) * futPerd) ));

                        /**
                         * Location custom field
                         * @type {number}
                         */
                        locationCustomField = parseInt(manualTpsData[data['pvl']]['custom_field']);

                        if((autoTpsData[data['pv']]['transferQty']) && ( (autoTpsData[data['pv']]['transferQty'] + toQty) == cQtyUnTouched)){
                            delete autoTpsData[data['pv']];
                            return
                        }

                        /**
                         * the equation to get the transfer quantity depend on needs by intervals Selling Period and Future Period
                         */
                         if(autoTpsData[data['pv']]['cQtyModified']){
                             cQty = autoTpsData[data['pv']]['cQtyModified']
                         }else{
                             cQty = cQtyUnTouched;
                         }

                        /**
                         * Available quantity in From location from result render product in table
                         * @type {number}
                         */
                        fromQty = parseInt(data['from_stock']);

                        /**
                         * is important check
                         * @type {number}
                         */
                        iCheck = 0;

                        /**
                         * tQty is transfer quantity
                         * @type {number}
                         */
                        tQty = 0;

                        auto_debug_pv = 'xx-xx';
                        // auto_debug_mode = (typeof auto_debug_pv !== 'undefined') && (data['pv'] == auto_debug_pv);
                        auto_debug_mode = true;

                        if (auto_debug_mode) {
                            console.log('autoTpsData = '+ autoTpsData[data['pv']])
                            console.log('data["pv"] = '+ data['pv'])
                            console.log('inTransitQty  = '+ inTransitQty)
                            console.log('toQty (to_stock + in_transit) = '+ toQty)
                            console.log('sQty  = '+ sQty)
                            console.log('cQty  = '+ cQty)
                            console.log('slngPerd  = '+ slngPerd)
                            console.log('futPerd  = '+ futPerd)
                            console.log('fromQty  = '+ fromQty)
                            console.log('locationCustomField  = '+ locationCustomField)
                        }


                        // if there is no stock in TO location and doesn't have any selling from this product
                        if ((toQty == sQty) && (toQty == 0)) {
                            tQty = 1
                            if ((fromQty - locationCustomField) <= 0) {
                                tQty = 0
                            }
                            iCheck = 1;

                            if(auto_debug_mode){
                                console.log('case 0')
                            }
                        } else {
                            if (toQty < cQty) {
                                if (fromQty > (cQty - toQty)) {
                                    tQty = cQty - toQty;
                                    iCheck = 0;

                                    if(auto_debug_mode){
                                        console.log('fromQty = ' + fromQty)
                                        console.log('cQty = ' + cQty)
                                        console.log('toQty = ' + toQty)

                                        console.log('case 1')
                                    }
                                } else if (fromQty == (cQty - toQty)) {
                                    tQty = (cQty - toQty) - locationCustomField;
                                    iCheck = 0;

                                    if(auto_debug_mode){
                                        console.log('fromQty = ' + fromQty)
                                        console.log('cQty = ' + cQty)
                                        console.log('toQty = ' + toQty)

                                        console.log('case 2')
                                    }
                                } else if (fromQty < (cQty - toQty)) {
                                    tQty = fromQty - locationCustomField;
                                    iCheck = 0;

                                    if(auto_debug_mode){
                                        console.log('fromQty = ' + fromQty)
                                        console.log('cQty = ' + cQty)
                                        console.log('toQty = ' + toQty)

                                        console.log('case 3')
                                    }
                                }
                            }else{
                                tQty = 0;

                                if(auto_debug_mode){
                                    console.log('fromQty = ' + fromQty)
                                    console.log('cQty = ' + cQty)
                                    console.log('toQty = ' + toQty)
                                    console.log('sQty = ' + sQty)

                                    console.log('else')
                                }
                            }
                        }

                        // console.log('tQty  = '+ tQty)
                        $(row).find('input[type="number"]').val(tQty);

                        if(!manualTpsData[data['pvl']]){
                            manualTpsData[data['pvl']] = {};
                        }
                        manualTpsData[data['pvl']]["transfer_quantity"] = tQty;

                        // Check if already put some/all Qty in transferQty
                        if(!autoTpsData[data['pv']]['transferQty']){
                            autoTpsData[data['pv']]['transferQty'] = tQty;
                        } else {
                            autoTpsData[data['pv']]['transferQty'] = parseInt(autoTpsData[data['pv']]['transferQty']) + tQty;
                        }

                        if(!autoTpsData[data['pv']]['cQtyModified']){
                            autoTpsData[data['pv']]['cQtyModified'] = cQty - tQty;
                        } else {
                            autoTpsData[data['pv']]['cQtyModified'] = parseInt(autoTpsData[data['pv']]['cQtyModified']) - tQty;
                        }

                        if(autoTpsData[data['pv']]['transferQty'] >= (cQtyUnTouched + toQty)){
                            delete autoTpsData[data['pv']];
                        }
                    }
                },
            });

            $(document).on('change', '#filter_type, #filter_category_id, #filter_sub_category_id, #filter_from_location_id, #filter_brand_id, #location_id',function () {
                $('#product_table').DataTable().ajax.reload();
            });

        });

        function reloadProductDatatable(temp_rows_selected) {
            pvid = $.merge(temp_rows_selected, pvid);
            $('#product_table').DataTable().ajax.reload();
        }

        $(document).on("change", ".lot-numbers", function () {
            pvl = $(this).data('pvl')
            $(this).parent().parent().find('input[type=number]').prop('max',$(this).find(':selected').data('qty-available')).change();
            $(this).parent().parent().find('.current-stock-qty').html(parseInt($(this).find(':selected').data('qty-available')));
            @can('view_purchase_price')
                $(this).parent().parent().find('.purchase-price').html(parseFloat($(this).find(':selected').data('purchase-price')));
            @endcan
        });
        // Return add product modal content
        $(document).on("click", ".add_product_modal", function (e) {
            e.preventDefault();
            let from_location = $("#from_location_id").select2("val");
            let to_location = $("#to_location_id").select2("val");
            if (from_location == '' || to_location == '') {
                toastr.error('select location.');
                return;
            }

            $.ajax({
                type: 'GET',
                url: '{{action('\Modules\AdvancedTransfer\Http\Controllers\TpsAddStockController@manualTempProduct')}}',
                data: {
                    from_location: from_location,
                    to_location: to_location
                },
                success: function (response) {
                    // Add response in Modal body
                    $('#add_product_modal_body').html(response);
                    //disable main inputs like locations (from - to)
                    $('.main-inputs').attr('disabled', true);

                    // Display Modal
                    $("#add_product").modal('show');
                }
            });

        });

        // Return auto product modal content
        $(document).on("click", ".auto_product_modal", function (e) {
            e.preventDefault();

            let from_location = $("#from_location_id").select2("val");
            let to_location = $("#to_location_id").select2("val");
            if (from_location == '' || to_location == '') {
                toastr.error('select location.');
                return;
            }
            $('.main-inputs').attr('disabled', true);
            $("#auto_product").modal('show');
        });

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

            // Check if period > 0 or not
            if(!parseInt($("#selling-period").val()) > 0){
                toastr.error('{{__('tpsTransfer::lang.selling_period_more_1_day')}}');
                return;
            }
            if(!parseInt($("#future-period").val()) > 0){
                toastr.error('{{__('tpsTransfer::lang.future_period_more_1_day')}}');
                return;
            }

            // Send data by ajax to server side to start auto process and return with products and qty
            $.ajax({
                type: 'POST',
                url: '{{action('\Modules\AdvancedTransfer\Http\Controllers\TpsAddStockController@autoTempProduct')}}',
                data: {
                    from_location_id: $("#from_location_id").select2("val"),
                    to_location_id: $("#to_location_id").select2("val"),
                    category_id: $("#auto_category_id").select2("val"),
                    sub_category_id: $("#auto_sub_category_id").select2("val"),
                    brand_id: $("#brand_id").select2("val"),
                    selling_period: $("#selling-period").val(),
                    future_period: $("#future-period").val()
                },
                success: function (response){
                    if(JSON.parse(response).length == 0){
                        toastr.error('{{__('tpsTransfer::lang.auto_calculate_return_0_products')}}');
                    }
                    else{
                        // Fresh response must override any stale accumulated entry
                        // (e.g. an outdated in_transit_qty from a previous run).
                        // $.extend(target, source): source wins -> response is source.
                        autoTpsData = $.extend(autoTpsData, JSON.parse(response));
                        pvid = $.merge(Object.keys(autoTpsData), pvid);

                        $('#product_table').DataTable().ajax.reload();
                    }
                    // Hide auto product modal
                    $("#auto_product").modal('hide');
                }
            });
        });

        //Date picker
        $('#transaction_date').datetimepicker({
            format: moment_date_format + ' ' + moment_time_format,
            ignoreReadonly: true,
        });

        // Get product info
        function callCoreProductInfoModal(el) {
            $.ajax({
                url: $(el).data('href'),
                dataType: 'html',
                success: function(result) {
                    $('#view_product_modal').html(result).modal('show');
                },
            });

        }

        $("body").on("click",".save_notes_button",function(){
            content = $("#notes_content").val();
            $("#notes_content").val('');

            pvl = $(this).data("pvl");
            if(!manualTpsData[pvl]){
                manualTpsData[pvl] = {};
            }
            manualTpsData[pvl]["note"] = content;

            if (content != "") {
                $("#actions_btn_"+pvl).addClass("btn-success");
                $("#actions_btn_"+pvl).removeClass("btn-primary");
            } else {
                $("#actions_btn_"+pvl).removeClass("btn-success");
                $("#actions_btn_"+pvl).addClass("btn-primary");
            }
        })

        $(document).on("click", ".add_notes", function () {
            pvl = $(this).data('pvl');
            $("#save_notes_button").data('pvl',pvl);

            if((manualTpsData[pvl]) && (manualTpsData[pvl]['note']) ){
                $("#notes_content").val(manualTpsData[pvl]['note']);
            }
        });

        $(document).on("click", ".delete_row_button", function () {
            pvl = $(this).data('pvl');
            $("#delete_row_button").data('pvl',pvl);
        });

        $(document).on("click", ".confirm_delete_row_button", function () {
            pvl = $(this).data('pvl');
            if(manualTpsData[pvl]){
                delete manualTpsData[pvl]
            }

            pv = pvl.slice(0, pvl.lastIndexOf('-'));
            if(autoTpsData[pv]){
                delete autoTpsData[pv]
            }

            pvid.splice( $.inArray(pv,pvid) ,1 );
            $('#product_table').DataTable().ajax.reload();
        });

        $(document).on("keyup change", ".product-row-input", function (e) {
            pvl = $(this).data('pvl');
            name = $(this).data('name');

            if(!manualTpsData[pvl]){
                manualTpsData[pvl] = {};
            }
            if(name == 'is_important'){
                if($(this).is(":checked")){
                    manualTpsData[pvl]['is_important'] = 1;
                    $("#tr-"+pvl).addClass("bg-yellow");
                }else{
                    manualTpsData[pvl]['is_important'] = 0;
                    $("#tr-"+pvl).removeClass("bg-yellow");
                }
            }else if(name == 'purchase_lines_id'){
                manualTpsData[pvl]["purchase_lines_id"] = $(this).find(':selected').data('lot-id');
            }else if(name == 'transfer_quantity'){
                manualTpsData[pvl]["transfer_quantity"] = $(this).val();
            }else{
                manualTpsData[pvl][name] = $(this).val();
            }
        });

        $(document).on("keyup change", ".transfer_quantity", function () {
            // Get value of input, max and min
            var current = $(this).val();
            var min = parseInt($(this).attr("min"));
            var max = parseInt($(this).attr("max"));

            // Compare the max and min with the current value
            if (current <= max) {
                return;
            } else {
                $(this).val(max)
            }
        });

        $(document).on("click", "#saveAddProductData", function (e) {
            // Prevent actual form submission
            e.preventDefault();
            // Guard: prevent re-submission while a previous request is in flight
            if ($(this).data('submitting')) {
                return;
            }
            $(this).data('submitting', true);
            // $('#loadingDiv .letters').html('Preparing data..');
            $.blockUI({ message: '{{__('tpsTransfer::lang.preparing_data')}}' });

            $('#product_table').DataTable().page.len( -1 ).ajax.reload().one('draw', function() {
                // $.unblockUI();
                // // $('#test-test .letters').html('Inserting data..');
                // $.blockUI({ message: $('#test-test') });

                $.each(manualTpsData, function(key,valueObj){
                    if(valueObj['transfer_quantity'] == 0){
                        delete manualTpsData[key]
                    }
                });

                // Send data by ajax to server side to start auto process and return with products and qty
                $.ajax({
                    // dataType : "json",
                    // contentType: "application/json; charset=utf-8",
                    type: 'POST',
                    url: '{{action('\Modules\AdvancedTransfer\Http\Controllers\TpsPrepareStockController@store')}}',
                    data: {
                        _token: $("meta[name='csrf-token']").attr("content"),
                        transaction_date: $('#transaction_date').val(),
                        manualTpsData: JSON.stringify(manualTpsData),
                        autoTpsData: JSON.stringify(autoTpsData),
                    },
                    success: function(r) {
                        // console.log('success')
                        if((r.status) && (r.status == 'success')){
                            $.unblockUI();
                            window.location.href = "{{action('\Modules\AdvancedTransfer\Http\Controllers\TpsPrepareStockController@index')}}";
                        }else{
                            $.unblockUI();
                            $('#saveAddProductData').data('submitting', false);
                            toastr.error('{{__('tpsTransfer::lang.an_error_has_been_occurred')}}');
                            return;
                        }
                        return
                    },
                    error: function(xhr) { // if error occurred
                        $.unblockUI();
                        $('#saveAddProductData').data('submitting', false);
                        toastr.error('{{__('tpsTransfer::lang.an_error_has_been_occurred')}}');
                        return;
                    }
                });
            })
        });

        $("#from_location_id").on("select2:select", function(evt) {
            $("#to_location_id option[value="+evt.params.data.id+"]").remove();

            var selectedOption = new Option(evt.params.data.text, evt.params.data.id);
            $('#filter_from_location_id').append(selectedOption).trigger("change");

            // Keep select2 order by selection
            var element = evt.params.data.element;
            var $element = $(element);

            if ($(this).find(":selected").length > 1) {
                var $second = $(this).find(":selected").eq(-1);
                $second.after($element);
            } else {
                $element.detach();
                $(this).prepend($element);
            }
            $(this).trigger("change");
        });

        $("#from_location_id").on("select2:unselecting", function(evt) {
            // Get unselected option
            var unselectedOption = new Option(evt.params.args.data.text, evt.params.args.data.id);

            // Append it to the select
            $('#to_location_id').append(unselectedOption).trigger("change");
        });

        $('body').on('change', '.categories-select-list', function() {
            var category = $(this).val();
            var sub_id = $(this).data('sub-id');

            if(category == ''){
                $(sub_id).html('<option value="">None</option>')
                return;
            }
            $.ajax({
                method: 'POST',
                url: "{{ action('\\App\\Http\\Controllers\\ProductController@getSubCategories') }}",
                dataType: 'html',
                data: { cat_id: category },
                success: function(result) {
                    if (result) {
                        $(sub_id).html(result);
                    }
                },
            });
        });

        $(document).on('click', '.actions-list .dropdown-menu', function (e) {
            e.stopPropagation();
        });
    </script>

    <script src="https://malsup.github.io/jquery.blockUI.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/animejs/2.0.2/anime.min.js"></script>
    <script>
        // Wrap every letter in a span
        var textWrapper = document.querySelector('.ml1 .letters');
        if(textWrapper !== null){
            textWrapper.innerHTML = textWrapper.textContent.replace(/\S/g, "<span class='letter'>$&</span>");

            anime.timeline({loop: true})
                .add({
                    targets: '.ml1 .letter',
                    scale: [0.3,1],
                    opacity: [0,1],
                    translateZ: 0,
                    easing: "easeOutExpo",
                    duration: 600,
                    delay: (el, i) => 70 * (i+1)
                }).add({
                targets: '.ml1 .line',
                scaleX: [0,1],
                opacity: [0.5,1],
                easing: "easeOutExpo",
                duration: 700,
                offset: '-=875',
                delay: (el, i, l) => 80 * (l - i)
            }).add({
                targets: '.ml1',
                opacity: 0,
                duration: 1000,
                easing: "easeOutExpo",
                delay: 1000
            });
        }

        $(document).on('shown.bs.modal', 'div.view_product_modal, div.view_modal, #view_product_modal',
            function(){
                var div = $(this).find('#view_product_stock_details');
                if (div.length) {
                    $.ajax({
                        url: "{{action('\App\Http\Controllers\ReportController@getStockReport')}}"  + '?for=view_product&product_id=' + div.data('product_id'),
                        dataType: 'html',
                        success: function(result) {
                            div.html(result);
                            __currency_convert_recursively(div);
                        },
                    });
                }
                __currency_convert_recursively($(this));
            });
    </script>
@endsection
