
//On Enter Move the cursor to desigtation Id
function shift_cursor(kevent,target){

    if(kevent.keyCode==13){
		$("#"+target).focus();
    }
	
}
/*Email validation code*/
function validateEmail(sEmail) {
    var filter = /^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,9}|[0-9]{1,3})(\]?)$/;
    if (filter.test(sEmail)) {
        return true;
    }
    else {
        return false;
    }
}

function uncheck_allow_tot_advance(){
  //verify is checked ?
  if($("#allow_tot_advance").is(':checked')){
    $("#click_to_uncheck").trigger("click");
  }
}

$("#pay_all").on("click",function(){
	save(print=true,pay_all=true);
});

// Prevent multiple save operations by tracking save state
var save_in_progress = false;

function save(print=false,pay_all=false){

	// Prevent double submission
	if(save_in_progress) {
		console.log("Save already in progress, ignoring duplicate call");
		return false;
	}

	var base_url=$("#base_url").val();
    
    if($(".items_table tr").length==1){
    	toastr["warning"]("Empty Sales List!!");
		return;
    }

	//RETRIVE ALL DYNAMIC HTML VALUES
    var tot_qty=$(".tot_qty").text();
    var tot_amt=$(".tot_amt").text();
    var tot_disc=$(".tot_disc").text();
    var tot_grand=$(".tot_grand").text();

    var paid_amt=(pay_all) ? tot_grand : $(".sales_div_tot_paid").text();
    var balance=(pay_all) ? 0 : parseFloat($(".sales_div_tot_balance").text());

    var customer_id=$("#customer_id").val();

    /* walk_in_customer_name defined in pos.php */
    if($('option:selected', "#customer_id").attr('data-delete_bit')==1 && balance!=0){
    	toastr["warning"]("Walk-in Customer Should Pay Complete Amount!!");
		return;
    }
    
    if(document.getElementById("sales_id")){
    	var command = 'update';
    }
    else{
    	var command = 'save';
    }
    
    // Set save in progress
    save_in_progress = true;
    
    var this_btn='make_sale';
    
    $("#"+this_btn).attr('disabled',true);  //Enable Save or Update button
    var data = new FormData($('#pos-form')[0]);//form name
    /*Check XSS Code*/
    if(!xss_validation(data)){ 
    	save_in_progress = false;
    	$("#"+this_btn).attr('disabled',false);
    	return false; 
    }
    
    $(".box").append('<div class="overlay"><i class="fa fa-refresh fa-spin"></i></div>');
    $.ajax({
        type: 'POST',
        url: base_url+'pos/pos_save_update?command='+command+'&tot_qty='+tot_qty+'&tot_amt='+tot_amt+'&tot_disc='+tot_disc+'&tot_grand='+tot_grand+"&paid_amt="+paid_amt+'&balance='+balance+"&pay_all="+pay_all,
        data: data,
        cache: false,
        contentType: false,
        processData: false,
        success: function(result){
            result=result.split("<<<###>>>");
            
            if(result[0]=="success")
            {
                toastr['success']("Record Saved Successfully!!");
                success.currentTime = 0;
                success.play();
                var warehouse_id=$("#warehouse_id").val();
                var print_done=true;
                if(print){
                    var print_done =window.open(base_url+"pos/print_invoice_pos/"+result[1], "_blank", "scrollbars=1,resizable=1,height=300,width=450");
                }
                if(print_done){
                    if(command=='update'){
                        window.location=base_url+"sales";		
                    }
                    else{
                        $(".items_table > tbody").empty();
                        $(".discount_input").val(0);

                        /**
                         * Note:
                         * Uncheck the advance checkbox
                         * Add this code before hiding modal
                         */
                        uncheck_allow_tot_advance();
                        
                        $('#multiple-payments-modal').modal('hide');
                        var rc=$("#payment_row_count").val();
                        while(rc>1){
                            remove_row(rc);
                            rc--;
                        }
                        $("#pos-form")[0].reset();

                        $("#customer_id").val(customer_id).select2();

                        $("#customer_id").find(':selected').attr('data-tot_advance',to_Fixed(result[4])).trigger('change');

                        $("#search_it").val('');

                        $("#search_it").val('');
                        
                        /*if warehouse enabled*/
                        if(warehouse_module){
                            $("#warehouse_id").val(warehouse_id).select2();	
                        }

                        final_total();
                        get_details(null,true);
                        hold_invoice_list();
                        get_coupon_details();
                    }
                }
                $("#init_code").val(result[2]);
                $("#count_id").val(result[3]);
            }
            else if(result[0]=="failed")
            {
               toastr['error']("Sorry! Failed to save Record.Try again");
            }
            else
            {
                alert(result);
            }
            
            // Reset save state and enable buttons
            save_in_progress = false;
            $("#"+this_btn).attr('disabled',false);  //Enable Save or Update button
            $(".overlay").remove();
       },
       error: function(){
           // Reset save state and enable buttons on error
           save_in_progress = false;
           $("#"+this_btn).attr('disabled',false);
           $(".overlay").remove();
           toastr['error']("An error occurred while saving. Please try again.");
       }
   });
}



