<?php use App\Model\people\TailorModel;
use App\Model\production\TailorStockPaymentModel;
use App\Model\setup\PackerModel;

Fun::lang();

if (request('type')) {
    $tailor = TailorStockPaymentModel::where(request()->all());
    if (request('type') === 'packing') {
        $tailor = $tailor->pluck('packer_id', 'packer_id');
        $tailor = PackerModel::whereIn('id', $tailor);
        $val = request('packer_id');
    } else {
        $tailor = $tailor->pluck('tailor_id', 'tailor_id');
        $tailor = TailorModel::whereIn('id', $tailor);
        $val = request('tailor_id');
    }
    $tailor = $tailor->pluck('name','id');
} else {
    $tailor = [];
    $val = null;
}
$input = [
    [
        'type' => 'text',
        'name' => 'date',
        'title' => 'date',
        'required' => 'required',
        'value' => date('d-m-Y'),
        'class' => 'date_picker',
    ],
    [
        'type' => 'select',
        'name' => 'type',
        'class' => 'op_type',
        'option' => ['cutting' => __('administrator.cutting'), 'sewing' => __('administrator.sewing'), 'packing' => __('administrator.packing')],
        'title' => 'type',
        'value' => request('type'),
        'required' => 'required'
    ],
    [
        'type' => 'select',
        'name' => 'tailor_id',
        'class' => 'tailor_id',
        'option' => $tailor,
        'value' => $val,
        'title' => 'tailor',
        'required' => 'required'
    ],
    [
        'type' => 'textarea',
        'name' => 'note',
        'title' => 'note',
        'rows' => '2',
    ],

];

?>
<div class="container">
    <h3>{{__('administrator.production_payment')}}</h3>
    <div class="master-form">
        <div class="title-note">
            <h3>
                <span class="fa fa-exclamation-triangle"></span> {{__('administrator.create')}}
                <i>({{__('administrator.fields_in_red_are_required')}})</i>
            </h3>
        </div>
        @include('component.form-component',['input'=>$input])
        <div class="form-group col-sm-12 col-xs-12">
            <div class="col-md-12">
                <table class="table table-bordered">
                    <thead>
                    <tr>
                        <th width="350px" class="required">{{__('administrator.item')}}</th>
                        <th width="250px" class="required">{{__('administrator.price')}}</th>
                        <th class="required">{{__('administrator.qty')}}</th>
                        <th>{{__('administrator.total')}}</th>
                        <th>
                            <button type="button" class="button_success button_sm" onclick="add_row()"><i class="fa fa-plus"></i></button>
                        </th>
                    </tr>
                    </thead>
                    <tbody class="add_item"></tbody>
                    <tfoot>
                    <tr>
                        <th colspan="2" class="text-right">{{__('administrator.total')}}</th>
                        <th class="total_qty">0</th>
                        <th class="total_amount ">0</th>
                        <th>
                            {!! Form::hidden('total_amount_riel',null) !!}
                            {!! Form::hidden('total_amount_usd',null) !!}
                        </th>
                    </tr>
                    <tr>
                        <th colspan="2"></th>
                        <th class="text-right" style="vertical-align: middle">{{__('administrator.payment_method')}}</th>
                        <th>{!! Form::select('payment_method',getPaymentMethod(),null,['class'=>'form-control input-sm','placeholder'=>__('administrator.please_select')]) !!}</th>
                    </tr>
                    </tfoot>
                </table>
            </div>
        </div>

        <div class="col-sm-12 col-xs-12 ">
            <div class="form-group footer-save">
                <button type="submit" class=" button_primary pull-right"><span
                        class="fa fa-save"></span> {{__('administrator.save')}}</button>
                <button type="button" onClick="history.go(-1)" class=" button_warning pull-right">
                    <span class=" fa fa-arrow-circle-left"></span> {{__('administrator.back')}}
                </button>
            </div>
        </div>
    </div>
