@extends(branchMenu())
@section('content')
    <?php Fun::lang() ?>
    @php
        $sp_width = '1%';
        $size  = getSize()->pluck('size','code');
        $color  = getColor()->pluck('name','code');
    @endphp
    <style>
        .table1 td {
            padding: 5px 10px;
        }
        .table_ex_payment td {
            padding: 5px;
            text-align: right;
        }
        table .select2{
            /*width: unset!important;*/
        }
    </style>
    <div class="page">
        {!! Form::open(array('route' => 'production-cutting.store','method'=>'POST','enctype'=>'multipart/form-data','class'=>'jform')) !!}
        <div class="row">
            <div class="col-sm-12 col-sm-12 col-xs-12">
                <div class="col-sm-12 col-sm-12 col-xs-12">
                    <h3 class="text-center"
                        style="margin-bottom: 28px">{{__('administrator.new_fabric_cutting')}}</h3>
                </div>
                <table class="production-text-align" width="55%">
                    <tr>
                        <td><label class="required" for="name">{{__('administrator.tailor_warehouse')}} </label></td>
                        <td>&nbsp;</td>
                        <td>{!! Form::select('from_warehouse_id',getWarehouse('tailor')->pluck('warehouse_name','id'),null, array('placeholder' => __('administrator.please_select'),'class' => 'form-control input-sm ')) !!}</td>

                        <td><label class="required" for="name">{{__('administrator.invoice_number')}} </label></td>
                        <td>&nbsp;</td>
                        <td>{!! Form::text('invoice_number',null, array('placeholder' => __('administrator.invoice_number'),'class' => 'form-control input-sm ')) !!}</td>

                        <td><label class="required" for="name">{{__('administrator.date')}} </label></td>
                        <td width="{{$sp_width}}"></td>
                        <td> {!! Form::text('date',date('d-m-Y'), array('placeholder' => __('administrator.date'),'class' => 'form-control input-sm date_picker')) !!}</td>
                    </tr>
                </table>
                <div class="col-sm-7 col-sm-7 col-xs-12">
                    <div class="col-sm-3 col-sm-3 col-xs-4"
                         style="height: 65vh;border: 1px solid rgba(1,1,1,0.3);padding: 0;overflow: scroll;margin-top: 5px">
                        <table class="table table-bordered table-hover">
                            <thead>
                            <tr>
                                <th> {!! Form::text('fabric',null, array('placeholder' => __('administrator.fabric'),'class' => 'form-control input-sm fabric_search',"autocomplete" => "on")) !!}</th>
                            </tr>
                            </thead>
                            <tbody class="warehouse_stock">
                            </tbody>
                        </table>
                    </div>
                    <div class="col-sm-9 col-sm-9 col-xs-8">
                        <div class="over-flow-box col-sm-12 col-sm-12 col-xs-12" style="margin-top: 4px;padding: 0">
                            <table class="table add-fabric-table">
                                <thead>
                                <tr>
                                    <th>#</th>
                                    <th>{{__('administrator.fabric')}}</th>
                                    <th>{{__('administrator.code')}}</th>
                                    <th width="120px">{{__('administrator.qty')}}</th>
                                    <th>{{__('administrator.yard')}}</th>
                                    <th width="100px">{{__('administrator.total')}}</th>
                                    <th>{{__('administrator.code_of_pant')}}</th>
                                    <th>{{__('administrator.action')}}</th>
                                </tr>
                                </thead>
                                <tbody class="fabric-tbody">

                                </tbody>
                            </table>
                        </div>
                        <div class="cutting-footer">
                            <table class="table">
                                <tr>
                                    <td rowspan="2" style="width: 65%"></td>

                                    <td style="border-bottom: none"
                                        class="text-center">{{__('administrator.total_piece')}}</td>
                                    <td style="border-bottom: none"
                                        class="text-center">{{__('administrator.total_yard')}}</td>
                                </tr>
                                <tr>
                                    <td style="border-top: none" class="text-center">
                                        <span class="g_total_qty">0</span>
                                    </td>
                                    <td style="border-top: none" class="text-center">
                                        <span class="g_total_yard">0</span>
                                    </td>
                                </tr>
                            </table>
                        </div>
                        <table class="table">
                            <tr>
                                <td style="white-space: nowrap">{{__('administrator.total_template')}} </td>
                                <td>{!! Form::text('f_total_template_take ', 0, ['class' => 'form-control f_total_template_take  input-sm number-only' ,'readonly']) !!}</td>
                                <td style="white-space: nowrap">{{__('administrator.qty_per_clothes')}} </td>
                                <td>{!! Form::text('qty_per_clothes ', 0, ['class' => 'form-control qty_per_clothes  input-sm number-only' ,'readonly']) !!}</td>
                            </tr>
                        </table>
                        <table class="table table-bordered">
                            <thead>
                            <th>{{__('administrator.size')}}</th>
                            <th>{{__('administrator.color')}}</th>
                            <th>
                                <button type="button" class="button_success btn_add_size"><span class="fa fa-plus"></span></button>
                                <button type="button" class="button_info btn_copy_size"><span class="fa fa-copy"></span></button>
                            </th>
                            </thead>
                            <tbody class="tb_generate_cp"></tbody>
                        </table>
                        <table class="table text-right">
                            <tr>
                                <td>
                                    <button type="button" class="button_primary button_generate">{{__('administrator.generate')}}</button>
                                </td>
                            </tr>
                        </table>
                    </div>
                </div>
                <div class="col-sm-5 col-sm-5 col-xs-12">
                    <div class="over-flow-box" style="margin-top: 5px">
                        <table class="table">
                            <thead>
                            <tr>
                                <th>#</th>
                                <th>{{__('administrator.cut_piece')}}</th>
                                <th>{{__('administrator.size')}}</th>
                                <th>{{__('administrator.color')}}</th>
                                <th>{{__('administrator.qty')}}</th>
                            </tr>
                            </thead>
                            <tbody class="tbody-cutpiece">

                            </tbody>
                        </table>
                    </div>
                    <div class="cutting-footer">
                        <table class="table">
                            <tr>
                                <td>
                                    {!! Form::textarea('description',null, ['placeholder'=>__('administrator.note'),'class' => 'form-control no-resize input-sm','rows'=>2]) !!}
                                </td>
                                <td>{{__('administrator.total_cutpiece')}}</td>
                                <td>{!! Form::text('f_g_total_cutpiece', 0, ['class' => 'form-control f_g_total_cutpiece input-sm number-only' ,'readonly']) !!}</td>
                            </tr>
                        </table>
                        <table class="table_ex_payment">
                            <tr>
                                <td >
                                    {{__('administrator.export_to')}} <span class="text-red">*</span>
                                </td>
                                <td>
                                    {!! Form::select('export_to',getWarehouse('cut_piece')->pluck('warehouse_name','id'), null, ['class' => 'form-control','placeholder'=>__('administrator.please_select') ]) !!}
                                </td>
                            </tr>
                        </table>
                    </div>
                </div>
                <div class="col-sm-12 col-sm-12 col-xs-12">
                    <button type="submit" class="button_primary pull-right">{{__('administrator.submit')}}</button>
                    <button type="button" onClick="history.go(-1)"
                            class=" button_warning pull-right">{{__('administrator.back')}}</button>
                </div>
            </div>
        </div>
        {!! Form::close() !!}
    </div>