/* *********************** HOLD INVOICE START****************************/
$('#hold_invoice').on("click",function (e) {

	//table should not be empty
	if($(".items_table tr").length==1){
    	toastr["error"]("Please Select Items from List!!");
    	failed.currentTime = 0;
		failed.play();
		return;
    }

	swal({
		title: "Hold Invoice ? Same Reference will replace the old list if exist!!",icon: "warning",buttons: true,dangerMode: true,
		content: {
			element: "input",attributes: 
			{
				placeholder: "Please Enter Reference Number!",
				type: "text",
				
				inputAttributes: {
				    maxlength: '5'
				  }
			},},
		}).then(name => {
			//If input box blank Throw Error
			if (!name){ throw null; return false; }
			var reference_id = name;
			/* ********************************************************** */
			var base_url=$("#base_url").val();
    
			//RETRIVE ALL DYNAMIC HTML VALUES
		    var tot_qty=$(".tot_qty").text();
		    var tot_amt=$(".tot_amt").text();
		    var tot_disc=$(".tot_disc").text();
		    var tot_grand=$(".tot_grand").text();
		    var hidden_rowcount=$("#hidden_rowcount").val();

		    var this_id=this.id;//id=save or id=update

				e.preventDefault();
				data = new FormData($('#pos-form')[0]);//form name
				/*Check XSS Code*/
				if(!xss_validation(data)){ return false; }
				
				$(".box").append('<div class="overlay"><i class="fa fa-refresh fa-spin"></i></div>');
				$("#"+this_id).attr('disabled',true);  //Enable Save or Update button				
				$.ajax({
					type: 'POST',
					url: base_url+'pos/hold_invoice?command='+this_id+'&tot_qty='+tot_qty+'&tot_amt='+tot_amt+'&tot_disc='+tot_disc+'&tot_grand='+tot_grand+"&reference_id="+reference_id,
					data: data,
					cache: false,
					contentType: false,
					processData: false,
					success: function(result){
						//alert(result);return;
						$("#hidden_invoice_id").val('');
						result=result.split("<<<###>>>");
						
							if(result[0]=="success")
							{
								$('#pos-form-tbody').html('');
								//CALCULATE FINAL TOTAL AND OTHER OPERATIONS
		    					final_total();

								hold_invoice_list();
								success.currentTime = 0;
								success.play();
							}
							else if(result[0]=="failed")
							{
							   toastr['error']("Sorry! Failed to save Record.Try again");
							}
							else
							{
								alert(result);
							}
						
						$("#"+this_id).attr('disabled',false);  //Enable Save or Update button
						$(".overlay").remove();
				   }
			   });
			/* ********************************************************** */

		}) //name end
	.catch(err => {
	    toastr['error']("Failed!! Invoice Not Saved! <br/>Please Enter Reference Number");
	    failed.currentTime = 0;
		failed.play();
	});//swal end

}); //hold_invoice end

