@extends('backend.layouts.master')
@section('title', 'Purchase')
@push('css')
    <link rel="stylesheet" href="{{asset('backend/plugins/select2.min.css')}}">
    <link rel="stylesheet" href="{{ asset('myfile/backend/assets/datepicker/zebra_datepicker.min.css') }}" type="text/css">
    <link rel="stylesheet" href="{{ asset('myfile/backend/assets/datepicker/examples.css') }}" type="text/css">

@endpush
<!-- page content -->
@section('content')
    <div class="right_col" role="main">
        <div class="">
            <div class="clearfix"></div>
            @if(Session::has('success'))
                <div class="alert alert-success">
                    {{ Session::get('success') }}
                </div>
            @endif
            @if(Session::has('error'))
                <div class="alert alert-danger">
                    {{ Session::get('error') }}
                </div>
            @endif
            <div class="row">
                <div class="col-md-12 col-sm-12 col-xs-12">
                    <div class="x_panel">
                        <div class="x_title">
                            <h2>
                                Purchase Create 

                                 <a href="{{route('purchase.list')}}" class="btn btn-xs btn-primary">Purchase List</a>
                            </h2> 
                            <ul class="nav navbar-right panel_toolbox">
                                <li>
                                    <a class="collapse-link"><i class="fa fa-chevron-up"></i></a>
                                </li>
                                <li class="dropdown">
                                    <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button"
                                       aria-expanded="false"><i class="fa fa-wrench"></i></a>
                                    <ul class="dropdown-menu" role="menu">
                                        <li><a href="#">Settings 1</a>
                                        </li>
                                        <li><a href="#">Settings 2</a>
                                        </li>
                                    </ul>
                                </li>
                                <li><a class="close-link"><i class="fa fa-close"></i></a>
                                </li>
                            </ul>
                            <div class="clearfix"></div>
                        </div>
                        <div class="x_content">
                            <form action="{{route('purchase.store')}}" method="post" class="form-horizont" role="form" autocomplete="off" >
                             {{ csrf_field()}}
                                <div class="row">
                                    <div class="col-sm-6">
                                        <div class="form-group">
                                            <label class="col-sm-4 control-label no-padding-right" for="form-field-1"> Supplier Name <span class="required">*</span></label>
                                            <div class="col-sm-8">
                                                <select name="supplier_name" id="supplier_id" class="form-control select2" required="required">
                                                    <option value="">-Select Supplier-</option>
                                                    @foreach($suppliers as $sup)
                                                        <option value="{{$sup->id}}" {{$sup->id == old('supplier_name') ? 'Selected' : ''}}>{{$sup->name}}</option>
                                                    @endforeach
                                                </select> 
                                                <p class="error-sms">{{ $errors->first('supplier_name') }}</p>
                                            </div>
                                        </div>
                                        <div class="form-group">
                                            <label class="col-sm-4 control-label no-padding-right" for="form-field-1"> Chalan No <span class="required">*</span></label>
                                            <div class="col-sm-8">
                                                <input type="text" name="chalan_no"  class="form-control" value="{{old('chalan_no') ?? $order_no}}" readonly placeholder="Order No">
                                                <p class="error-sms">{{ $errors->first('chalan_no') }}</p>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="col-sm-6">
                                        <div class="form-group">
                                            <label class="col-sm-4 control-label no-padding-right" for="form-field-1"> Purchase Date <span class="required">*</span></label>
                                            <div class="col-sm-8">
                                                <input id="datepicker" type="text" name="purchase_date"  class="form-control" data-zdp_readonly_element="true" value="{{ date('d-m-Y')}}" placeholder="dd-mm-yyyy">
                                                <p class="error-sms">{{ $errors->first('purchase_date') }}</p>
                                            </div>
                                        </div>
                                        <div class="form-group">
                                            <label class="col-sm-4 control-label no-padding-right" for="form-field-1"> Note</label>
                                            <div class="col-sm-8">
                                                <input type="text" name="note"  class="form-control" placeholder="Note About this Purchase">
                                                <p class="error-sms">{{ $errors->first('note') }}</p>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <hr/>
                                <div class="row">
                                    <div class="col-sm-2"></div>
                                    <div class="col-sm-2">
                                        <label>Input Code</label>
                                    </div>
                                    <div class="col-sm-6">
                                        <div class="form-group">
                                            <input type="text" class="form-control" name="model_no" placeholder="Input Code" id="bar_code" autofocus autocomplete='off' tabindex="1">
                                        </div>
                                        <p class="error" id="notification"></p>
                                    </div>
                                    <div class="col-sm-2"></div>
                                </div>
                                <table class="table table-condensed table-bordered table-hover table-header-fixed dt-responsive green" id="sale">
                                    <thead class="info">
                                        <tr>
                                            <th class="all">SL </th>
                                            <th class="all">Product </th>
                                            <th class="all">Category </th>
                                            <th class="all">Unit </th>
                                            <th class="all">Code No </th>
                                            <th class="all">Size </th>
                                            <th class="all">Square Feet</th>
                                            <th class="all">Rate</th>
                                            <th class="all">Sub Total</th>
                                           <th class="all">Delete</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                    </tbody>
                                    <tfoot>
                                        <tr>
                                            <th>-</th>
                                            <th class="all" colspan="5">Total</th>
                                            <th id="total_ordered">0</th>
                                            <th>-</th>
                                            <th id="total_sub">0</th>
                                            <th>-</th>
                                        </tr>
                                    </tfoot>
                                </table>
                                <div class="row">
                                    <div class="col-sm-7">
                                        <div class="form-group">
                                            <label class="control-label col-sm-4" for="discount">Discount</label>
                                            <div class="col-sm-8 ">
                                              <input type="text" class="form-control" min="0" value="0" name="discount" id="discount">
                                                <p class="error-sms">{{ $errors->first('discount') }}</p>
                                            </div>
                                        </div>
                                        <div class="form-group">
                                            <label class="control-label col-sm-4">Discount Type</label>
                                            <div class="col-sm-8 ">          
                                                <select class="form-control select2" id="discount_type" name="discount_type">
                                                    <option> Fixed</option>
                                                    <option>Percentage </option>
                                                </select>
                                                <p class="error-sms">{{ $errors->first('discount_type') }}</p>
                                            </div>
                                        </div>
                                        <div class="form-group">
                                            <label class="control-label col-sm-4">Payment Amount</label>
                                            <div class="col-md-8">
                                                <input type="number" class="form-control" id="payment" min="0" name="payment" required >
                                                <p class="error-sms">{{ $errors->first('payment') }}</p>
                                            </div>  
                                        </div>
                                    </div>
                                    <div class="col-sm-5">
                                        <table style="max-width:80%;margin:0 auto" class="table table-striped table-bordered table-hover table-header-fixed" id="sample_2" >
                                            <tfoot>
                                                <tr>
                                                    <th> Name: </th>
                                                    <th>Amount:</th>
                                                </tr>
                                                <tr>
                                                    <th> Items: </th>
                                                    <th><span class="pull-right" id="total_items">0</span></th>
                                                </tr>
                                                <tr>
                                                    <th> Total: </th>
                                                    <th><span class="pull-right" id="total_value">0</span></th>
                                                </tr>
                                                <tr>    
                                                    <th> Discount: </th>
                                                    <th> <span class="pull-right" id="total_discount">0</span></th>
                                                </tr>
                                                <!--<tr>
                                                    <th> Tax </th><th>  <span class="pull-right" id="total_tax">0</span></th>
                                                </tr>
                                                <tr>
                                                    <th> Shipping </th><th>  <span class="pull-right" id="total_shipping">0</span></th>
                                                </tr>-->
                                                <tr>
                                                    <th> Grand Total: </th>
                                                    <th>  <span class="pull-right" id="grand_total">0</span></th>
                                                </tr>
                                                <tr>
                                                    <th> Due: </th>
                                                    <th>  <span class="pull-right" id="due">0</span></th>
                                                </tr>
                                            </tfoot>
                                        </table>
                                        <input type="hidden" id="total_price" name="total_price"  />
                                        <input type="hidden" class="grand_total" name="grand_total"  />
                                        <input type="hidden" class="due" name="due"  />
                                    </div>
                                </div>
                                <hr>
                                <div class="form-group">
                                    <div class="col-md-6 col-sm-6 col-xs-12 col-md-offset-5">
                                      <button class="btn btn- btn-warning" type="reset">Reset</button>
                                      <button type="submit" class="btn btn- btn-success">Save</button>
                                    </div>
                                </div>
                                <br><br>
                            </form>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <!-- /page content -->
