@extends(branchMenu())
@section('content')
    <?php Fun::lang() ?>
    <div class="page">
        <div class=container>
            <div class="top-content">
                <div class="row">
                    <div class="col-sm-12 col-xs-12">
                        <div class="title-add">
                            <div class="pull-left">
                                <h3>{{__('administrator.production_template')}}</h3>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            {!! Form::open(array('route' => 'production-template.store','method'=>'POST','enctype'=>'multipart/form-data','class'=>'jform')) !!}
            <div class="row">
                <div class="tab-content">
                    <div id="home" class="tab-pane fade-in active">
                        <div class="col-sm-12">
                            <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>
                                <div class="form-group col-sm-12 col-xs-12">
                                    <div class="col-sm-2 col-xs-12 ">
                                        <label class="required" for="name">{{__('administrator.item')}}</label>
                                    </div>
                                    <div class="col-sm-10 col-xs-12">
                                        <div class="input-group">
                                            {!! Form::select('product_id',[],null, array('placeholder' => __('administrator.please_select'),'class' => 'form-control product_code search_product')) !!}
                                            <span class="input-group-addon cursor btn_generate_size_color">&nbsp;&nbsp;<span class="fa fa-cog"></span>&nbsp;&nbsp;</span>
                                            <span class="input-group-addon cursor" onclick="resetTB()">&nbsp;&nbsp;<span class="fa fa-refresh"></span>&nbsp;&nbsp;</span>
                                        </div>
                                    </div>
                                </div>
                                <div class="form-group col-sm-12 col-xs-12">
                                    <div class="col-sm-2 col-xs-12 ">
                                        <label class="required" for="name">{{__('administrator.currency')}}</label>
                                    </div>
                                    <div class="col-sm-10 col-xs-12">
                                        {!! Form::select('currency_id',getCurrency(),null, array('placeholder' => __('administrator.please_select'),'class' => 'select2 form-control')) !!}
                                    </div>
                                </div>
                                <div class="form-group col-sm-12 generate_size_color">

                                </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>
                    </div>
                </div>
            </div>
            {!! Form::close() !!}
        </div>
    </div>