function hold_invoice_list(){
	var base_url=$("#base_url").val();
  $.post(base_url+"pos/hold_invoice_list",{},function(result){
  	//alert(result);
  	var data = jQuery.parseJSON(result)
    $("#hold_invoice_list").html('').html(data['result']);
    $(".hold_invoice_list_count").html('').html(data['tot_count']);
  });
}
function hold_invoice_delete(invoice_id){
	swal({ title: "Are you sure?",icon: "warning",buttons: true,dangerMode: true,}).then((sure) => {
	if(sure) {//confirmation start
	var base_url=$("#base_url").val();
  $.post(base_url+"pos/hold_invoice_delete/"+invoice_id,{},function(result){
  	result=result;
    if(result=='success'){
    	toastr["success"]("Success! Invoice Deleted!!");
	    success.currentTime = 0;
		success.play();
	    hold_invoice_list();
    }
    else{
    	toastr['error']("Failed to Delete Invoice! Try again!!");
    	failed.currentTime = 0;
		failed.play();
    }
  });
  } //confirmation sure
		}); //confirmation end
}

function hold_invoice_edit(id){

	swal({ title: "Are you sure?",icon: "warning",buttons: true,dangerMode: true,}).then((sure) => {
	if(sure) {//confirmation start
	var base_url=$("#base_url").val();

	$(".box").append('<div class="overlay"><i class="fa fa-refresh fa-spin"></i></div>');
	$.post(base_url+"pos/hold_invoice_edit",{hold_id:id},function(result){

    		console.log(result);

      result=result.split("<<<###>>>");
      $('#pos-form-tbody').html('').append(result[0]);
      $('#discount_input').val(result[1]);
      $('#discount_type').val(result[2]);
      /*if(store_module){
        $('#store_id').val(result[4]).select2();
      }
      else{*/
        $('#store_id').val(result[4]);
      /*}*/
      console.log("warehouse = "+result[5]);
      if(warehouse_module){
        $('#warehouse_id').val(result[5]).select2();
      }
      else{
        $('#warehouse_id').val(result[5]);
      }

      //$('#customer_id').val(result[3]).select2();
      //$("#customer_id").trigger("change");
      
      //$('#temp_customer_id').val(result[3]);

      autoLoadFirstCustomer(result[3]);
      //$('#customer_id').val(result[3]).select2();
      $("#hidden_invoice_id").val(result[7]);
      $("#hidden_rowcount").val(parseInt($(".items_table tr").length)-1);
      final_total();
      get_details(null,true);
      $(".overlay").remove();
      
      if(result[5]==1){
        $( "#binvoice" ).prop( "checked", true );
        $('#binvoice').parent('div').addClass('checked');
      }
    	});

				
		} //confirmation sure
	}); //confirmation end
}
/* *********************** HOLD INVOICE END****************************/
/* *********************** ORDER INVOICE START****************************/
function get_id_value(id){
	return $("#"+id).val();
}
$('#collect_customer_info').on("click",function (e) {
	
	//table should not be empty
	if($(".items_table tr").length==1){
    	toastr["error"]("Please Select Items from List!!");
    	failed.currentTime = 0;
		failed.play();
		return;
    }
    if(get_id_value('customer_id')==1){
    	//$('#customer-modal').modal('toggle');
    	toastr["error"]("Please Select Customer!!");
    	failed.currentTime = 0;
		failed.play();
    	return false;
    }
    else{
    	$('#delivery-info').modal('toggle');
    }
}); //hold_invoice end
$('.show_payments_modal').on("click",function (e) {
	
	//table should not be empty
	if($(".items_table tr").length==1){
    	toastr["error"]("Please Select Items from List!!");
    	failed.currentTime = 0;
		failed.play();
		return;
    }
    else{
    	adjust_payments();
    	$("#add_payment_row,#payment_type_1").parent().show();
    	$("#amount_1").parent().parent().removeClass('col-md-12').addClass('col-md-6');
    	$('#multiple-payments-modal').modal('toggle');
    }
}); 