@endsection
@push('js')
    <script src="{{asset('backend/plugins/select2.min.js')}}"></script>
    <!-- Jquery Plugin For Date Calender-->
    <script type="text/javascript" src="{{ asset('myfile/backend/assets/datepicker/zebra_datepicker.src.js') }}"></script>
    <!-- jQuery autocomplete -->
    <script type="text/javascript">
        $(document).ready(function(){
            $('#datepicker').Zebra_DatePicker({
                format: 'd-m-Y',
                direction: 1,
            });
            /*-------------*/
            $(".select2").select2();
            /*---------product not found notification--------------*/
            setInterval(function(){ 
                $("#notification").hide('slow');
            },5000);

            var array = [];
            var total_tax = 0;
            var tax_type = "Fixed";
            var sl = 1
            $('#bar_code').keydown(function (e) {
                if (e.keyCode == 13) {
                    var code = $('#bar_code').val();
                    var token = "{{csrf_token()}}";
                    if(code != ''){
                        $.ajax({
                            url: '{{ route("purchase.productDetails2") }}',
                            type: 'Get',
                            data: {code: code, '_token' : token},
                            dataType: 'json',
                            success: function (response) {
                            //alert(response)
                            //console.log(response)
                                if(response['id'] != undefined){
                                    var id = response['id'];  
                                    var name = response['product_name'];                    
                                    var category_name = response['category']['name'];               
                                    //var brand_name = response['brand']['brand_name'];               
                                    var unit_name = response['unit']['name'];               
                                    var code =  response['code'];
                                    var size =  response['size'];
                                    var supplier_price =  response['supplier_price'];
                                    var sale_price =  response['sale_price'] + 10;
                                    var ordered_quantity =  1;
                                    var sub_total =  supplier_price*ordered_quantity;
                                    sl++
                                    $("#sale tbody").append(
                                        "<tr id='"+sl+"'>"
                                        +"<td>"+sl+"</td>"
                                        +"<td><input type='hidden' name='product_id[]' value='"+id+"' />"+name+" </td>"
                                        +"<td><input type='hidden' name='category_name[]' value='"+category_name+"' />"+category_name+" </td>"
                                        +"<td><input type='hidden' name='unit_name[]' value='"+unit_name+"' />"+unit_name+" </td>"
                                        +"<td><input type='hidden' name='code[]' value='"+code+"' />"+code+" </td>"
                                        +"<td><input type='hidden' name='size[]' value='"+size+"' />"+size+" </td>"
                                        +"<td><input type='text' id='"+sl+"_ordered_quantity' class='ordered_quantity' name='ordered_quantity[]' min='1' value='"+ordered_quantity+"' size='10' /></td>"
                                        +"<td><input id='"+sl+"_price' type='text' name='supplier_price[]' class='supplier_price' value='"+supplier_price+"' size='10'/></td>"
                                        // +"<td><input type='text' name='sale_price[]' value='"+sale_price+"' size='10'></td>"
                                        +"<td class='sub_total' id='"+sl+"_sub_total'>"+sub_total+"</td>"
                                        +"<td class='text-center'><i class='red fa fa-trash fa-lg'></i></td>"
                                        +"</tr>");

                                    array.push(id);
                                    var idLength = array.length;
                                    for(j = 0; j<idLength; j++){
                                        $('#product_'+array[j]).attr('disabled','disabled').select2({placeholder:"",width:"auto",allowClear:!0});
                                    }

                                    var total_ordered = parseFloat($('#total_ordered').html());
                                    total_ordered = total_ordered + 1;
                                    $('#total_ordered').html(total_ordered);

                                    calculate_sub_total();
                                    calculate_total();

                                    /*---------empty the input field---------*/
                                    $('#bar_code').val('');
                                    $('#bar_code').focus();
                                }else{
                                    $('#notification').html('Woops!! Sorry no product information found!!, please check the label code.').show();
                                    $('#bar_code').val('');
                                    $('#bar_code').focus();
                                }
                            }
                        })
                    }
                }
            });
            
            $(document).on('click','.fa-trash',function(){
                var id = $(this).parent().parent().attr('id');
                $('#'+id).remove();

                $('#product_'+id).removeAttr('disabled');
                array.splice($.inArray(id, array), 1);

                // $('#product').select2("destroy").select2({placeholder:"",width:"auto",allowClear:!0});
                calculate_ordered_quantity();
                calculate_sub_total();
                calculate_total();
            });

            $(document).on('keyup','.ordered_quantity',function(){
                var id = $(this).parent().parent().attr('id');
                var price = $('#'+id+'_price').val();
                var quantity = $('#'+id+'_ordered_quantity').val();
                var sub_total =  price*quantity;
                $('#'+id+'_sub_total').html(sub_total);

                calculate_ordered_quantity();

                calculate_sub_total();

                calculate_total();
            });
            $(document).on('keyup','.supplier_price',function(){
                var id = $(this).parent().parent().attr('id');
                var price = $('#'+id+'_price').val();
                var quantity = $('#'+id+'_ordered_quantity').val();
                // var stock = $('#'+id+'_stock').val();
                    var sub_total =  price*quantity;
                    $('#'+id+'_sub_total').html(sub_total);
                    calculate_ordered_quantity();
                    calculate_sub_total();
                    calculate_total();
                    
                    //16-07-19
                    calculate_due();
            });
            $(document).on('keyup','#discount',function(){
                calculate_discount();
                calculate_grand_total();
                calculate_due();
            });

            $(document).on('change','#discount_type',function(){
                calculate_discount();
                calculate_grand_total();
                calculate_due();
            });

            $(document).on('keyup','#payment',function(){
                calculate_discount();
                calculate_grand_total();
                calculate_due();
            });

            function calculate_ordered_quantity(){
                var total_ordered = 0;
                //iterate through each td based on class and add the values
                $(".ordered_quantity").each(function() {

                    var value = parseFloat($(this).val());

                    total_ordered = total_ordered + value;
                });
                $('#total_ordered').html(total_ordered);
            }

            function calculate_discount(){
                var discount = $('#discount').val();
                var type = $('#discount_type').val();
                if (type != 'Fixed') {
                    discount = parseFloat($('#total_value').html()) * discount / 100;
                }
                
                $('#total_discount').html(discount);
            }

            function calculate_sub_total(){
                var total_sub = 0;
                //iterate through each td based on class and add the values
                $(".sub_total").each(function() {

                    var value = parseFloat($(this).html());

                    total_sub = total_sub + value;
                });
                $('#total_sub').html(total_sub);
            }

            function calculate_grand_total(){ 
                // var grand_total = parseFloat($('#total_value').html())-parseFloat($('#total_discount').html())+parseFloat($('#total_tax').html())+parseFloat($('#total_shipping').html());
                var grand_total = parseFloat($('#total_value').html())-parseFloat($('#total_discount').html());
                $('#grand_total').html(grand_total);
                $('.grand_total').val(grand_total);
                $('#due').html(grand_total);
                //alert(grand_total)
            }

            function calculate_total(){
                var total_items = 0;            
                var total_sub = 0;
                //iterate through each td based on class and add the values
                $(".sub_total").each(function() {
                    total_items++;
                });

                $('#total_items').html(total_items);
                $('#total_value').html($('#total_sub').html());
                $('#total_price').val($('#total_sub').html());

                calculate_discount();
            // calculate_tax();
                //calculate_shipping();
                calculate_grand_total();
            }
            // due section
            function calculate_due(){
                var pay = $('#payment').val() || 0;
                var grand_total = $('.grand_total').val() || 0;
                var due = parseInt(grand_total) - parseInt(pay);
                $('.due').val(due);
                $('#due').html(due);
            }
        })
    </script>
@endpush