@endsection
@section('script')
    <script type="text/javascript">
        let count = 1;
        $(document).ready(function () {
            gen_total();
            resetTB()
            $(document).on('click', '.add-material', function () {
                let $html = `
                    <tr>
                        <td>${count}</td>
                        <td>{!! Form::select('material_id[-][${count}]', [],null, ['placeholder'=>__('administrator.please_select'),'class' => 'form-control input-sm search_material select2']) !!}</td>
                        <td>{!! Form::select('material_unit[-][${count}]', [],null, ['placeholder'=>__('administrator.please_select'),'class' => 'form-control input-sm material_unit select2']) !!}</td>
                        <td>{!! Form::text('qty[-][${count}]', 1, ['class' => 'form-control number-only input-sm qty']) !!}</td>
                        <td>{!! Form::text('cost[-][${count}]', null, ['class' => 'form-control number-only input-sm cost']) !!}</td>
                        <td>{!! Form::text('total_amount[-][${count}]', 0, ['class' => 'form-control number-only input-sm total_amount','readonly']) !!}</td>
                        <td><button class="button_danger remove_material" type="button"><span class="fa fa-times"></span></button></td>
                    </tr>
               `;
                $(this).closest('.production_material').append($html);
                search_something('material', '.search_material');
                count++;
            });
            $(document).on('change', '.search_material', function () {
                let this_ = $(this);
                let item = this_.val();
                $.ajax({
                    url: '{{route('production-template-find-material-unit')}}',
                    dataType: 'json',
                    method: 'get',
                    data: {
                        item,
                    },
                    success: function (data) {
                        this_.closest('tr').find('.material_unit').html(data)
                    },
                    error(xhr) {
                        alertErrorFormController(xhr);
                    }
                });
            });
            $(document).on('keyup', '.number-only', function () {
                gen_total();
                $(this).attr("value", $(this).val());
            });
            $(document).on('change', 'select', function () {
                let val = $(this).val()
                $(this).find(`option`).removeAttr('selected');
                $(this).find(`option[value=${val}]`).attr('selected','selected');
            });
            $(document).on('change', '.material_unit', function () {
                let this_ = $(this);
                let material_id = this_.closest('tr').find('.search_material').val();
                let material_unit = this_.closest('tr').find('.material_unit').val();
                let currency_id = $('select[name=currency_id]').val();
                $.ajax({
                    url: '{{route('production-template-find-material-price')}}',
                    dataType: 'json',
                    method: 'get',
                    data: {
                        material_id,
                        material_unit,
                        currency_id
                    },
                    success: function (data) {
                        this_.closest('tr').find('.cost').val(data.price).attr("value", data.price)
                        gen_total();
                    },
                    error(xhr) {
                        alertErrorFormController(xhr);
                    }
                });
            });
            $(document).on('click', '.remove_material', function () {
                $(this).closest('tr').remove();
            });

            $('.btn_generate_size_color').on('click', function () {
                $('.btn_generate_size_color').fadeOut()
                let parent = $('.generate_size_color')
                let product_id = $('select[name=product_id]').val()
                let first_table = parent.find('.my_row:first').html()
                $.ajax({
                    url: '{{route('production-template.create')}}',
                    dataType: 'json',
                    method: 'get',
                    data: {product_id},
                    success: function (res) {
                        $('.generate_size_color').html('')
                        $.each(res, function (i, v) {
                            parent.append(`<div class="row my_row">${first_table}</div>`)
                            let last_row = parent.find('.my_row:last');
                            parent.find('.template_text:last').html(`
                            <b><br><br><br>${v.barcode}<br><br>(${v.size} , ${v.color_html})</b>
                            <input type="hidden" name="barcode[${v.barcode}]" value="${v.barcode}">
                            <input type="hidden" name="color_code[${v.barcode}]" value="${v.color_code}">
                            <input type="hidden" name="size_code[${v.barcode}]" value="${v.size_code}">
                            `)
                            console.log(last_row.html())
                            let text_html = last_row.html().replace(/\[-]/g, `[${v.barcode}]`)
                            last_row.html(text_html)
                        })
                        let remove_row = $('.generate_size_color tr')
                        $.each(remove_row, function (i, v) {
                            $(this).find('button').remove()
                        })
                        $(document).find('.search_material').parent().find('.select2-container').remove()
                        search_something('material', '.search_material');
                        gen_total();
                    },
                    error(xhr) {
                        alertErrorFormController(xhr);
                    }
                })

            })
        });

        function resetTB() {
            count = 1
            $('.generate_size_color').html(`${tableMaterial()}`)
            $('.btn_generate_size_color').fadeIn()

            count++;
        }

        function gen_total() {
            let template = $(document).find('.my_row')

            $.each(template, function (i, v) {
                let parent = $(this)
                let table = parent.find('.table-material .cost');
                let total_ = 0;
                $.each(table, function (ii, vv) {
                    let this_ = $(this).closest('tr');
                    let qty = toFloat(this_.find('.qty').val());
                    let cost = toFloat(this_.find('.cost').val());
                    let total = qty * cost;
                    total_ += total;
                    this_.find('.total_amount').val(total);
                });
                let sewing = toFloat(parent.find('.sewing_price').val());
                let cutting_price = toFloat(parent.find('.cutting_price').val());

                total_ += sewing+cutting_price;
                parent.find('.total_cost_').val(total_);
            });

        }

        function tableMaterial() {
            return `
                            <div class="row my_row">
                            <div class="col-sm-2 col-xs-12 template_text"></div>
                            <div class="col-sm-10 col-xs-12">
                            <table class="table table-bordered table-material">
                            <thead>
                            <tr>
                                <td>#</td>
                                <td width="300px">{{__('administrator.item_name')}} <span class="text-red">*</span></td>
                                <td width="150px">{{__('administrator.unit')}} <span class="text-danger">*</span></td>
                                <td>{{__('administrator.qty')}} <span class="text-danger">*</span></td>
                                <td>{{__('administrator.cost_per_qty')}} <span class="text-danger">*</span></td>
                                <td>{{__('administrator.total')}}</td>
                                <td>{{__('administrator.action')}} </td>
                            </tr>
                            </thead>
                            <tbody class="production_material">
                            <tr>
                                <td>1</td>
                                <td>{{__('administrator.cut_piece')}}{!! Form::hidden("material_id[-][`+count+`]", 'cut_piece', ['class' => 'form-control number-only input-sm']) !!}</td>
                                <td>{{__('administrator.piece')}}{!! Form::hidden("material_unit[-][`+count+`]", 0) !!}</td>
                                <td>{!! Form::text("qty[-][`+count+`]", 1, ['class' => 'form-control number-only input-sm qty','readonly']) !!}</td>
                                <td>{!! Form::text("cost[-][`+count+`]",null, ['class' => 'form-control number-only input-sm cost']) !!}</td>
                                <td>{!! Form::text("total_amount[-][`+count+`]", 0, ['class' => 'form-control number-only input-sm total_amount','readonly']) !!}</td>
                                <td>
                                    <button class="button_success add-material" type="button"><span class="fa fa-plus"></span></button>
                                </td>
                            </tr>
                            </tbody>
                            <tfoot>
                            <tr>
                                <td colspan="5" class="text-right">{{__('administrator.sewing_price')}} </td>
                                                <td>{!! Form::text('sewing_price[-]', null, ['class' => 'form-control number-only input-sm sewing_price']) !!}</td>
                                                <td></td>
                                            </tr>
                                <td colspan="5" class="text-right">{{__('administrator.cutting_price')}} </td>
                                                <td>{!! Form::text('cutting_price[-]', null, ['class' => 'form-control number-only input-sm cutting_price']) !!}</td>
                                                <td></td>
                                            </tr>
                                            <tr>
                                                <td colspan="5" class="text-right">{{__('administrator.total_cost')}}</td>
                                                <td>{!! Form::text('total_cost_[-]', 0, ['class' => 'form-control number-only input-sm total_cost_' ,'readonly']) !!}</td>
                                                <td></td>
                                            </tr>
                                            </tfoot>
                                        </table>
                            </div>
                            </div>
            `;
        }
    </script>
@endsection