$('#show_cash_modal').on("click",function (e) {
	//table should not be empty
	if($(".items_table tr").length==1){
    	toastr["error"]("Please Select Items from List!!");
    	failed.currentTime = 0;
		failed.play();
		return;
    }
    else{
    	adjust_payments();
    	$("#add_payment_row,#payment_type_1").parent().hide();
    	$("#amount_1").focus();
    	$("#amount_1").parent().parent().removeClass('col-md-6').addClass('col-md-12');
    	$('#multiple-payments-modal').modal('toggle');
    }
});

$('#add_payment_row').on("click",function (e) {
	
	var base_url=$("#base_url").val();
	//table should not be empty
	if($(".items_table tr").length==1){
    	toastr["error"]("Please Select Items from List!!");
    	failed.currentTime = 0;
		failed.play();
		return;
    }
    /*if(get_id_value('customer_id')==1){
    	//$('#customer-modal').modal('toggle');
    	toastr["error"]("Please Select Customer!!");
    	failed.currentTime = 0;
failed.play();
    	return false;
    }*/
    else{
    	/*BUTTON LOAD AND DISABLE START*/
    	var this_id=this.id;
    	var this_val=$(this).html();
    	$("#"+this_id).html('<i class="fa fa-spinner fa-spin"></i> Please Wait..');
    	$("#"+this_id).attr('disabled',true);  
    	/*BUTTON LOAD AND DISABLE END*/

    	var payment_row_count=get_id_value("payment_row_count");
    	$.post(base_url+"pos/add_payment_row",{payment_row_count:payment_row_count},function(result){
    		$('.payments_div').parent().append(result);
    		$("#payment_row_count").val(parseInt(payment_row_count)+1);

    		/*BUTTON LOAD AND DISABLE START*/
    		$("#"+this_id).html(this_val);
    		$("#"+this_id).attr('disabled',false); 
    		/*BUTTON LOAD AND DISABLE END*/    	
    		failed.currentTime = 0;
			failed.play();
    		adjust_payments();
    	});
    }
}); //hold_invoice end
function remove_row(id){
	$(".payments_div_"+id).html('');
	failed.currentTime = 0;
	failed.play();
	adjust_payments();
}
function calculate_payments(){
	adjust_payments();
}

//LEFT SIDE: FINAL TOTAL - Calculate payments for modal
function adjust_payments(){
  var total=0;
  var item_qty=parseFloat(0);
  var rowcount=$("#hidden_rowcount").val();
  var discount_input=$("#discount_input").val();
  var discount_type=$("#discount_type").val();

  if($(".items_table tr").length>1){
    for(i=0;i<rowcount;i++){
      if(document.getElementById('tr_item_id_'+i)){
        total=parseFloat(total)+parseFloat($("#td_data_"+i+"_4").val());
        item_id=$("#tr_item_id_"+i).val();

        // Use proper function to get float data
        var row_wise_item_qty = get_float_type_data("#item_qty_"+item_id);
        item_qty += row_wise_item_qty;
      }
    }//for end
  }//items_table

  //Find customers payment
  var payments_row = parseInt(get_id_value("payment_row_count")) || 1;
  console.log("payments_row="+payments_row);
  var paid_amount = parseFloat(0);
  
  for (var i = 1; i <= payments_row; i++) {
    if(document.getElementById("amount_"+i)){
      var amount = parseFloat(get_id_value("amount_"+i));
      amount = isNaN(amount) ? 0 : amount;
      console.log("amount_"+i+"="+amount);
      paid_amount += amount;
    }
  }
  
  //Calculate discount
  var discount_amt = calulate_discount(discount_input, discount_type, total);

  var change_return = 0;
  var subtotal = total - discount_amt;
  var coupon_amt = discount_coupon_tot(subtotal);
  subtotal -= coupon_amt;

  var balance = subtotal - paid_amount;

  if(balance < 0){
    change_return = Math.abs(parseFloat(balance));
    balance = 0;
  }
  
  balance = round_off(balance);
  
  // Update display values
  $(".sales_div_tot_qty").html(format_qty(item_qty));
  $(".sales_div_tot_amt").html(to_Fixed(total));
  $(".sales_div_tot_discount").html(to_Fixed(discount_amt)); 
  $(".coupon_discount_div_amt").html(to_Fixed(coupon_amt)); 
  $("#coupon_discount_amt").val(coupon_amt); 
  $(".sales_div_tot_payble").html(round_off(subtotal)); 
  $(".sales_div_tot_paid").html(round_off(paid_amount));
  $(".sales_div_tot_balance").html(round_off(balance)); 
  $(".sales_div_change_return").html(to_Fixed(change_return)); 
}

