@extends('backend.layouts..master')

@section('title', 'Create Invoice')

@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">
    <style>
        input[readonly] {
            background: #dfe0e0;
            border: 1px;
        }
        span.Zebra_DatePicker_Icon_Wrapper {
            width: 100% !important;
        }
        i.fa.red.fa-remove{
            cursor: pointer;
        }
    </style>
@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 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>{{$type->name}} Invoice Create </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('sales.store')}}" method="post" class="form-" role="form" autocomplete="off" >
                                {{ csrf_field()}}
                                <div class="row">
                                    <div class="col-sm-3">  
                                        <div class="form-group">
                                            <label>Customer Search<span class="required">*</span></label>
                                            <input class="form-control" type="text" id="customer_name" name="customer_name" placeholder="Customer Name & Phone" required style="width:100%" autocomplete="off" / >
                                            <input type="hidden" name="customer_id" id="customer_id">
                                            <input type="hidden" name="invoice_type_id" id="invoice_type_id" value="{{$type->id}}" >
                                            <p class="error-sms">{{ $errors->first('customer_name') }}</p>
                                        </div>
                                    </div>
                                    <div class="col-sm-2">
                                        <div class="form-group">
                                            <label> Phone</label>
                                            <input type="text" name="customer_phone" id="customer_phone" class="form-control" placeholder="01xxxxxxxx" required>
                                            <p class="error-sms">{{ $errors->first('customer_phone') }}</p>
                                        </div>
                                    </div>
                                    <div class="col-sm-2">
                                        <div class="form-group">
                                            <label > Address <span class="required">*</span></label>
                                            <input type="text" name="customer_address" id="customer_address" class="form-control" value="" placeholder="Address" >
                                            <p class="error-sms">{{ $errors->first('customer_address') }}</p>
                                        </div>
                                    </div>
                                    <div class="col-sm-2">  
                                        <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="{{ request()->sale_date ? request()->sale_date : date('d-m-Y') }}" placeholder="dd-mm-yyyy">
                                            <p class="error-sms">{{ $errors->first('sale_date') }}</p>
                                        </div>
                                    </div>
                                    <div class="col-sm-3">
                                        <div class="form-group">
                                            <label for="note"> Note</label>
                                            <input type="text" name="note" id="note" class="form-control" placeholder="Note About this Purchase">
                                            <p class="error-sms">{{ $errors->first('note') }}</p>
                                        </div>
                                    </div>
                                </div>
                                <hr/>
                                <div class="row">
                                    <div class="col-sm-3"></div>
                                    <div class="col-sm-3">
                                        <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-3">
                                        <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-3"></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">Stock</th>
                                            <th class="all">Height </th>
                                            <th class="all">Width </th>
                                            <th class="all" title="">Size</th>
                                            <th class="all">Quantity</th>
                                            <th class="all" title="Total Squre Feet">TSQF</th>
                                            <th class="all">Sale Price</th>
                                            <th class="all">Discount</th>
                                            <th class="all">Sub Total</th>
                                            <th class="all">Action</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        @php $ss = 0;@endphp
										@foreach($drafts as $sd)
											@php $ss++ ;@endphp
											@if($sd->pd)
											<tr id='{{$ss}}'>
												<td>{{$ss}}</td>
												<td>
													<input type='hidden' name='category_id[]' value='{{$sd->category_id}}' />
													<input type='hidden' name='product_id[]' value='{{$sd->product_id}}'>
													<input type='hidden' name='type_id[]' value='{{$sd->type_id}}' />
													<input type='hidden' name='purchase_details_id[]' id='purchase_detail_{{$ss}}' value='{{$sd->purchase_detail_id}}' />
													<input type='hidden' name='code_no[]' value='{{$sd->code_no}}' />
													
													<input type='hidden' name='unit_id[]' value='{{$sd->unit_id}}' />
													
													<input type='hidden' id='{{$ss}}_stock' name='stock[]' value='{{$sd->pd->now_stock}}' size='5'/>
													<input type="hidden" name="labour_total[]" id='{{$ss}}_labour_total2' value="{{ $sd->labour_total }}"/>
													<input type="hidden" name="profit_amount[]" class="profit_amount" id='{{$ss}}_profit_amount' value="{{ $sd->profit_amount }}"/>
													<input type="hidden" name="profit_total[]" class="profit_total" id='{{$ss}}_profit_total' value="{{ $sd->profit_total }}"/>
													<input type="hidden" name="purchase_price_total[]" class="purchase_price_total" id='{{$ss}}_purchase_price_total' value="{{ $sd->purchase_price_total }}"/>

												{{$sd->product_name}}({{$sd->code_no}}) </td>
												<td>{{$sd->pd->now_stock}}</td>
												<td><input type='text' id='{{$ss}}_height' class='height' name='height[]' value='{{$sd->height}}' size='5'/></td>
												<td><input type='text' id='{{$ss}}_width' class='width' name='width[]' value='{{$sd->width}}' size='5'/></td>
												<td><input type='text' id='{{$ss}}_size' class='size' name='size[]'  value='{{$sd->size}}' size='5' placeholder="00ml/10 x 12" readonly /></td>
												<td><input type='text' id='{{$ss}}_ordered_quantity' class='ordered_quantity' name='ordered_quantity[]' min='1' value='{{$sd->pd->now_stock >= $sd->quantity ? $sd->quantity :  $sd->pd->now_stock}}' size='5' placeholder="00"/></td>
												<td><input type='text' id='{{$ss}}_tsqf' class='tsqf' name='tsqf[]' value='{{$sd->tsqf}}' size='5' min='1' readonly /></td>
												<td><input type='text' id='{{$ss}}_price' class='sale_price' name='sale_price[]' value='{{$sd->sale_price}}' size='5' placeholder="0.00" ></td>
												<td>
												    <input type='hidden' id='{{$ss}}_labour_cost' class='labour_cost' name='labour_cost[]' value='{{$sd->labour_cost}}' size='5' placeholder="0.00" >
												    <input type="hidden" name="sub_total[]" id='{{$ss}}_sub_total2' value="{{ $sd->sub_total }}"/>
												    <input type='text' id='{{$ss}}_single_discount' class='single_discount' name='single_discount[]' value='{{$sd->discount}}' size='5' placeholder='0.00' >
												</td>
												<!--<td class='labour_total' id='{{$ss}}_labour_total'>{{$sd->labour_total}}</td>-->
												<td class='sub_total' id='{{$ss}}_sub_total'>{{$sd->sub_total}}</td>
												<td class='text-center'><i class='fa red fa-remove fa-lg'></i></td>
											</tr>
											@endif
										@endforeach
                                    </tbody>
                                    <tfoot>
                                        <tr>
                                            <th class="all" colspan="3">Total</th>
                                            <th id="supplier_price"></th>
                                            <th id="model_no"></th>
                                            <th id="">-</th>
                                            <th id="total_ordered">0</th>
                                            <th id="total_squarefeet">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-7">
                                        <div class="form-group">
											<label class="control-label col-sm-4">Other Cost</label>
											<div class="col-md-8">
												<input type="text" class="form-control" id="other_cost" min="0" name="other_cost" placeholder="Other Cost Include If need">
												<p class="error-sms">{{ $errors->first('other_cost') }}</p>
											</div>  
										</div>
                                        <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">Grand Total</label>
                                            <div class="col-md-8">
                                                <input type="number" class="form-control grand_total" id="" min="0" readonly name="grand_total" >
                                                <p class="error-sms">{{ $errors->first('grand_total') }}</p>
                                            </div>  
                                        </div>
                                        <div class="form-group">
                                            <label class="control-label col-sm-4">Payment Amount</label>
                                            <div class="col-md-8">
                                                <input type="text" class="form-control" id="payment" min="0" name="payment" placeholder="0.00" required>
                                                <p class="error-sms">{{ $errors->first('payment') }}</p>
                                            </div>  
                                        </div>
                                        <div class="form-group">
                                            <label class="control-label col-sm-4">Check Information</label>
                                            <div class="col-sm-2">
                                                <div class="checkbox">
                                                    <label><input type="checkbox" class="ch" name="sms"> Send SMS </label>
                                                </div>
                                            </div> 
                                            <div class="col-sm-2">
                                                <div class="checkbox">
                                                    <label><input type="checkbox" class="ck" id="paid"> Full Paid </label>
                                                </div>
                                            </div>
                                            <div class="col-sm-4">
                                                <div id="pdate_group" class="form-group hidden" >
                                                    <label> Possible Date <span class="required">*</span></label>
                                                    <input id="possible_date" type="date" name="possible_date"  class="form-control" data-zdp_readonly_element="true"  placeholder="dd-mm-yyyy">
                                                    <p class="error-sms">{{ $errors->first('possible_date') }}</p>
                                                </div>
                                            </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> 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" class="total_price" name="total_price"  />
                                        <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">
                                      <a href="javascript:history.back()" class="btn btn-warning"><i class="ace-icon fa fa-arrow-left"></i> Back</a>
                                      <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" src="{{asset('myfile/backend/assets/js/bootstrap-notify.min.js')}}" ></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $('#datepicker').Zebra_DatePicker({
                format: 'd-m-Y',
                //direction: 1,
            });
            $('#possible_dates').Zebra_DatePicker({
                format: 'd-m-Y',
                //direction: 1,
            });
            $(".select2").select2();

            AutoComplete();
            
            calculate_ordered_quantity();
    		calculate_sub_total();
    		calculate_total();
    		calculate_due();

            function AutoComplete(){
                 if( typeof ($.fn.autocomplete) === 'undefined'){ return; }
               // console.log('init_autocomplete');
                var token = "{{csrf_token()}}";
                $.ajax({
                    url: '{{ route("sales.customerList") }}',
                    type: 'Get',
                    data: {'_token' : token},
                    dataType: 'json',
                    success: function (response) {
                        //console.log(response);
                        /*-----------------*/
                        var countriesArray = $.map(response, function(value, key) {
                          return {
                            value: value,
                            data: key
                          };
                        });

                        // initialize autocomplete with custom appendTo
                        $('#customer_name').autocomplete({
                          lookup: countriesArray
                        });
                        /***************-*/
                    }
                });
            }
            /*-------------------Customer Details search section-------------------------*/
            $(document).on('focusout','#customer_name',function(){
                getCustomer();
            });
            $(document).on('click','.autocomplete-suggestion', function(){
               // alert('ssss')
                getCustomer();
            })
            /*-----------*/
            function getCustomer(){
                var customer = $('#customer_name').val();
                if(customer != ''){
                    var token = "{{csrf_token()}}";
                    $.ajax({
                        url: '{{ route("sales.customerDetails") }}',
                        type: 'GET',
                        data: {customer:customer, '_token' : token},
                        dataType: 'json',
                        success: function (response) {  
                            if(response != ''){
                                //console.log(response)
                                $('#customer_id').val(response.id)
                                $('#customer_name').val(response.name)
                                $('#customer_phone').val(response.phone)
                                //$('#customer_address').val(response.customer_address)
                            }
                        }
                    });
                }
            }
        });
        $("#category").change(function () {
            var type = $(this).val();
            var token = "{{csrf_token()}}";
            $.ajax({
                url: '{{ route("ajaxproduct.list") }}',
                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 = {{$ss}};
        $("#product").change(function () {
            var id = $(this).val();
           // $("#supplier").attr('disabled', true);
            var token = "{{csrf_token()}}";
            if(id != ''){
                $.ajax({
                    url: '{{ route("ajaxproduct.detail") }}',
                    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 pdid = response['id'];  
                        var type_id = response['type_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['sale_price'];
                        var height =  1;
                        var width =  1;
                        var size =  height*width;
                        var ordered_quantity =  1;
                        var tsqf = ordered_quantity * size;
                        var sub_total =  sale_price*ordered_quantity;
                        sl++
                        $("#sale tbody").append(
                            "<tr id='"+sl+"'>"
                              +"<td><input type='hidden' name='type_id[]' value='"+type_id+"' />'"+sl+"</td>"
                              +"<td><input type='hidden' name='purchase_details_id[]' id='purchase_detail_"+sl+"' value='"+pdid+"' />"+name+" ("+code+")</td>"
                             // +"<td>"+category_name+" </td>"
                             // +"<td>"+unit_name+" </td>"
                              +"<td><input  type='hidden' id='"+sl+"_stock' name='stock[]' value='"+stock+"' size='10'/>"+stock+"</td>"
                              +"<td><input id='"+sl+"_height' class='height' type='text' name='height[]'  size='5' value='"+height+"' required /></td>"
                              +"<td><input id='"+sl+"_width' class='width' type='text' name='width[]'  size='5' value='"+width+"' required /></td>"
                              +"<td><input id='"+sl+"_size' class='size' type='text' name='size[]' size='5' value='"+size+"' required readonly /></td>"
                              +"<td><input type='text' id='"+sl+"_ordered_quantity' class='ordered_quantity' name='ordered_quantity[]' min='1' value='"+ordered_quantity+"' size='5' /></td>"
                              +"<td><input type='text' id='"+sl+"_tsqf' class='tsqf' name='tsqf[]' min='1' value='"+tsqf+"' size='5' readonly /></td>"
                              +"<td><input type='text' id='"+sl+"_price' class='sale_price' name='sale_price[]' value='"+sale_price+"' size='5'></td>"
                              +"<td><input type='text' id='"+sl+"_single_discount' class='single_discount' name='single_discount[]' value='' size='5' placeholder='0.00'></td>"
                              +"<td class='sub_total' id='"+sl+"_sub_total'>"+sub_total+"</td>"
                              +"<td class='text-center'><i class='fa red fa-remove 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());
                        var total_squarefeet = parseFloat($('#total_squarefeet').html());
                        total_ordered = total_ordered + 1;
                        total_squarefeet = total_squarefeet + 1;

                        $('#total_ordered').html(total_ordered);
                        $('#total_squarefeet').html(total_squarefeet);

                        calculate_sub_total();
                        calculate_total();
                        calculate_due();
                        
                        $('#category').trigger('change');
                    }
                });
            }
        });
        $(document).on('click','.fa-remove',function(){
            var id = $(this).parent().parent().attr('id');
            var token = "{{csrf_token()}}";
			var pd_id = $("#purchase_detail_"+id).val();
            //console.log(product_id)
            $.ajax({
                url: '{{ route("sales.sdf_remove") }}',
                type: 'Get',
                data: {pd_id:pd_id, '_token' : token},
                dataType: 'json',
                success: function (response) {
                    console.log(response)

                    $('#'+id).remove();
                    calculate_ordered_quantity();
                    calculate_sub_total();
                    calculate_total();
                    calculate_due();
                }
            });

        });
        /*-------------------*/
        $(document).on('keyup','.height',function(){
            var id = $(this).parent().parent().attr('id');
            var height = $(this).val() || 0;
            var width = $('#'+id+'_width').val() || 0;
            var quantity = $('#'+id+'_ordered_quantity').val() || 0;
            var stock = $('#'+id+'_stock').val();
            var price = $('#'+id+'_price').val();

            var size = parseFloat(height) * parseFloat(width);

            var tsqf = size * parseFloat(quantity);

            if(parseFloat(stock) >= parseFloat(tsqf)){
                $('#'+id+'_size').val(size);
                 $('#'+id+'_tsqf').val(tsqf);

                var sub_total =  price*tsqf;
                $('#'+id+'_sub_total').html(sub_total);

                calculate_ordered_quantity();
                calculate_sub_total();
                calculate_total();
                calculate_due();
                update_sales_draft(id);
            }else{
                alert('Product Stock is low than Ordered Square Feet!!!!!!');
                $(this).val(0);
                $('#'+id+'_sub_total').empty();
                $('#'+id+'_tsqf').val(0);
                $('#'+id+'_ordered_quantity').val(0);
            }
        });
        $(document).on('keyup','.width',function(){
            var id = $(this).parent().parent().attr('id');
            var width = $(this).val() || 0;
            var height = $('#'+id+'_height').val() || 0;
            var quantity = $('#'+id+'_ordered_quantity').val() || 0;
            var stock = $('#'+id+'_stock').val();
            var price = $('#'+id+'_price').val();

            var size = parseFloat(height) * parseFloat(width);
            var tsqf = size * parseFloat(quantity);

            if(parseFloat(stock) >= parseFloat(tsqf)){
                $('#'+id+'_size').val(size);
                $('#'+id+'_tsqf').val(tsqf);

                var sub_total =  price*tsqf;
                $('#'+id+'_sub_total').html(sub_total);

                calculate_ordered_quantity();
                calculate_sub_total();
                calculate_total();
                calculate_due();
                update_sales_draft(id);
            }else{
                alert('Product Stock is low than Ordered Square Feet!!!!!!');
                $(this).val(0);
                $('#'+id+'_sub_total').empty();
                $('#'+id+'_tsqf').val(0);
                $('#'+id+'_ordered_quantity').val(0);
            }

           
        });
        $(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();
            var size = $('#'+id+'_size').val();
            var tsqf = size * parseFloat(quantity);
            
            if(parseFloat(stock) >= parseFloat(tsqf)){
                
                $('#'+id+'_tsqf').val(tsqf);
                var sub_total =  price*tsqf;
                $('#'+id+'_sub_total').html(sub_total);

                calculate_ordered_quantity();
                calculate_sub_total();
                calculate_total();
                calculate_due();
                update_sales_draft(id);
            }else{
                alert('Product Stock is low than Ordered Square Feet!!!!!!');
                $('#'+id+'_sub_total').empty();
                $('#'+id+'_tsqf').val(0);
                $('#'+id+'_ordered_quantity').val(0);

                //calculate_ordered_quantity();
                //calculate_sub_total();
               // calculate_total();
            }
        });
        $(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 tsqf = $('#'+id+'_tsqf').val();
            
                var sub_total =  price*tsqf;
                $('#'+id+'_sub_total').html(sub_total);
                calculate_ordered_quantity();
                calculate_sub_total();
                calculate_total();
                calculate_due();
                update_sales_draft(id);
        });
        $(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 tsqf = $('#'+id+'_tsqf').val();
            var discount = $('#'+id+'_single_discount').val() || 0;
            //alert(discount)
                var sub_total =  price*tsqf;
                $('#'+id+'_sub_total').html(sub_total - discount);
                
            calculate_ordered_quantity();
            calculate_sub_total();
            calculate_total();
            calculate_due();
            update_sales_draft(id);
        });
        $(document).on('keyup','#other_cost',function(){
			calculate_discount();
            calculate_grand_total();
			calculate_due();
			//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;
            var tsqf = 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);
            //calculate order total squrefeet
            $(".tsqf").each(function() {
                var sq = parseFloat($(this).val());
                tsqf = tsqf + sq;
            });
            $('#total_squarefeet').html(tsqf);
        }
        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 other = $('#other_cost').val() || 0;
            var grand_total = (parseFloat($('#total_value').html()) + parseFloat(other))- parseFloat($('#total_discount').html());
            /*------------24-15-19------------------*/
            
            /*var paid = $('#paid_amount').html();
            var due = parseFloat(grand_total) - parseFloat(paid);*/
            
            /*--------------------------*/
            
            $('#grand_total').html(grand_total);
            $('.grand_total').val(grand_total);
            $('#due').html(grand_total);
            $('.due').val(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 other = $('#other_cost').val() || 0;
            var pay = $('#payment').val() || 0;
            var grand_total = $('.grand_total').val() || 0;
            var due = parseFloat(grand_total) - parseFloat(pay);
            if(due > 0){
                $("#possible_date").prop('required',true);
                $("#pdate_group").removeClass('hidden');
            }else{
                $("#possible_date").prop('required',false);
                $("#pdate_group").addClass('hidden');
            }
            $('.due').val(due);
            $('#due').html(due);
        }
        $("#paid").click(function(){
            if($(this).is(':checked')){
                //alert('Check')
                $("#payment").val($('.due').val());
                calculate_due();
            }else{
                //alert('uncheck');
                $("#payment").val(0);
                calculate_due();
            }
        });
        function update_sales_draft(id){
            var token = "{{csrf_token()}}";
            var pd_id = $("#purchase_detail_"+id).val();
            var barcode = $("#barcode_"+id).val();
            var height = $("#"+id+"_height").val();
			var width = $("#"+id+"_width").val();
			var tsqf = $("#"+id+"_tsqf").val();
			var size = $("#"+id+"_size").val();
            var quantity = $("#"+id+"_ordered_quantity").val();
            
			var purchase_price = $("#"+id+"_purchase_price").val();
            var ppt = $("#"+id+"_purchase_price_total").val();
            var sale_price = $("#"+id+"_price").val();
			var profit_amount = $("#"+id+"_profit_amount").val();
            var profit_total = $("#"+id+"_profit_total").val();
            var labour_cost = $("#"+id+"_labour_cost").val();
            var discount = $("#"+id+"_single_discount").val();
            var discount_type = $("#"+id+"_single_discount_type").val();
            var labour_total = $("#"+id+"_labour_total").html();
            var sub_total = $("#"+id+"_sub_total").html();
			
           // console.log(labour_cost)
            $.ajax({
                url: '{{ route("sales.sales_draft_update") }}',
                type: 'Post',
                data: {pd_id:pd_id,height:height,width:width,size:size,quantity:quantity,tsqf:tsqf,purchase_price:purchase_price,ppt:ppt,sale_price:sale_price,profit_amount:profit_amount,profit_total:profit_total,labour_cost:labour_cost,discount:discount,discount_type:discount_type,labour_total:labour_total,sub_total:sub_total, '_token' : token},
                dataType: 'json',
                success: function (response) {
                    console.log(response)
                },error: function (e) {
					//$("#output").text(e.responseText);
					console.log("ERROR : ", e);
					// $("#btnSubmit").prop("disabled", false);
				}
            });
        }
    </script>
@endpush