</div>
@section('script')
    <script>
        $(document).ready(function () {
            setTimeout(function () {
                add_row()
            },300)
            $('.op_type,.tailor_id').on('change', function () {
                $('.add_item').html('')
                add_row()
            })
            $('.op_type').on('change', function () {
                let type = $(this).val()
                $.get('{{route('production-payments.create')}}', {type, getTailor: 1}, function (res) {
                    let option = '<option>{{__('administrator.please_select')}}</option>'
                    $.each(res, function (id, name) {
                        option += `<option value="${id}">${name}</option>`
                    })
                    $('.tailor_id').html(option);
                })
            })
            $('.add_item').on('change','.price', function () {
                let t = $(this)
                let price = t.val()
                let html = t.html()
                if(price){
                    let check = $(document).find(`.price option:selected[value="${price}"]`).length
                    if(check>1){
                        t.html(html)
                    }
                }
            })
            $('.add_item').on('keyup', '.qty', function () {
                let qty = $(this).val()
                let max = toFloat($(this).closest('tr').find('.price option:selected').data('max'));
                if (qty > max) {
                    $(this).val(max)
                }
                total()
            })
            $('.add_item').on('change', '.search_stock', function () {
                let tailor_id = $('select[name=tailor_id]').val()
                let type = $('select[name=type]').val()
                let t = $(this)
                let barcode = t.val()
                $.get('{{route('production-payments.create')}}', {type, tailor_id, barcode, getStockPrice: 1}, function (res) {
                    let option = '<option value="">{{__('administrator.please_select')}}</option>'
                    $.each(res, function (k, data) {
                        option += `<option data-max="${data.stock_qty}" data-cur="${data.cur}" data-price="${data.price}" value="${data.id}">${data.text}</option>`
                    })
                    t.closest('tr').find('.price').html(option);
                })
            })
        })

        function add_row() {
            $('.add_item').append(`
                <tr>
                    <td><select name="barcode[]" class="form-control search_stock"><option>{{__('administrator.please_select')}}</option></select></td>
                    <td><select name="price[]" class="form-control price"></select></td>
                    <td><input type="number" name="qty[]" value="0" class="form-control qty" /></td>
                    <td>
                    <div class="input-group">
                     <input type="text" name="total[]" readonly value="0" class="form-control total" />
                      <span class="input-group-addon"></span>
                    </div>
                    </td>
                    <td class="text-center"><button onclick="$(this).closest('tr').remove()" type="button" class="button_sm button_danger"><i class="fa fa-times"></i></button></td>
                </tr>
            `)
            search_stock()
        }

        function total() {
            let total_qty = 0
            let total_amount = []
            $('.add_item tr').each(function (i, v) {
                let qty = toFloat($(this).find('.qty').val())
                let price = toFloat($(this).find('.price option:selected').data('price'))
                let cur = ($(this).find('.price option:selected').data('cur'))
                let total = qty * price
                $(this).find('.total').val(total)
                $(this).find('.input-group-addon').text(cur)
                total_qty += qty
                if (typeof total_amount[cur] === 'undefined') {
                    total_amount[cur] = total
                } else {
                    total_amount[cur] += total
                }
            })
            $('.total_qty').html(total_qty + ' ឯកតា')
            let riel = total_amount['៛']
            let usd = total_amount['$']

            $('input[name=total_amount_riel]').val(riel ? riel : 0)
            $('input[name=total_amount_usd]').val(usd ? usd : 0)


            riel = riel ? (riel + '៛') : ''
            usd = usd ? (usd + '$') : ''


            $('.total_amount').html(riel + (riel && usd ? '<br>' : '') + usd)
        }

        function search_stock() {
            let tailor_id = $('select[name=tailor_id]').val()
            let type = $('select[name=type]').val()

            $(document).find('.search_stock:last').select2({
                tags: true,
                tokenSeparators: [','],
                minimumInputLength: 0,
                minimumResultsForSearch: 0,
                ajax: {
                    url: '{{route('production-payments.create')}}',
                    dataType: "json",
                    type: "GET",
                    data: function (term) {
                        return {
                            search_stock: 1,
                            type: type,
                            term: term,
                            tailor_id: tailor_id,
                        };
                    },
                    processResults: function (data) {
                        return {
                            results: data
                        };
                    }
                }
            });
        }
    </script>
@endsection

