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

@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.all_stock_transfers')</h1>
    </section>

    <!-- Main content -->
    <section class="content">
        <div class="row">
            <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' => 'type', 'placeholder' => __('lang_v1.all')]); !!}
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="form-group">
                            {!! Form::label('category_id', __('product.category') . ':') !!}
                            {!! Form::select('category_id', $categories, null, ['class' => 'form-control select2', 'style' => 'width:100%', 'id' => 'category_id', 'placeholder' => __('lang_v1.all')]); !!}
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="form-group">
                            {!! Form::label('sub_category_id', __('product.sub_category') . ':') !!}
                            {!! Form::select('sub_category_id', [], [], ['class' => 'form-control select2', 'style' => 'width:100%', 'id' => 'sub_category_id']); !!}
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="form-group">
                            {!! Form::label('brand_id', __('product.brand') . ':') !!}
                            {!! Form::select('brand_id', $brands, null, ['class' => 'form-control select2', 'style' => 'width:100%', 'id' => 'brand_id', 'placeholder' => __('lang_v1.all')]); !!}
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="form-group">
                            {!! Form::label('from_location_id',  __('tpsTransfer::lang.from').__('purchase.business_location') . ':') !!}
                            {!! Form::select('from_location_id', $fromBusinessLocations, null, ['id' => 'from_location_id', 'class' => 'form-control select2 main-inputs', 'style' => 'width:100%']); !!}
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="form-group">
                            {!! Form::label('to_location_id',  'To '.__('purchase.business_location') . ':') !!}
                            {!! Form::select('to_location_id', [], null, ['id' => 'to_location_id', 'class' => 'form-control select2 main-inputs', 'style' => 'width:100%']); !!}
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="form-group">
                            {!! Form::label('shipping_id',  __('tpsTransfer::lang.shipping_no').':') !!}
                            {!! Form::select('shipping_id', [], null, ['id' => 'shipping_id', 'class' => 'form-control select2 main-inputs', 'style' => 'width:100%']); !!}
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="form-group">
                            {!! Form::label('nst_status',  __('sale.status').':') !!}

                            {!! Form::select('nst_status', ['all' => __('messages.all'), 'prepare' => __('tpsTransfer::lang.prepare'), 'receive' => __('tpsTransfer::lang.receive'), 'complete' => __('tpsTransfer::lang.complete'),], 'all', ['id' => 'nst_status', 'class' => 'form-control select2 main-inputs', 'style' => 'width:100%']); !!}
                        </div>
                    </div>
                @endcomponent
            </div>
        </div>
        @component('components.widget', ['class' => 'box-primary', 'title' => __('lang_v1.all_purchase_orders')])
            @php
                $colspan = 12;
                $custom_labels = json_decode(session('business.custom_labels'), true);
            @endphp
            <table class="table table-bordered table-striped ajax_view hide-footer" id="receive_data" style="width: 100%;">
                <thead>
                <tr>
                    <th>@lang('sale.product')</th>
                    <th>@lang('lang_v1.lot_number')</th>
                    <th>@lang('product.sku')</th>
                    <th>@lang('product.category')</th>
{{--                    <th>@lang('product.sub_category')</th>--}}
                    <th>@lang('product.brand')</th>
                    @can('view_purchase_price')
                        @php
                            $colspan += 2;
                        @endphp
                        <th>@lang('tpsTransfer::lang.avg_unit_purchase_price')</th>
                        <th>{{__('tpsTransfer::lang.shipping_price_per_unit')}}</th>
                    @endcan
                    <th>{{__('tpsTransfer::lang.from')}} @lang('purchase.business_location') @show_tooltip(__('lang_v1.product_business_location_tooltip'))</th>
                    <th>@lang('lang_v1.stock_transfer')</th>
                    <th>{{__('tpsTransfer::lang.to')}} @lang('purchase.business_location') @show_tooltip(__('lang_v1.product_business_location_tooltip'))</th>
                    <th>@lang('sale.status')</th>
                    <th>@lang('messages.action')</th>

                </tr>
                </thead>
            </table>
        @endcomponent
    </section>
    <!-- /.content -->

    <!-- 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>
        </div>
    </div>

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

