window.onbeforeunload = function exit() {
    if($('#status').val()=="done" && $('#saveAll').attr('disabled') == 'disabled'){
        return "هل أنت متأكد من الخروج ؟";
    }
}

$(document).ready(function(){
    var company_id=$('#company_id').val();
    var sale_bill_id=$('#sale_bill_id').val();
    var sale_bill_number = $('#sale_bill_number').val(); 
    let token = $('meta[name=_token]').attr('content');
    let app_url = $('meta[name=app_url]').attr('content');
    var count = $('#elementCout').val() ;
    let status = $('#status').val(); 
    let elementError = 0;

    checkInvoiceItem();
    getProducts();
    if(count){
        calculateTotal();
    }else{
        count = 1 ;
    }

	$(document).on('click', '#addRow', function() { 
		count++;
        var product = $('#product_id').val();
		var productName =  $('#product_id option[value="' + product + '"]').data('name');
		var is_product =  $('#product_id option[value="' + product + '"]').data('product');
		var productMaxCount =  checkProduct(product);
        var price = $('#product_price').val();
        var quantity = parseFloat($('#quantity').val());
        var unit = $('#unit_id').val();
		var unitName =  $('#unit_id option[value="' + unit + '"]').data('name');
        var totalItemPrice = $('#quantity_price').val();
        var unit_quantity = $('#product_unit_quantity').val();


        if(product==""){
            Error("الرجاء إختيار صنف");
                return 0 ;
        }
        if(price==""|| price==0){
            Error("الرجاء إدخال سعر");
                return 0 ;
        }
        if(quantity=='' ||quantity==0 || quantity<0){
            Error("الرجاء إدخال كمية");
                return 0 ;
        }
                if(quantity > (productMaxCount / unit_quantity)){
                    Error(" الكمية المتاحة لهذا المنتج : "  +parseFloat(productMaxCount / unit_quantity).toFixed(3)+" "+unitName," الكمية غير متاحة");
                return 0 ;
        }

        $.post(app_url+"/dashboard/sale_bills/post", {
            product_id: product,
            product_price:price,
            quantity:quantity,
            quantity_price:totalItemPrice,
            unit_id:unit,
            company_id:company_id,
            sale_bill_number:sale_bill_number,
            outer_client_id:$('#outer_client_id').val(),
            date:$('#date').val(),
            time:$('#time').val(),
            "_token": token,
        },
        function (data) {
          if(data.status){
            $('#product_id option:selected').removeData('max');
		    $("#product_id").val("").trigger( "change" ); 
		    $("#unit_id").val("").trigger( "change" ); 
            $('.available').hide();
            $('#product_price').val(0);
            $('#quantity').val(1);
            $('#quantity_price').val(0);
            $('#product_unit_quantity').val(0);
            $('#cancel').attr('disabled',false);
            $('#viewInvoice').attr('disabled',false);
            $('.invoice-padding-extra').show();
            $('#payment_method').attr('disabled',false);
            $('.invoice-spacing').show();
            $('.unti').prop('disabled',false);


            CheckPaymentForClent();
          }

        });
    
        if(is_product==1){
             for(i=1;i<=count;i++){
                if( $('#productName_'+i+'').text() == productName && $('#unit_'+i+'').val() == unit){

                            var createRow = 1 ;
                            var quantityRow = parseFloat($('#quantity_'+i+'').val());
                            var quantity = parseFloat(quantityRow +quantity);
                            $('#quantity_'+i).val(quantity);
                            calculateTotal();
                }
             } 
        }else{
            var createRow = 0 ;
        }

        if(createRow!=1){
        var htmlRows = '';
        htmlRows +=` <div class="mb-3 invItem" data-repeater-list="group-a" id="row-`+count+`">
                      <div class="repeater-wrapper pt-0 pt-md-4" data-repeater-item="">
                        <div class="d-flex border rounded position-relative pe-0">
                          <div class="row w-100 p-3">

                            <div class="col-md-2 col-12 mb-md-0 mb-3">
                              <p class="mb-2 repeater-title">المنتج</p>
                              <div id="productName_`+count+`">`+productName+`</div><input type="hidden" name="product[]" id="product_`+count+`"  value="`+product+`"  class="form-control product"  autocomplete="off" required>
                            </div>

                            <div class="col-md-2 col-12 mb-md-0 mb-3">
                              <p class="mb-2 repeater-title">الكمية</p>
                              <input type="number" name="quantity[]" id="quantity_`+count+`" class="form-control quantity"  value="`+quantity+`" product="`+product+`" max="`+productMaxCount+`" min="0" step="any"  >                              
                            </div>

                            <div class="col-md-2 col-12 mb-md-0 mb-3">
                            <p class="mb-2 repeater-title">الوحدة</p>
                            `+unitName+`<input type="hidden" name="unit[]" id="unit_`+count+`"  value="`+unit+`"  class="form-control unit"  autocomplete="off" required>
                            <input type="hidden" name="product_unit_quantity[]" id="product_unit_quantity_`+count+`"  value="`+unit_quantity+`"  class="form-control product_unit_quantity"  autocomplete="off" required>
                            </div>

                            <div class="col-md-3 col-12 mb-md-0 mb-3">
                              <p class="mb-2 repeater-title">السعر</p>
                              <input type="number"  step="any" name="price[]" id="price_`+count+`"  value="`+price+`" product="`+product+`" class="form-control price"  autocomplete="off" required>
                            </div>

                            <div class="col-md-3 col-12 mb-md-0 mb-3">
                              <p class="mb-2 repeater-title">الإجمالي</p>
                              <input type="text" name="total[]" id="total_`+count+`" class="form-control total" value=`+quantity*price+` readonly required>
                            </div>

                        </div>

                        <div class="d-flex flex-column align-items-center justify-content-between border-start p-2">
                        <a class="delete" data-unit="`+unit+`" data-product="`+product+`" data-div="`+count+`" data-invoice="`+sale_bill_number+`" id="removeRows" ><i class="la la-trash" style="font-size:20px;color:red" ></i></a>                        </div>
                      </div>
                      </div>
                    </div>
                  </div>
                  `;

		$('#productsTable').append(htmlRows);
        }
        calculateTotal();

     });


     $(document).on('click', '#removeRows', function(){

    var divId = $(this).data('div');
    var unit_id = $(this).data('unit');

    $('#row-'+divId).remove();


    calculateTotal();

    $.post(app_url+"/dashboard/sale_bills/element/delete", {
        product_id: $(this).data('product'),
        invoice_number: $(this).data('invoice'),
        status:status,
        unit_id:unit_id,
        "_token": token
    }, function (data) {
        if(data.status){
            $('#product_id option:selected').removeData('max');
            $("#product_id").val("").trigger( "change" ); 
            $('.available').hide();
            
            checkInvoiceItem();
        }
        
    });

    calculateTotal();


});	

     $(document).on('keyup', "[id^=quantity_]", function(){
        var product_id = $(this).attr('product');
        var max = parseFloat($(this).attr('max'));
        var id = $(this).attr('id');
		id = id.replace("quantity_",'');
        var quantity = $('#quantity_'+id).val();
		var price = $('#price_'+id).val();
        var unit_id = $('#unit_'+id).val();
        // 100> 20 
        // if(max >= quantity){
            calculateTotal();
                // }else{
                    
                // }
        updatePriceAndQuantity(product_id,price,quantity,unit_id,id);
        
	});	

    $(document).on('keyup', "[id^=price_]", function(){
        calculateTotal();
        var product_id = $(this).attr('product');
        var id = $(this).attr('id');
		id = id.replace("price_",'');
		var quantity = $('#quantity_'+id).val();
		var price = $('#price_'+id).val();
        var unit_id = $('#unit_'+id).val();

        if(status=='open'){
        updatePriceAndQuantity(product_id,price,quantity,unit_id,id);
        }

	});	

$('#store_id').on('change',function(){
    getProducts();
});


function getProducts(){
    var store_id = $('#store_id').val();

    $.post(app_url+"/dashboard/sale_bills/inv/product/get", {
        store: store_id,
        "_token": token
    }, function (data) {

        $('#product_id').empty();
        $('#product_id').append('<option value="">اختر منتج</option>');
        $.each(data.products, function (key, value) {
            if(value.code_universal){var barcode = ' - '+value.code_universal;}else{var barcode = '';}
            $('#product_id').append('<option data-product="'+value.is_product+'" data-name="'+value.product_name+'" value="'+value.id+'" >'+value.product_name+barcode+'</option>');
        });
        // $('#product_id').select2();
    });
}

function calculateTotal(){
	var totalAmount = 0; 
	var totalQuantity=0;
    var tax = parseFloat($("#tax").text());
    var totalAfterTax=0;
    var finalTotal=0;
    var discount = parseFloat($("#discount").text());
    var extra = parseFloat($("#extra").text());
    var disType = $("#disType").text();
    var exType = $("#exType").text();
    if(!discount){discount=0;}
    if(!extra){extra=0;}
    $("[id^='price_']").each(function() {
		var id = $(this).attr('id');
		id = id.replace("price_",'');
		var price = $('#price_'+id).val();
		var quantity  = $('#quantity_'+id).val();
		if(!quantity) {
			quantity = 1;
		}     
        var total = price*quantity;
		$('#total_'+id).val(parseFloat(total).toFixed(2));   
        totalAmount += total;		

	});
    if (/%/.test(disType)) {
        discount = totalAmount * discount /100;
    }else{

        discount = discount;

    }

    if (/%/.test(exType)) {

        extra = totalAmount * extra /100;
    }else{
        
        extra = extra ;
    }






    $('#subtotal').text(formatMoney(totalAmount));	
    var totalAfterTax = totalAmount + (totalAmount * tax/100);
    $('#totalAfterTax').text(formatMoney(totalAfterTax));
    finalTotal = totalAfterTax + extra - discount ;
    $('#finalTotal').text(formatMoney(finalTotal)); 
    $('#payAmountCash').val(Number(finalTotal.toFixed(2))); 
    $('#payAmountBank').val(Number(finalTotal.toFixed(2))); 

    
    


    if(status == 'open'){
    $.post(app_url+"/dashboard/sale_bills/total/update", {
        final_total: finalTotal,
        sale_bill_number: sale_bill_number,
        "_token": token
    }, function (data) {
        
    });
    }


    
}
    
     $('#outer_client_id').on('change', function () {
        var date = $('#date').val();
        var  time = $('#time').val();
        let outer_client_id = $(this).val();
        
            $('.outer_client_details').fadeIn(200);
            $.post(app_url+"/dashboard/sale_bills/getOuterClientDetails", {
                outer_client_id: outer_client_id,
                sale_bill_number:sale_bill_number,
                date:date,
                time:time,
                "_token": token
            }, function (data) {
                if(data.status){
                $('#category').val(data.category);
                if(data.balance_before < 0){
                    debit =" لة " ;
               }else{
                   debit =" علية " ;
               }
               $('#balance_before').val(debit+Math.abs(data.balance_before));
                $('#client_national').val(data.client_national);
                $('#cancel').attr('disabled',false);
                if(data.category=='قطاعى'){
                    $('#sector').prop('checked', true);
                    setItemPrice();
                }else if(data.category=='جملة'){
                    $('#wholesale').prop('checked', true);
                    setItemPrice();

                }
            }else if (outer_client_id == "") {
                $('.outer_client_details').fadeOut(200);
                $('#sector').prop('checked', true);
            }else{
                $('#NonPayment_method').show();
                $('#payment_method').hide();
                $('.outer_client_details').hide();
            }
            });

            CheckPaymentForClent();


    });

    $('#product_id').on('change', function () {
        $('.available').hide();
        $('#priceType').hide();
        setItemPrice();
    });

    $('#wholesale').on('click', function () {
        let product_id = $('#product_id').val();
        var unit_quantity = $('#product_unit_quantity').val();
        $.post(app_url+"/dashboard/sale_bills/get", {
            product_id: product_id,
            "_token": token
        }, function (data) {
            $('input#product_price').val(data.wholesale_price*unit_quantity);
            let quantity = $('#quantity').val();
            let quantity_price = quantity * data.wholesale_price*unit_quantity;
            $('#quantity_price').val(quantity_price);
        });
    });
    
    $('#sector').on('click', function () {
        let product_id = $('#product_id').val();
        var unit_quantity = $('#product_unit_quantity').val();
        var quantity = $('#quantity').val();

        $.post(app_url+"/dashboard/sale_bills/get", {
            product_id: product_id,
            "_token": token
        }, function (data) {
            $('input#product_price').val(data.sector_price * unit_quantity);
            let quantity_price = quantity * data.sector_price * unit_quantity;
            $('#quantity_price').val(quantity_price);
        });
    });

    function setItemPrice(){

        let sale_bill_number = $('#sale_bill_number').val();
        var product_id = $('#product_id').val();
        var unit_quantity = 0;
        var quantity = $('#quantity').val();
        if(product_id){
        $.post(app_url+"/dashboard/sale_bills/get", {
            product_id: product_id,
            sale_bill_number: sale_bill_number,
            "_token": token
        }, function (data) {

            unit_quantity = data.unit_quantity;
            $('#product_unit_quantity').val(unit_quantity);

                if($('#sector').is(':checked')){

            $('input#product_price').val(data.sector_price*unit_quantity);
             $('#quantity_price').val(quantity*data.sector_price*unit_quantity);

                }else if($('#wholesale').is(':checked')){

            $('input#product_price').val(data.wholesale_price*unit_quantity);
            $('#quantity_price').val(quantity*data.wholesale_price*unit_quantity);

                }

            $('input#quantity').attr('max', data.first_balance*unit_quantity);
            // $('#product_id option:selected').attr('data-max', data.first_balance);
            if(data.first_balance || data.first_balance==0){
                if(data.is_product==1){
                $('.available').show();
                $('#priceType').show();
                $('.unti').prop('disabled',false);

            }else{
                $('.unti').prop('disabled', true);
            }
            }else{
                // $('.available').hide();
                $('#quantity_price').val(0);
                $('#priceType').hide();
            }

            if(data.is_product==1){$('.available').html('الكمية المتاحة : ' + (data.first_balance) +' '+ data.unit_name);}
            $('#unit_id option[value='+data.unit+']').prop('selected',true);  
            $('#product_unit_quantity').val(data.unit_quantity); 



        }); 
        
        }
    }

    $('#product_price').on('keyup', function () {
        var productPrice = $('#product_price').val();
        var quantity = $('#quantity').val();
        var unit_quantity = $('#product_unit_quantity').val();
        $('#quantity_price').val(quantity*productPrice);
    });
    $('#quantity').on('keyup', function () {
        var productPrice = $('#product_price').val();
        var quantity = $('#quantity').val();
        var unit_quantity = $('#product_unit_quantity').val();
        $('#quantity_price').val(quantity*productPrice);
    });

    $('#unit_id').on('change', function () {
        let product_id = $('#product_id').val();
        var quantity = $('#quantity').val();
        var unit_id = $('#unit_id').val();
        var productPrice = 0;

        if(product_id !==''){
        $.post(app_url+"/dashboard/sale_bills/get/UnitPrice", {
            product_id: product_id,
            unit_id: unit_id,
            "_token": token
        }, function (data) {

            if($('#sector').is(':checked')){productPrice = data.product_sector_price;}else if($('#wholesale').is(':checked')){productPrice = data.product_wholesale_price;}
           
            $('#product_unit_quantity').val(data.quantity);
            $('#product_price').val(productPrice *data.quantity);
            $('#quantity_price').val(quantity * (productPrice * data.quantity));
            $('input#quantity').attr('max',data.first_balance / data.quantity);

        });
         }
    });

    // discount 
    $('#discount_type').on('change', function () {
        var discount_type =  $('#discount_type').val();
        var discount_value = Number($('#discount_value').val());
 
         $.post(app_url+"/dashboard/sale_bills/discount",
         {
             "_token": token,
             sale_bill_number: sale_bill_number,
             discount_type: discount_type,
             discount_value: discount_value
         },
         function (data) {
             if(data.status){
                 $('#discount').text(data.value);
                $('#disType').text(data.disType); 
                calculateTotal();

             }   
         });
     });

    $('#discount_value').on('keyup', function () {
       var discount_type =  $('#discount_type').val();
       var discount_value =  $('#discount_value').val();

        $.post(app_url+"/dashboard/sale_bills/discount",
        {
            "_token": token,
            sale_bill_number: sale_bill_number,
            discount_type: discount_type,
            discount_value: discount_value
        },
        function (data) {
            if(data.status){
                $('#discount').text(data.value);
                $('#disType').text(data.disType); 
                calculateTotal();

            }   
        });
    });

    //end discount
// extra
    $('#extra_value').on('keyup', function () {
        var extra_type =  $('#extra_type').val();
        var extra_value =  $('#extra_value').val();

    $.post(app_url+"/dashboard/sale_bills/extra",
    {
        "_token": token,
        sale_bill_number: sale_bill_number,
        extra_type: extra_type,
        extra_value: extra_value
    },
    function (data) {
        if(data.status){
            $('#extra').text(data.value);
            $('#exType').text(data.exType); 
            calculateTotal();

        }
    });
});

    $('#extra_type').on('change', function () {
        var extra_type =  $('#extra_type').val();
        var extra_value =  $('#extra_value').val();

    $.post(app_url+"/dashboard/sale_bills/extra",
    {
        "_token": token,
        sale_bill_number: sale_bill_number,
        extra_type: extra_type,
        extra_value: extra_value
    },
    function (data) {
        if(data.status){
            $('#extra').text(data.value);
            $('#exType').text(data.exType); 
            calculateTotal();
        }
    });
});
    // end extra

   function updatePriceAndQuantity(product_id,price,quantity,unit_id,id){

        $.post(app_url+"/dashboard/sale_bills/updatePriceAndQuuantity", {
            product_id: product_id,
            sale_bill_number:sale_bill_number,
            company_id:company_id,
            price:price,
            quantity:quantity,
            status:status,
            unit_id:unit_id,
            "_token": token
        }, function (data) {

            if(data.status){

            return true;

            }else{

                $('#quantity_'+id).val(data.last_quantity); 
                $('#quantity_'+id).attr('max',data.quantity);
                var unit_quantity = $('#product_unit_quantity_'+id).val();

                toastr.error(" الكمية المتاحة لهذا المنتج : "+data.quantity / unit_quantity+" "+data.unit_name+" فقط "," الكمية غير متاحة",{positionClass: "toast-top-right",
                tapToDismiss: !1,
                timeOut: 2e3,
                rtl: $("html").attr("data-textdirection")
                });

                calculateTotal();
                // updatePriceAndQuantity(product_id,price,quantity,unit_id,id);
                
            }
       
        });

    }
    function checkInvoiceItem(){

                if($('.invItem').text()==''){
               // $('#cancel').attr('disabled',true);
                $('#saveAll').attr('disabled',true);
                $('#saveAllWithOutPrint').attr('disabled',true);
                $('.invoice-padding-extra').hide();
                $('#payCash').hide();
                $('#payment_method').attr('disabled',true);
                $('#submitPay').hide();
                $('#viewInvoice').attr('disabled',true);
                $('.invoice-spacing').hide();

                if(status=='done'){
                $.post(app_url+"/dashboard/sale_bills/checkInvoice", {
                    '_token': token,
                    sale_bill_number: sale_bill_number,
                }, function (data) {
                    if(data.status){  
                        Error(data.message);
                    }
                });  
            }

            }else{
                    CheckPaymentForClent();
            }
    }
    $('#payment_method').on('change', function () {
        var paymentMethod = $('#payment_method').val() ;
        if(paymentMethod=='cash'){
            $('#payCash').show();
            $('#safes').show();
            $('#banks').hide();
            $('#submitPay').show();
            $('#payBank').hide();
        }else if(paymentMethod=='bank'){
            $('#payCash').hide();
            $('#safes').hide();
            $('#banks').show();
            $('#payBank').show();
            $('#submitPay').show();
        }else{
            $('#payCash').hide();
            $('#safes').hide();
            $('#banks').hide();
            $('#payBank').hide();
            $('#submitPay').hide(); 
        }
    });

    $("#payForm").on('submit',(function(e) {
        e.preventDefault();
        var outer_client_id = $('#outer_client_id').val();
        var date = $('#date').val();
        var  time = $('#time').val();
        var payment_method = $('#payment_method').val();
        var bank_id = $('#bank_id').val();
        var safe_id = $('#safe_id').val();
        var bank_check_number = $('#bank_check_number').val();
        var error = 1;
        if(payment_method=='cash'){
            var amount = $('#payAmountCash').val();
            
            if(safe_id==''){
                Error('الرجاء اختيار الخزنة');
                 error = 0;
            }
            if(amount==''){
                Error('الرجاء إدخال قيمة الدفع');
                error = 0;

            }
        }else{
            var amount = $('#payAmountBank').val();
            if(bank_id==''){
                Error('الرجاء اختيار البنك');
                error = 0;

            }
            if(amount==''){
                Error('الرجاء إدخال قيمة الدفع');
                error = 0;

            }
            // if(bank_check_number==''){
            //     Error('الرجاء إدخال رقم عملية الدفع');
            //     error = 0;
            // }
        }
        var cash_number = $('#cash_number').val();
        var notes = $('#bank_notes').val();
        if(error==1){
        $.post(app_url+"/dashboard/sale_bills/pay/store/cash", {
            outer_client_id: outer_client_id,
            company_id: company_id,
            bill_id: sale_bill_number,
            date: date,
            time: time,
            cash_number: cash_number,
            amount: amount,
            safe_id: safe_id,
            bank_id: bank_id,
            bank_check_number: bank_check_number,
            notes: notes,
            payment_method: payment_method,
            "_token": token
        }, function (data) {
            if(data.status){
                CheckPaymentForClent();
                toastr.success("",data.message,{
                    positionClass: "toast-top-right",
                    tapToDismiss: !1,
                    timeOut: 2e3,
                    rtl: $("html").attr("data-textdirection")
                    }); 
                    if(data.safe){
                        var safe = data.safe;
                    }else{
                        var safe = data.bank;

                    }
                    $('#payCash').hide();
                     $('#payBank').hide();
                    $('#submitPay').hide();
                    $('#cashPaied').show();
                    $('#pay').show();
                    $('#pay').append('<div class="opreation" id="'+data.cash_number+'"><td> '+data.amount+'</td>'+'<td> ('+safe+') </td><td>'+'<button type="button" payment_method="'+data.method+'" id="deleteCash" cash_id='+data.cash_number+' class="btn delete_pay"> <i style="font-size:20px ; color:red " class="la la-trash"></i> </button>'+'</td> </div>');
                    $("#payment_method").val("").trigger( "change" ); 
                    // $('#outer_client_id').attr('disabled',true);
                    

            }else{
                toastr.error("",data.message,{
                    positionClass: "toast-top-right",
                    tapToDismiss: !1,
                    timeOut: 2e3,
                    rtl: $("html").attr("data-textdirection")
                    }); 

            }

        });
    }

           }));

     $(document).on('click', '#deleteCash', function(){

                let payment_method = $(this).attr('payment_method');
                let cash_id = $(this).attr('cash_id');
                $.post(app_url+"/dashboard/sale_bills/pay-delete", {
                    '_token': token,
                    payment_method: payment_method,
                    cash_id: cash_id,
                }, function (data) {
                    if(data.status){
                        toastr.warning ("",data.message,{
                            positionClass: "toast-top-right",
                            tapToDismiss: !1,
                            timeOut: 2e3,
                            rtl: $("html").attr("data-textdirection")
                            }); 
                             $('#' + cash_id).remove();
                             if($('.opreation').text()==''){
                                $('#cashPaied').hide();
                                 $('#outer_client_id').attr('disabled',false);
                             }
                                
                             
                            
                    }
                

                });
                
                CheckPaymentForClent();
               
            });
          
        $('.submit').on('click', function(e){
        e.preventDefault();
        var tax = $('#tax').text();
        var subTotal = $('#subtotal').text();
        subTotal=subTotal.replace(/\,/g,'');
        var total = $('#finalTotal').text();
        total=total.replace(/\,/g,'');
        var arrProduct = $('input[name="product[]"]').map(function () {return this.value; $(this).val()}).get();
        var arrPrice = $('input[name="price[]"]').map(function () {return this.value; $(this).val()}).get();
        var arrQuantity = $('input[name="quantity[]"]').map(function () {return this.value; $(this).val()}).get();
        var arrUnit = $('input[name="unit[]"]').map(function () {return this.value; $(this).val()}).get();
        var productUnitQuantity = $('input[name="product_unit_quantity[]"]').map(function () {return this.value; $(this).val()}).get();
        var outer_client_id = $('#outer_client_id').val();
        var buttonType = this.id ;

        // if( checkInvoiceElment() == 1){
        //     return 0 ;
        // }
        $.post(app_url+"/dashboard/sale_bills/saveAll", {
            sale_bill_number: sale_bill_number,
            payment_method: "cash",
            total: total,
            tax:tax,
            subtotal:subTotal,
            status:status,
            price:arrPrice,
            product:arrProduct,
            quantity:arrQuantity,
            unit:arrUnit,
            product_unit_quantity:productUnitQuantity,
            outer_client_id: outer_client_id,
            "_token": token
        }, function (data) {
            if(status=='open' || status=='done'){
            if(buttonType == 'saveAll'){
            var url = app_url+"/dashboard/sale_bills/print/:id";
            url = url.replace(':id', sale_bill_number);
            window.open(url,'_blank');
            }
            $(location).attr('href', app_url+"/dashboard/sale_bills/redirect");

            }else{
                $(location).attr('href', app_url+"/dashboard/sale_bills/index");

            }
        });
        
     });

    function CheckPaymentForClent(){
        var outer_client_id = $('#outer_client_id').val();

        if(outer_client_id  && $('.invItem').text()!==''){
            $('#saveAll').attr('disabled',false);
            $('#saveAllWithOutPrint').attr('disabled',false);

        }else if(!outer_client_id){
        $.post(app_url+"/dashboard/sale_bills/check_payment", {
            sale_bill_number: sale_bill_number,
            "_token": token

        }, function (data) {

            if(data.status){
                $('#saveAll').attr('disabled',false);
                $('#saveAllWithOutPrint').attr('disabled',false);
                 
            }else{
                $('#saveAll').attr('disabled',true);
                $('#saveAllWithOutPrint').attr('disabled',true);

            }

        });

    }


    }

    function Error(message,subTitle){
        toastr.error(subTitle,message,{
            positionClass: "toast-top-right",
            tapToDismiss: !1,
            timeOut: 2e3,
            rtl: $("html").attr("data-textdirection")
            }); 
    }
    
        function checkProduct(product){ 

            $.ajax({
                type: "POST",
                url: app_url + "/dashboard/sale_bills/get",
                data: {
                    product_id: product,
                    sale_bill_number: sale_bill_number,
                    "_token": token
                },
                async: false, 
                success: function(data) {
                    max = data.first_balance;
                },
                error: function() {
                }
            });
        
            return max;
        



         }


         function checkInvoiceElment(){
            $.ajax({
                type: "POST",
                url: app_url + "/dashboard/sale_bills/check_sale_bill_elment",
                data: {
                    sale_bill_number: sale_bill_number,
                    "_token": token
                },
                async: false, 
                success: function(data) {
                    if(data.error.status){
                        error = 0 ;
                    } else
                    {
                        error = 1 ;
                    }
                },
                error: function() {
                }
            });

            return error ;
        }
    

});