<?php $__env->startSection('title', 'Create Invoice'); ?>

<?php $__env->startPush('css'); ?>

<link rel="stylesheet" href="<?php echo e(asset('backend/plugins/select2.min.css')); ?>">
<link rel="stylesheet" href="<?php echo e(asset('myfile/backend/assets/datepicker/zebra_datepicker.min.css')); ?>" type="text/css">
<link rel="stylesheet" href="<?php echo e(asset('myfile/backend/assets/datepicker/examples.css')); ?>" type="text/css">
<style>
input[readonly] {
    background: #dfe0e0;
    border: 1px;
}
</style>
<?php $__env->stopPush(); ?>

<!-- page content -->
<?php $__env->startSection('content'); ?>
<div class="right_col" role="main">
    <div class="">
        <div class="clearfix"></div>
        <?php if(Session::has('success')): ?>
        <div class="alert alert-success">
            <?php echo e(Session::get('success')); ?><div id="msg"></div>
        </div>
        <?php endif; ?>
        <?php if(Session::has('error')): ?>
        <div class="alert alert-danger">
            <?php echo e(Session::get('error')); ?>

        </div>
        <?php 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>Create Invoice</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="<?php echo e(route('sales.store')); ?>" method="post" class="form-" role="form" autocomplete="off">
                            <?php echo e(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">
                                        <p class="error-sms"><?php echo e($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"><?php echo e($errors->first('customer_phone')); ?></p>
                                    </div>
                                </div>
                                <div class="col-sm-2">
                                    <div class="form-group">
                                        <label> Invoice No <span class="required">*</span></label>
                                        <input type="text" name="invoice_no" class="form-control" value="<?php echo e($inv_no); ?>"
                                            placeholder="Invoice No" readonly>
                                        <p class="error-sms"><?php echo e($errors->first('invoice_no')); ?></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="<?php echo e(date('d-m-Y')); ?>"
                                            placeholder="dd-mm-yyyy">
                                        <p class="error-sms"><?php echo e($errors->first('sale_date')); ?></p>
                                    </div>
                                </div>
                                <div class="col-sm-3">
                                    <div class="form-group">
                                        <label> Note</label>
                                        <input type="text" name="note" class="form-control"placeholder="Note About this Purchase">
                                        <p class="error-sms"><?php echo e($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>
                                            <?php $__currentLoopData = $categories; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $category): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                            <option value="<?php echo e($category->id); ?>"> <?php echo e($category->name); ?> </option>
                                            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                        </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>
                            <div class="row table-responsive">
                                 <table class="table table-striped table-bordered table-condensed 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">Code </th>
                                            <th class="all">Stock</th>
                                            <th class="all">Quantity</th>
                                            
                                            <th class="all">Sale 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="2">Total</th>
                                            <th id="supplier_price"></th>
                                            <th id="total_square"></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>
                            <div class="row">
                                <div class="col-sm-8">
                                    <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"><?php echo e($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"><?php echo e($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"><?php echo e($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"><?php echo e($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"><?php echo e($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-3">
                                            <div class="checkbox">
                                                <label><input type="checkbox" class="ck" name="sale_type" > Condition Invoice</label>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-sm-4">
                                    <table  class="table table-striped table-bordered table-condensed 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">
                                    <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>
</div>
<!-- /page content -->
<?php $__env->stopSection(); ?>
<?php $__env->startPush('js'); ?>
<script src="<?php echo e(asset('backend/plugins/select2.min.js')); ?>"></script>
<!-- Jquery Plugin For Date Calender-->
<script type="text/javascript" src="<?php echo e(asset('myfile/backend/assets/datepicker/zebra_datepicker.src.js')); ?>"></script>
<!-- jQuery autocomplete -->
<script src="<?php echo e(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: <?php echo e(setting()->previous_date); ?>,
        });
        $(".select2").select2();

        AutoComplete();

        function AutoComplete() {
            if (typeof($.fn.autocomplete) === 'undefined') {
                return;
            }
            // console.log('init_autocomplete');
            var token = "<?php echo e(csrf_token()); ?>";
            $.ajax({
                url: '<?php echo e(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 = "<?php echo e(csrf_token()); ?>";
                $.ajax({
                    url: '<?php echo e(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 = "<?php echo e(csrf_token()); ?>";
        $.ajax({
            url: '<?php echo e(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 code = response[i]['code'];
                    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 = 0;
    $("#product").change(function() {
        var product = $(this).val();
        // $("#supplier").attr('disabled', true);
        var token = "<?php echo e(csrf_token()); ?>";
        if (product != '') {
            $.ajax({
                url: '<?php echo e(route("ajaxproduct.detail")); ?>',
                type: 'Get',
                data: { id: product, '_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 pid = response['product_id'];
                    var cid = response['productcategory_id'];
                    var uid = response['unit_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 square_foot = response['square_foot'];
                    var ordered_quantity = 1;
                   // var tsqf = ordered_quantity * square_foot;
                    var sub_total = ordered_quantity * sale_price;
                    sub_total = sub_total.toFixed(2);
                    sl++
                    $("#sale tbody").append(
                        "<tr id='" + sl + "'>"
                        + "<td> <input type='hidden' name='product_id[]' value='" + pid +"' /> " + sl + "</td>"
                        + "<td><input type='hidden' name='category_id[]' value='" + cid +"' />" + name + " </td>"
                        + "<td><input type='hidden' name='unit_id[]' value='" + uid +"' />"
                        + "<input type='hidden' name='purchase_details_id[]' value='" + pdid +"' />"
                        + "<input type='hidden' name='code[]' value='" + code +"' />" + code + " </td>"
                        + "<td><input  type='hidden' id='" + sl + "_stock' name='stock[]' value='" +stock + "' size='10'/>" + stock + "</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 +  "_square_foot' class='square_foot' type='text' name='square_foot[]' size='5' value='" + square_foot + "' required readonly /></td>"
                        //+"<td><input type='text'  id='"+sl+"_tsqf' name='tsqf[]' value='"+tsqf+"' readonly size='6'></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-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());
                    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();
                }
            });
        }
    });
    $(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();
        calculate_due();
    });
    $(document).on('keyup', '.ordered_quantity', function() {
        var id = $(this).parent().parent().attr('id');
        var price = $('#' + id + '_price').val();
        var quantity = parseFloat($('#' + id + '_ordered_quantity').val()) || 0;
        var stock = parseFloat($('#' + id + '_stock').val());
        //var squarefoot = $('#'+id+'_square_foot').val();

        //console.log(quantity);

        if (stock >= quantity) {
            //var tsqf = quantity * squarefoot;
            var sub_total = quantity * price;
            $('#' + id + '_sub_total').html(sub_total.toFixed(2));
            //$('#'+id+'_tsqf').val(tsqf);
            calculate_ordered_quantity();
            calculate_sub_total();
            calculate_total();
            calculate_due();
        } 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 squarefoot = $('#'+id+'_square_foot').val();
        //var tsqf = quantity * squarefoot;

        var sub_total = quantity * price;
        $('#' + id + '_sub_total').html(sub_total.toFixed(2));
        calculate_ordered_quantity();
        calculate_sub_total();
        calculate_total();
        calculate_due();
    });
    $(document).on('keyup', '.single_discount', function() {
        var id = $(this).parent().parent().attr('id');

        var price = $('#' + id + '_price').val();
        var quantity = $('#' + id + '_ordered_quantity').val() || 0;
        //var tsqf = $('#'+id+'_tsqf').val();
        var discount = $('#' + id + '_single_discount').val() || 0;
        //var squarefoot = $('#'+id+'_square_foot').val();
       // var tsqf = quantity * squarefoot;
        var sub_total = quantity * price;
        
        $('#' + id + '_sub_total').html(sub_total - discount);

        calculate_ordered_quantity();
        calculate_sub_total();
        calculate_total();
        calculate_due();
    });
    $(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;
        //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.toFixed(2));

        /*-------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($('#total_discount').html())+parseFloat($('#total_tax').html())+parseFloat($('#total_shipping').html());
        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);
        //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 = parseFloat(grand_total) - parseFloat(pay);
        $('.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();
        }
    });
</script>
<?php $__env->stopPush(); ?>
<?php echo $__env->make('backend.layouts..master', array_except(get_defined_vars(), array('__data', '__path')))->render(); ?>