@section('javascript')
    <script src="https://malsup.github.io/jquery.blockUI.js"></script>
    <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 nstData = new Object();

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

            receive_data = $('#receive_data').DataTable({
                aaSorting: [],
                rowGroup: {
                    dataSrc: function(data) {
                        return data.product_name+'-'+data.sku
                    },
                    startRender: function ( rows, group ) {
                        return '<a onclick="callCoreProductInfoModal(this)" data-href="'+rows.data()[0]['data-href']+'">'+group+'</a>';
                    }
                },
                processing: true,
                serverSide: true,
                scrollY: "130vh",
                scrollX: true,
                scrollCollapse: true,
                ajax: {
                    "url": "{{action('\Modules\AdvancedTransfer\Http\Controllers\TpsController@index')}}",
                    "type": "POST",
                    "data": function (d) {
                        d.type = $('#type').val();
                        d.category_id = $('#category_id').val();
                        d.sub_category_id = $('#sub_category_id').val();
                        d.brand_id = $('#brand_id').val();
                        d.from_location_id = $('#from_location_id').val();
                        d.to_location_id = $('#to_location_id').val();
                        d.shipping_id = $('#shipping_id').val();
                        d.nst_status = $('#nst_status').val();
                        d = __datatable_ajax_callback(d);
                    }
                },
                columnDefs: [ {
                    "targets": [0],
                    "orderable": false,
                    // "searchable": false
                } ],
                columns: [
                    {data: 'product_name', name: 'products.name'},
                    {data: 'lot_number', name: 'purchase_lines.lot_number'},
                    {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_lines.purchase_price', searchable: true},
                    { data: 'value_per_unit', name: 'value_per_unit', searchable: false},
                        @endcan
                    {data: 'from_location_name', name: 'from_business_locations.name'},
                    {data: 'transfer_quantity',},
                    {data: 'to_location_name', name: 'to_business_locations.name'},
                    {data: 'status', name: 'status', sortable: false, searchable: false, className: "button"},
                    {data: 'actions', name: 'actions', sortable: false, searchable: false, className: "button"},
                ],
                lengthMenu: [[10, 25, 50, 200, 500], [10, 25, 50, 200, 500]],
                rowCallback: function (row, data) {
                    if(data['is_important'] == 1){
                        $(row).addClass("bg-yellow");
                    }

                    if (data['note']) {
                        $(row).find('.add_notes').addClass("btn-success")
                        if(!nstData[data['id']]){
                            nstData[data['id']] = {}
                        }

                        nstData[data['id']]['note'] = data['note'];
                    }
                },
            });

            $(document).on('change', '#type, #category_id, #sub_category_id, #brand_id, #from_location_id, #to_location_id, #shipping_id, #nst_status', function(){
                $('#receive_data').DataTable().ajax.reload();
            });
        });

        jQuery(function($) {
            $('#from_location_id').on('change', function(e) {
                // Prevent actual form submission
                e.preventDefault();

                var from_location_id = $('#from_location_id').val();
                var status = $('#nst_status').val();

                $.ajax({
                    method: 'POST',
                    url: '{{action('\Modules\AdvancedTransfer\Http\Controllers\TpsController@getToLocationByFromLocationId')}}',
                    dataType: 'html',
                    data: { from_location_id: from_location_id, status: status, preAppendAll: true },
                    success: function(result) {
                        if (result) {
                            $('#to_location_id').html(result).change();
                        }
                    },
                });
            }).trigger('change');
        });

        jQuery(function($) {
            $('#to_location_id').on('change', function(e) {
                // Prevent actual form submission
                e.preventDefault();

                var from_location_id = $('#from_location_id').val();
                if(!from_location_id){
                    return
                }
                var to_location_id = $('#to_location_id').val();
                if(!to_location_id){
                    return
                }
                $.ajax({
                    method: 'POST',
                    url: '{{action('\Modules\AdvancedTransfer\Http\Controllers\TpsController@getShippingIdsWithLocations')}}',
                    dataType: 'html',
                    data: { from_location_id: from_location_id, to_location_id: to_location_id, preAppendAll: true},
                    success: function(result) {
                        if (result) {
                            $('#shipping_id').html(result).change();
                        }
                    },
                });
            }).trigger('change');
        });

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

        }

        $(document).on("click", ".add_notes", function () {
            id = $(this).data('id');
            if((nstData[id]) && (nstData[id]['note']) ){
                $("#notes_content").val(nstData[id]['note']);
            }
        });

        $(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