@endsection
@section('script')
    <script type="text/javascript">
        $(document).ready(function () {
            let count_size = 0;
            $(document).on('keyup', '.cost_per_piece', function () {
                let cost_per_piece = $(this).val();
                let total_piece = $('.f_g_total_cutpiece').val();
                let cash_advance = $('.t_cash_advance_baht').val();
                cash_advance = cash_advance ? parseFloat(cash_advance) : 0;
                total_piece = parseFloat(total_piece ? total_piece : 0);
                cost_per_piece = parseFloat(cost_per_piece ? cost_per_piece : 0);
                let total = total_piece * cost_per_piece;
                $('.total_tailor_fee').val(total);
                $('input[name=t_amount_to_pay]').val(cash_advance - total);
            });
            $(document).on('click', '.btn_add_size', function () {
                let add_row = `<tr>
                                    <td>{!! Form::select('size_select[`+count_size+`]',$size, null, ['placeholder'=>__('administrator.please_select'),'class' => 'form-control __size_name _size_name`+count_size+` input-sm​ select2']) !!}</td>
                                    <td>{!! Form::select('color_select[`+count_size+`]',$color, null, ['placeholder'=>__('administrator.please_select'),'class' => 'form-control __color_name _color_name`+count_size+` input-sm​ select2']) !!}</td>

                                    <td class="text-center"><button type="button" class="button_danger btn_remove_gen_cp button_sm"><span class="fa fa-times"></span></button></td>
                                    </tr>`;

                $('.tb_generate_cp').append(add_row);
                count_size++;
                $('input').attr('autocomplete','off');
            });
            $(document).on('click', '.btn_copy_size', function () {
                $('.tb_generate_cp tr').each(function (i,v) {
                    let size = $(this).find('.__size_name').val()
                    let color = $(this).find('.__color_name').val()
                    let _size_qty = $(this).find('._size_qty').val()
                    $('.tb_generate_cp').append(`<tr>
                                    <td>{!! Form::select('size_select[`+count_size+`]',$size, null, ['placeholder'=>__('administrator.please_select'),'class' => 'form-control __size_name _size_name`+count_size+` input-sm​ select2']) !!}</td>
                                    <td>{!! Form::select('color_select[`+count_size+`]',$color, null, ['placeholder'=>__('administrator.please_select'),'class' => 'form-control __color_name _color_name`+count_size+` input-sm​ select2']) !!}</td>
                                    <td class="text-center"><button type="button" class="button_danger btn_remove_gen_cp button_sm"><span class="fa fa-times"></span></button></td>
                                    </tr>`);
                    let last_row = $('.tb_generate_cp tr:last')
                    last_row.find('.__size_name').val(size).change()
                    last_row.find('.__color_name').val(color).change()
                    last_row.find('._size_qty').val(_size_qty).change()
                    count_size++;
                });
                $('input').attr('autocomplete','off');
            });
            $('.tb_generate_cp').on('click', '.btn_remove_gen_cp', function () {
                $(this).closest('tr').remove();
            });
            $(document).on('change', 'select[name=from_warehouse_id]', function () {
                $('.fabric-tbody').html('');
                $('.tbody-cutpiece').html('');
                $('.warehouse_stock').html('');
                send_barcode('search');
            });
            $(document).on('click', '.button_generate', function () {
                let index_count = 1;
                let count_row = $('.fabric-tbody').find('.code_of_pant').length;
                let count_code_inserted = $('.fabric-tbody').find('.code_of_pant').filter(function() { return $(this).val(); }).length;
                if (count_row===count_code_inserted) {
                    $('.tbody-cutpiece').html('');
                    $('.code_of_pant').each(function (iii, vvv) {
                        let cop = $(this)
                        let product_id_arr = cop.val();
                        let fabric_id = cop.closest('tr').find('.product_id').val();
                        $.each(product_id_arr,function (i,product_id) {
                            let code = cop.find(`option[value=${product_id}]`).text();
                            $('.__size_name').each(function (ii, vvv) {
                                let this_ = $(this);
                                let size_text = this_.val() ? this_.find(':selected').text() : '';
                                let size_code = this_.val();
                                let color_code = this_.closest('tr').find('.__color_name').val();
                                let color_text = this_.closest('tr').find('.__color_name option:selected').text();

                                let size_text1 = size_text?size_text:0;
                                size_code = size_code?size_code:'';
                                color_code = color_code?color_code:'';
                                let $code = '';
                                if (size_text1 > 10) {
                                    $code = (code +''+ size_text1);
                                } else {
                                    $code = (code +''+ size_code+''+color_code);
                                }
                                let tr = `
                                <tr>
                                <td>` + (index_count) + `</td>
                                <td>
                                <input name="c_product_code[]" class="form-control  c_product_code" type="text" value="${$code}" readonly>
                                {!! Form::hidden('c_product_id[]', '`+product_id+`') !!}</td>
                                {!! Form::hidden('c_fabric_id[]', '`+fabric_id+`') !!}</td>
                                <td>
                                <input name="c_size_cutpiece[]" class="form-control number-only  c_size_cutpiece" type="hidden" value="${size_code}">
                                ${size_text}</td>
                                <td>
                                <input name="c_color_cutpiece[]" class="form-control number-only  c_color_cutpiece" type="hidden" value="${color_code}">
                                ${color_text}</td>
                                <td><input name="c_qty_cutpiece[]" class="form-control number-only  qty_cutpiece" value="1" type="text" ></td>
                                </tr>
                                 `;
                                $('.tbody-cutpiece').append(tr);
                                index_count++;
                                $('input').attr('autocomplete','off');
                            });
                        })
                    });
                    generate_process();
                } else {
                    jalert('Warning', 'Please insert Code of Pant');
                }

            });
            $(document).on('keyup', '.cost_per_piece', function () {
                let cost_per_piece = $(this).val();
                let total_piece = $('.total_piece_').val();
                total_piece = parseFloat(total_piece ? total_piece : 0);
                cost_per_piece = parseFloat(cost_per_piece ? cost_per_piece : 0);
                $('.total_amount').val(total_piece * cost_per_piece);
            });
            $('.fabric-tbody ').on('keyup', '.fabric_qty', function () {
                let qty = $(this).val();
                let stock = $(this).closest('tr').find('.stock_qty').val();
                let qty_per_unit = $(this).closest('tr').find('.qty_per_unit').val();
                stock = stock ? parseFloat(stock) : 0;
                qty = qty ? parseFloat(qty) : 0;
                qty_per_unit = qty_per_unit ? parseFloat(qty_per_unit) : 0;
                stock = parseInt(stock / qty_per_unit);
                if (qty > stock) {
                    $(this).val(stock);
                    jalert('Warning', '{{__('administrator.this_product_is_out_of_stock')}}')
                }
                total_fabric();
            });
            $('.tbody-cutpiece ').on('keyup', '.qty_cutpiece', function () {
                generate_process();
            });
            $('.add_size_qty ').on('keyup', function () {
                generate_process();
            });
            $(document).on('click', '.remove_fabric', function () {
                let tr = $(this).closest('tr').find('.product_id').val();
                $(".fabric-tbody .pro" + tr).remove();
                total_fabric();
            });
            $('.warehouse_stock').on('click', '.cursor', function () {
                let $this = $(this);
                let barcode = $this.data('ccc');
                send_barcode(barcode);
                clear_search();
            });
            $(".fabric_search").autocomplete({
                source: function (request, response) {
                    send_barcode(request.term)
                },
                minLength: 0,
            });
        });

        function generate_process() {
            let total_qty_cutpiece = 0;
            let g_total_qty_cutpiece = 0;
            let g_total_yard = $('.g_total_yard').text();
            $('.tbody-cutpiece tr').each(function (ii, vv) {
                let this_ = $(this);
                let qty_cutpiece = this_.closest('tr').find('.qty_cutpiece').val();
                qty_cutpiece = qty_cutpiece ? parseFloat(qty_cutpiece) : 0;
                let sub_qty_cutpiece = qty_cutpiece;
                sub_qty_cutpiece = sub_qty_cutpiece ? parseFloat(sub_qty_cutpiece) : 0;
                total_qty_cutpiece += qty_cutpiece;
                g_total_qty_cutpiece += sub_qty_cutpiece;
            });
            $('.f_total_cutpiece_size').val(total_qty_cutpiece);
            $('.f_g_total_cutpiece').val(g_total_qty_cutpiece);

            g_total_yard = g_total_yard ? parseFloat(g_total_yard) : 0;
            $('.qty_per_clothes').val(g_total_yard / g_total_qty_cutpiece);
            $('.total_piece_').val(g_total_qty_cutpiece);
        }

        function total_fabric() {
            let g_total_yard = 0;
            let g_total_fabric = 0;
            $('.fabric-tbody tr').each(function () {
                let qty = parseFloat($(this).find(".fabric_qty").val() ? $(this).find(".fabric_qty").val() : 0);
                let qty_per_unit = parseFloat($(this).find(".qty_per_unit").val() ? $(this).find(".qty_per_unit").val() : 0);
                let $total = qty * qty_per_unit;
                $(this).find(".child_qty").text($total);
            });
            $('.fabric-tbody tr').each(function () {
                let total_fabric = 0;
                let product_id = ($(this).find(".product_id").val() ? $(this).find(".product_id").val() : 0) + '';
                let subtotal = 0;
                $('.fabric-tbody tr.pro' + product_id).each(function () {
                    subtotal = $(this).find(".child_qty").text();
                    subtotal = subtotal ? parseFloat(subtotal) : 0;
                    total_fabric += subtotal;
                });
                $(this).find(".total" + product_id).val(total_fabric);

            });
            $('.subtotal_fabric').each(function () {
                g_total_yard += parseFloat($(this).val() ? $(this).val() : 0);
            });
            $('.fabric_qty').each(function () {
                g_total_fabric += parseFloat($(this).val() ? $(this).val() : 0);
            });
            $('.g_total_qty').text(g_total_fabric);
            $('.g_total_yard').text(g_total_yard);
        }

        function send_barcode(barcode) {
            let url = '{{route('find-fabric')}}';
            let from_warehouse_id = $('select[name=from_warehouse_id]').val();
            $.ajax({
                url: url,
                dataType: 'json',
                method: 'get',
                data: {
                    from_warehouse_id,
                    barcode,
                },
                success: function (data) {
                    if (data.status === 'search') {
                        let list = '';
                        let count = parseFloat(data.data.length);
                        if (count === 0) {
                            list += '<tr><td data-ccc ="">No Item Found</td></tr>';
                        }
                        $.each(data.data, function (ii, vv) {
                            let qty_alert = (vv.qty_alert);
                            qty_alert = qty_alert ? parseFloat(qty_alert) : 0;
                            let stock = parseInt(vv.stock_convert);
                            let alert = '';
                            if (stock > qty_alert) {
                                alert = 'success';
                            } else if (stock <= alert || stock > 0) {
                                alert = 'warning';
                            } else {
                                alert = 'danger';
                            }
                            list += '<tr ><td data-ccc = ' + vv.barcode + ' class="cursor">' + vv.name + ' <span class="label label-' + alert + '">' + stock + ' ក្នុងស្តុក</span></td></tr>';
                        });
                        $('.warehouse_stock').html(list);
                    } else {
                        add_to_table(data);
                        clear_search();
                    }
                },
                error: function (xhr) {
                    alertErrorFormController(xhr);
                }
            });
        }

        function add_to_table(data) {
            let $row2 = '';
            let $row1 = '';
            let tb_leng = $('.add-fabric-table tr').length;
            let count_row = $(".pro" + data.product_id).length;

            if (count_row > 0) {
                $row1 = `<tr class="pro` + (data.product_id + ``) + `">` +
                    `<td>` + data.barcode + `</td>` +
                    `<td>` +
                    `<div class="row">` +
                    `<div class="col-sm-9 col-sm-9 col-xs-12">` +
                    `{!! Form::text('f_qty[`+data.product_id+`]', 1, ['class' => 'form-control number-only input-sm fabric_qty']) !!}` +
                    `</div>` +
                    `<div class="col-sm-3 col-sm-3 col-xs-12">`
                    + data.unit +
                    `</div>` +
                    `</div>` +
                    `</td>` +
                    `<td>` +
                    `<span class="child_qty">` + data.qty_per_unit + `</span>` + data.child_unit +
                    `{!! Form::hidden("stock_qty[`+data.product_id+`]",  "`+data.stock_qty+`", ["class" => "number-only stock_qty"]) !!}` +
                    `{!! Form::hidden("f_barcode[`+data.product_id+`]",  "`+data.barcode+`", ["class" => "number-only barcode"]) !!}` +
                    `{!! Form::hidden("f_product_id[`+data.product_id+`] ",  "`+data.product_id+`", ["class" => "number-only product_id"]) !!}` +
                    `{!! Form::hidden("f_child_qty[`+data.product_id+`]", "`+data.qty_per_unit+`", ["class"=>"number-only"]) !!}` +
                    `{!! Form::hidden("f_qty_per_unit[`+data.product_id+`]", "`+data.qty_per_unit+`", ["class" => "number-only qty_per_unit"]) !!}` +
                    `</td></tr>`;
                    function row_span($child){
                        return $(document).find('.pro' + data.product_id + ':first td:nth-of-type('+$child+')').prop('rowspan', count_row + 1);
                    }
                row_span(1);
                row_span(2);
                row_span(6);
                row_span(7);
                row_span(8);
            } else {
                $row2 = `<tr class= "pro` + data.product_id + `">` +
                    `<td rowspan = "1" > ` + (tb_leng) + ` </td>` +
                    `<td rowspan = "1" > ` + data.name + ` {!! Form::hidden('f_product_name[`+data.product_id+`]', '`+data.name+`', ['class' => 'form-control product_name']) !!}</td>` +
                    `<td> ` + data.barcode + ` </td>` +
                    `<td>
                    <div class="input-group">
                     {!! Form::text('f_qty[`+data.product_id+`]', 1, ['class' => 'form-control number-only input-sm fabric_qty']) !!}
                      <span class="input-group-addon">${data.unit}</span>
                    </div>
                    </td>` +
                    `<td>` +
                    `<span class="child_qty">` + (data.qty_per_unit) + `</span>` +
                    `` + data.child_unit +
                    `{!! Form::hidden("stock_qty[`+data.product_id+`]",  "`+data.stock_qty+`", ["class" => "number-only stock_qty"]) !!}` +
                    `{!! Form::hidden("f_barcode[`+data.product_id+`]",  "`+data.barcode+`", ["class" => " number-only input-sm barcode"]) !!}` +
                    `{!! Form::hidden("f_product_id[`+data.product_id+`]",  "`+data.product_id+`", ["class" => " number-only input-sm product_id"]) !!}` +
                    `{!! Form::hidden("f_child_qty[`+data.product_id+`]", "`+data.qty_per_unit+`", ["class" => "number-only"]) !!}` +
                    `{!! Form::hidden("f_qty_per_unit[`+data.product_id+`]", "`+data.qty_per_unit+`", ["class" => "number-only qty_per_unit"]) !!}` +
                    `</td>` +
                    `<td rowspan = "1" > <input type = "text" class = " subtotal_fabric form-control total` + data.product_id + `" readonly name = "f_total` + data.product_id + `[`+data.product_id+`]" value = "0" > </td>` +
                    `
                    <td>
                    {!! Form::select('code_of_pant`+data.product_id+`[]',[],null, array('class' => 'form-control input-sm search_product code_of_pant','multiple','required')) !!}
                </td>
                <td>
                <button type = "button" class = "button_danger button_sm remove_fabric" > <span class = "fa fa-times" > </span></button>
                </td>

                </tr>`;
                $('input').attr('autocomplete','off');
            }
            $(document).find(".pro" + data.product_id + ":last").after($row1);
            $('.add-fabric-table tbody').append($row2);
            setTimeout(function () {
                $('input').attr('autocomplete','off');
                total_fabric();
                search_something('product_code', '.search_product');
            }, 111);
        }

        function clear_search() {
            $('.fabric_search').val('');
            $('.fabric_search').focus();
        }
    </script>
@endsection