function get_float_type_data(selector) {
  var value = parseFloat($(selector).val());
  return isNaN(value) ? 0 : value;
}

function get_item_details(item_id){
  var base_url=$("#base_url").val();
  var warehouse_id=$("#warehouse_id").val();
  $(".box").append('<div class="overlay"><i class="fa fa-refresh fa-spin"></i></div>');
  $.post(base_url+"pos/get_item_details",{item_id:item_id,warehouse_id:warehouse_id},function(result){
    console.log(result);
    var item = jQuery.parseJSON(result);

    var obj = {};
    obj['item_id']        = item['id'];
    obj['item_name']      = item['item_name'];
    obj['stock']          = item['stock'];
    obj['sales_price']    = item['sales_price'];
    obj['purchase_price'] = item['purchase_price'];
    obj['tax_id']         = item['tax_id'];
    obj['tax_type']       = item['tax_type'];
    obj['tax']            = item['tax'];
    obj['tax_name']       = item['tax_name'];
    obj['item_tax_amt']   = item['item_tax_amt'];
    obj['discount_type']  = item['discount_type'];
    obj['discount']       = item['discount'];
    obj['service_bit']    = item['service_bit'];
    addrow(null,obj);
    $(".overlay").remove();
  });
}

// Helper function to calculate discount
function calulate_discount(discount_input, discount_type, total) {
  discount_input = parseFloat(discount_input) || 0;
  total = parseFloat(total) || 0;
  
  if(discount_type == 'in_percentage') {
    return parseFloat((total * discount_input) / 100);
  } else { // in_fixed
    return parseFloat(discount_input);
  }
}

/* *********************** ORDER INVOICE END****************************/


$("#item_search").bind("paste", function(e){
    $("#item_search").autocomplete('search');
} );



$("#item_search").autocomplete({
	minLength: 0,
    source: function(data, cb){
        $.ajax({
        	autoFocus:true,
            url: $("#base_url").val()+'items/get_json_items_details',
            method: 'GET',
            dataType: 'json',
            /*showHintOnFocus: true,
			autoSelect: true, 
			
			selectInitial :true,*/
			
            data: {
                name: data.term,
                store_id:$("#store_id").val(),
                warehouse_id:$("#warehouse_id").val(),
                search_for:"sales",
            },
            beforeSend: function() {
                if($("#warehouse_id").val()==''){
                  toastr['warning']("Please Select Wareshouse!");
                  $("#warehouse_id").select2('open');
                  $("#item_search").removeClass('ui-autocomplete-loading');
                  return;
                }
                $("#item_search").addClass('ui-autocomplete-loading');
            },
            success: function(res){
              //console.log(res);
                var result;
                result = [
                    {
                        //label: 'No Records Found '+data.term,
                        label: 'No Records Found ',
                        value: ''
                    }
                ];

                if (res.length) {
                    result = $.map(res, function(el){
                        return {
                            label: el.item_code +'--[Qty:'+el.stock+'] --'+ el.label,
                            value: '',
                            id: el.id,
                            item_name: el.value,
                            stock: el.stock,
                            service_bit: el.service_bit,
                           // mobile: el.mobile,
                            //customer_dob: el.customer_dob,
                            //address: el.address,
                        };
                    });
                }

                cb(result);
            }
        });
    },
     response:function(e,ui){
          if(ui.content.length==1){
            $(this).data('ui-autocomplete')._trigger('select', 'autocompleteselect', ui);
            $(this).autocomplete("close");
          }
          //console.log(ui.content[0].id);
        },
        //loader start
        search: function (e, ui) {
        },
        select: function (e, ui) { 
          	
            
           
            if(typeof ui.content!='undefined'){
              console.log("Autoselected first");
              if(isNaN(ui.content[0].id)){
                return;
              }
              var stock=ui.content[0].stock;
              var item_id=ui.content[0].id;
              var service_bit=ui.content[0].service_bit;
            }
            else{
              console.log("manual Selected");
              var stock=ui.item.stock;
              var item_id=ui.item.id;
              var service_bit=ui.item.service_bit;
            }
            if(service_bit==0 && parseFloat(stock)<=0){
              toastr["warning"](stock+" Items in Stock!!");
              failed.currentTime = 0; 
              failed.play();
              return false;
            }

           /* if(service_bit==1){
              return_row_with_data(item_id);  
            }
            else {
              if(restrict_quantity(item_id)){
                return_row_with_data(item_id);  
              }
            }*/
            //addrow(item_id);
            get_item_details(item_id);
            $("#item_search").val('');
            
            
        },   
        //loader end
});


