@extends('backend.layouts..master')
@section('title', 'Factory Product Entry')
@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="">
            @if(Session::has('success'))
                <div class="alert alert-success">
                    {{ Session::get('success') }}<div id="msg"></div>
                </div>
            @endif
            @if(Session::has('error'))
                <div class="alert alert-danger">
                    {{ Session::get('error') }}
                </div>
            @endif
            <div class="resp"></div>
            <div class="row">
                <div class="col-md-12 col-sm-12 col-xs-12">
                    <div class="x_panel">
                        <div class="x_title">
                            <h2>Factory Product Entry</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('wastage.store')}}" method="post" class="form-" role="form" autocomplete="off">
                                {{ csrf_field()}}
                                <div class="row">
                                    <div class="col-sm-4">
                                        <div class="form-group ">
                                            <label>Select Category <span class="required">*</span></label>
                                            <select class="form-control select2" name="category_id" id="category">
                                                <option value="">- Select Category -</option>
                                                @foreach($categories as $category)
                                                <option value="{{ $category->id }}"> {{ $category->name }} </option>
                                                @endforeach
                                            </select>
                                        </div>
                                    </div>
                                    <div class="col-sm-4">
                                        <div class="form-group">
                                            <label>Select Product <span class="required">*</span></label>
                                            <select class="form-control select2" name="product_name" id="product">
                                                <option value="">-Select Product-</option>
                                            </select>
                                        </div>  
                                    </div>
                                    <div class="col-sm-4">
                                        <div class="form-group">
                                            <label> Date <span class="required">*</span></label>
                                            <input id="datepicker" type="text" name="sale_date"  class="form-control" data-zdp_readonly_element="true" value="{{ date('d-m-Y')}}" placeholder="dd-mm-yyyy">
                                            <p class="error-sms">{{ $errors->first('sale_date') }}</p>
                                        </div>
                                    </div>
                                </div>
                                <table class="table table-striped 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">Stock</th>
                                            <th class="all">Quantity</th>
                                            <th class="all">Purchase Price</th>
                                            <th class="all">Discount</th>
                                            <th class="all">Sub Total</th>
                                            <th class="all">Delete</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                    </tbody>
                                    <tfoot>
                                        <tr>
                                            <th class="all" colspan="3">Total</th>
                                            <th id="supplier_price"></th>
                                            <th id="total_ordered">0</th>
                                            <th id="">-</th>
                                            <th id="single_total_dis">0</th>
                                            <th id="total_sub">0</th>
                                            <th>-</th>
                                        </tr>
                                    </tfoot>
                                </table>
                                <div class="row">
                                    <div class="col-sm-3"></div>
                                    <div class="col-sm-6">
                                        <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 Price: </th>
                                                    <th><span class="pull-right" id="total_value">0</span></th>
                                                </tr>
                                            </tfoot>
                                        </table>
                                        <input type="hidden" id="total_price" class="total_price" name="total_price"  />
                                        <input type="hidden" class="due" name="due"  />
                                    </div>
                                    <div class="col-sm-3"></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-warning" type="reset">Reset</button>
                                      <button type="submit" class="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 src="{{asset('backend/vendors/devbridge-autocomplete/dist/jquery.autocomplete.min.js') }}"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $('#datepicker').Zebra_DatePicker({
                format: 'd-m-Y',
                //direction: 1,
            });
            $(".select2").select2();
        });

        $("#category").change(function () {
            var type = $(this).val();
            var token = "{{csrf_token()}}";
            $.ajax({
                url: '{{ route("purchase.getProduct") }}',
                type: 'Get',
                data: {type: type, '_token' : token},
                dataType: 'json',
                success: function (response) {
                //console.log(response)
                    var len = response.length;
                    $("#product").empty();
                    $("#product").append("<option value=''> Select Product</option>");
                    if (len == 0) {
                        $("#product").empty();
                        var id = "";
                        var name = "";
                        $("#product").append("<option value='" + id + "'>" + name + "</option>");
                    }
                    for (var i = 0; i < len; i++) {
                        var id = response[i]['id'];
                        var name = response[i]['product_name'];
                        var stock = response[i]['now_stock'];
                        var disable = "";
                        $("#product").append("<option " + disable + " value='" + id + "'>"+name+" ( "+stock+" ) </option>");
                    }
                }
            });
        });
        /*---------------------------*/
        var array = [];
        var total_tax = 0;
        var tax_type = "Fixed";
        var SL = 1;
        $("#product").change(function () {
            var id = $(this).val();
           // $("#supplier").attr('disabled', true);
            var token = "{{csrf_token()}}";
            $.ajax({
                url: '{{ route("purchase.getProducts") }}',
                type: 'Get',
                data: {id: id, '_token' : token},
                dataType: 'json',
                success: function (response) {
                //console.log(response)
                    var len = response.length;
                    for (var i = 0; i < len; i++) {
                        var id = response[1][i]['id'];
                        var name = response[1][i]['product_name'];
                        var disable = "";
                        $("#product").append("<option " + disable + " id='product_" + id + "' value='" + id + "'>" + name + "</option>");
                    }

                    var id = response['id'];  
                    var name = response['product_name'];                    
                    var category_name = response['category_name'];                            
                    var unit_name = response['unit_name'];               
                    var code =  response['code'];
                    var stock =  response['now_stock'];
                    var sale_price =  response['supplier_price'];
                    var ordered_quantity =  1;
                    var sub_total =  sale_price*ordered_quantity;

                    $("#sale tbody").append(
                        "<tr id='"+id+"'>"
                          +"<td>"+(SL++)+"</td>"
                          +"<td><input type='hidden' name='purchase_details_id[]' value='"+id+"' />"+name+" ("+code+")</td>"
                          +"<td><input type='hidden' name='code[]' value='"+code+"' />"+category_name+" </td>"
                         // +"<td>"+unit_name+" </td>"
                          +"<td><input  type='hidden' id='"+id+"_stock' name='stock[]' value='"+stock+"' size='10'/>"+stock+"</td>"
                         // +"<td><input id='"+id+"_height' type='text' name='height[]' placeholder='00' size='5' value='1' required /></td>"
                         // +"<td><input id='"+id+"_width' type='text' name='width[]' placeholder='00' size='5' value='1' required /></td>"
                          //+"<td><input id='"+id+"_sqf' type='hidden' name='sqf[]' placeholder='00' size='5' value='1' required /></td>"
                          +"<td><input type='text' id='"+id+"_ordered_quantity' class='ordered_quantity' name='ordered_quantity[]' min='1' value='"+ordered_quantity+"' size='5' /></td>"
                          +"<td><input type='text' id='"+id+"_price' class='sale_price' name='sale_price[]' value='"+sale_price+"' size='5'></td>"
                          +"<td><input type='text' id='"+id+"_single_discount' class='single_discount' name='single_discount[]' value='' size='5' placeholder='0.00'></td>"
                          +"<td class='sub_total' id='"+id+"_sub_total'>"+sub_total+"</td>"
                          +"<td class='text-center'><i class='fa red 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();
                }
            });
        });
        $(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 stock = $('#'+id+'_stock').val();

            if(parseInt(stock) >= parseInt(quantity)){
                var sub_total =  price*quantity;
                $('#'+id+'_sub_total').html(sub_total);
                calculate_ordered_quantity();
                calculate_sub_total();
                calculate_total();
            }else{
                alert('Product Stock is low than Ordered Quantity!!!!!!');
                $('#'+id+'_sub_total').empty();
                $('#'+id+'_ordered_quantity').val('');
            }
        });
        $(document).on('keyup','.sale_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();
        });
        $(document).on('keyup','.single_discount',function(){
            var id = $(this).parent().parent().attr('id');
            
            var price = $('#'+id+'_price').val();
            var quantity = $('#'+id+'_ordered_quantity').val();
            var discount = $('#'+id+'_single_discount').val() || 0;
            //alert(discount)
                var sub_total =  price*quantity;
                $('#'+id+'_sub_total').html(sub_total - discount);
                
                calculate_ordered_quantity();
                calculate_sub_total();
                calculate_total();
            
        });
        $(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;
            var total_dis = 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);
            
            /*-------single discount calculation ------------*/
            $(".single_discount").each(function() {
                var dis = parseFloat($(this).val() || 0);
                total_dis = total_dis + dis;
            });
            $('#single_total_dis').html(total_dis);
        }
        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());
            /*------------24-15-19------------------*/
            
            /*var paid = $('#paid_amount').html();
            var due = parseInt(grand_total) - parseInt(paid);*/
            
            /*--------------------------*/
            
            $('#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