function set_previous_due(previous_due,tot_advance){
  $(".customer_previous_due").html(previous_due);
  $(".customer_tot_advance").html(tot_advance);
}



function get_coupon_details(){
  var input_box = $("#coupon_code");
  var coupon_code = $.trim(input_box.val());
  var customer_id = $("#customer_id").val();
  var base_url=$("#base_url").val();

  var coupon_type='';
  var coupon_value=0;
  if(coupon_code!=''){
    input_box.addClass('ui-autocomplete-loading');
    $.post(base_url+'customer_coupon/get_coupon_details', {invoice_type:'sales',coupon_code: coupon_code,customer_id:customer_id}, function(data, textStatus, xhr) {
      var json = $.parseJSON(data);
      coupon_value=json.coupon_value;
      coupon_type=json.coupon_type;

      

      $(".coupon_value").html(to_Fixed(coupon_value));
      $(".coupon_type").html(coupon_type);  

      $(".div1,.div2").removeClass('hide');
      
      if(json.expire_status=='Valid'){
        $(".msg_color").removeClass('alert-warning').addClass('alert-success');
      }
      else{
       $(".msg_color").removeClass('alert-success').addClass('alert-warning');
       $(".div2").addClass('hide');
      }
      $("#coupon_code_msg").text(json.message);

      input_box.removeClass('ui-autocomplete-loading');

      final_total();
      adjust_payments();
    });
  }else{
    $(".div1, .div2").addClass('hide');
    $(".coupon_value").html(to_Fixed(coupon_value));
    $(".coupon_type").html(coupon_type);  
    final_total();
    adjust_payments();
  }  
}


$("#coupon_code, #customer_id").on("change",function() {
  get_coupon_details();
});
$('#coupon_code').keypress(function (e) {
 var key = e.which;
 // the enter key code
 if(key == 13){
    get_coupon_details();  
  }
});  

/*Calculate Coupon Discount Amount*/
 const discount_coupon_tot = function(subtotal) {
     var coupon_value=parseFloat($(".coupon_value").html());
         coupon_value = isNaN(coupon_value) ? 0 : coupon_value;

     var coupon_type=$(".coupon_type").html();

     var discount_amt =0;
     if(coupon_type!='' && coupon_value>0){

         if(coupon_type=='Percentage'){
             discount_amt=(subtotal*coupon_value)/100;
         }
         else{//Fixed
             discount_amt=coupon_value;
         }
     }
     return discount_amt;
 }
 
 $('#item_search').keypress(function (e) {
 var key = e.which;
 // the enter key code
 if(key == 13){
    $("#item_search").autocomplete('search');
  }
}); 


