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

    if(kevent.keyCode==13){
		$("#"+target).focus();
    }
	
}


$('#save,#update,#create').on("click",function (e) {
	var base_url=$("#base_url").val();

    //Initially flag set true
    var flag=true;

    function check_field(id)
    {

      if(!$("#"+id).val() ) //Also check Others????
        {

            $('#'+id+'_msg').fadeIn(200).show().html('Required Field').addClass('required');
           // $('#'+id).css({'background-color' : '#E8E2E9'});
            flag=false;
        }
        else
        {
             $('#'+id+'_msg').fadeOut(200).hide();
             //$('#'+id).css({'background-color' : '#FFFFFF'});    //White color
        }
    }


   //Validate Input box or selection box should not be blank or empty
	  check_field("customer_id");
    check_field("return_date");
    check_field("return_status");
    //check_field("warehouse_id");
	/*if(!isNaN($("#amount").val()) && parseInt($("#amount").val())==0){
        toastr["error"]("You have entered Payment Amount! <br>Please Select Payment Type!");
        return;
    }*/

	if(flag==false)
	{
		toastr["error"]("You have missed Something to Fillup!");
		return;
	}

	//Atleast one record must be added in sales table 
    var rowcount=document.getElementById("hidden_rowcount").value;
	var flag1=false;
	for(var n=1;n<=rowcount;n++){
		if($("#td_data_"+n+"_3").val()!=null && $("#td_data_"+n+"_3").val()!=''){
			flag1=true;
		}	
	}
	
    if(flag1==false){
    	toastr["warning"]("Please Select Item!!");
        $("#item_search").focus();
		return;
    }
    //end


    if($("#amount").val()!=''){
      if(parseFloat($("#amount").val())!=0){
          if($("#payment_type").val()==''){
            toastr["warning"]("Please Select Payment Type!!");
            return;
          }
      }
    }

    var tot_subtotal_amt=$("#subtotal_amt").text();
    var other_charges_amt=$("#other_charges_amt").text();//other_charges include tax calcualated amount
    var tot_discount_to_all_amt=$("#discount_to_all_amt").text();
    var tot_round_off_amt=$("#round_off_amt").text();
    var tot_total_amt=$("#total_amt").text();
    var coupon_discount_amt=$("#coupon_discount_amt").text();

    var this_id=this.id;
    
			//if(confirm("Do You Wants to Save Record ?")){
				e.preventDefault();
				data = new FormData($('#sales-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+'sales_return/sales_save_and_update?command='+this_id+'&rowcount='+rowcount+'&tot_subtotal_amt='+tot_subtotal_amt+'&tot_discount_to_all_amt='+tot_discount_to_all_amt+'&tot_round_off_amt='+tot_round_off_amt+'&tot_total_amt='+tot_total_amt+"&other_charges_amt="+other_charges_amt+"&coupon_discount_amt="+coupon_discount_amt,
				data: data,
				cache: false,
				contentType: false,
				processData: false,
				success: function(result){
         // alert(result);return;
				result=result.split("<<<###>>>");
					if(result[0]=="success")
					{
						location.href=base_url+"sales_return/invoice/"+result[1];
					}
					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();

			   }
			   });
		//}
  
});

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

$("#item_search").autocomplete({
    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){
                      //qty_ = (el.service_bit!=1) ? '--[Qty:'+el.stock+'] --' : '--';
                      qty_ ='--'
                        return {
                            label: el.item_code +qty_+ el.label,
                            value: '',
                            id: el.id,
                            item_name: el.value,
                            stock: el.stock,
                           // 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, u) {
        },
        select: function (e, ui) { 
           if(typeof ui.content!='undefined'){
              if(isNaN(ui.content[0].id)){
                return;
              }
              var stock=ui.content[0].stock;
              var item_id=ui.content[0].id;
            }
            else{
              var stock=ui.item.stock;
              var item_id=ui.item.id;
            }

            /*if(parseFloat(stock)<=0){
              toastr["warning"]("Only "+stock+" Items in Stock!!");
              failed.currentTime = 0; 
              failed.play();
              return false;
            }
            else{*/
              if(restrict_quantity(item_id)){
                return_row_with_data(item_id);  
              }
            /*}*/
            
            $("#item_search").val('');
            
        },   
        //loader end
});

function check_same_item(item_id){

  if($("#sales_table tr").length>1){
    var rowcount=$("#hidden_rowcount").val();
    for(i=0;i<=rowcount;i++){
            if($("#tr_item_id_"+i).val()==item_id){
              increment_qty(i);
              failed.currentTime = 0;
              failed.play();
              return false;
            }
      }//end for
  }
  return true;
}

function return_row_with_data(item_id){
  //CHECK SAME ITEM ALREADY EXIST IN ITEMS TABLE 
  var item_check=check_same_item(item_id);
  if(!item_check){return false;}
  //END
  
  $("#item_search").addClass('ui-autocomplete-loader-center');
  /*Check purchase id avaialable or not*/
  if(!document.getElementById("sales_id")){
    var sales_id='';
  }else{
    var sales_id=$("#sales_id").val()
  }
  /*end*/

	var base_url=$("#base_url").val();
	var rowcount=$("#hidden_rowcount").val();
	$.post(base_url+"sales_return/return_row_with_data/"+rowcount+"/"+item_id,{sales_id:sales_id},function(result){
        //alert(result);
        if(result=='item_not_exist'){
          toastr["error"]("Sorry! This Item Not exist in this Sales Entry!!");
         
        }
        else{
          $('#sales_table tbody').append(result);
          $("#hidden_rowcount").val(parseInt(rowcount)+1);
          success.currentTime = 0;
          success.play();
          enable_or_disable_item_discount(); 
        }


        $("#item_search").removeClass('ui-autocomplete-loader-center');
    }); 
}
//INCREMENT ITEM
function increment_qty(rowcount){
  
  var flag = restrict_quantity($("#tr_item_id_"+rowcount).val());
  if(!flag){ return false;}

  var item_qty=$("#td_data_"+rowcount+"_3").val();
  var available_qty=$("#tr_available_qty_"+rowcount+"_13").val();
  if(parseFloat(item_qty)<parseFloat(available_qty)){
    item_qty=parseFloat(item_qty)+1;
    $("#td_data_"+rowcount+"_3").val(format_qty(item_qty));
  }
  calculate_tax(rowcount);
}
//DECREMENT ITEM
function decrement_qty(rowcount){
  var item_qty=parseFloat($("#td_data_"+rowcount+"_3").val());
  if(item_qty<=1){
    $("#td_data_"+rowcount+"_3").val(format_qty(1));
    return;
  }
  $("#td_data_"+rowcount+"_3").val(format_qty(item_qty-1));
  calculate_tax(rowcount);
}

function update_paid_payment_total() {
  var rowcount=$("#paid_amt_tot").attr("data-rowcount");
  var tot=0;
  for(i=1;i<rowcount;i++){
    if(document.getElementById("paid_amt_"+i)){
      tot += parseFloat($("#paid_amt_"+i).html());
    }
  }
  $("#paid_amt_tot").html(to_Fixed(tot));
}
function delete_payment(payment_id){
 if(confirm("Do You Wants to Delete Record ?")){
    var base_url=$("#base_url").val();
    $(".box").append('<div class="overlay"><i class="fa fa-refresh fa-spin"></i></div>');
   $.post(base_url+"sales_return/delete_payment",{payment_id:payment_id},function(result){
   //alert(result);return;
   result=result;
     if(result=="success")
        { 
          toastr["success"]("Record Deleted Successfully!");
          $("#payment_row_"+payment_id).remove();
          success.currentTime = 0; 
          success.play();
        }
        else if(result=="failed"){
          toastr["error"]("Failed to Delete .Try again!");
          failed.currentTime = 0; 
          failed.play();
        }
        else{
          toastr["error"](result);
          failed.currentTime = 0; 
          failed.play();
        }
        $(".overlay").remove();
        update_paid_payment_total();
   });
   }//end confirmation   
  }

  //Delete Record start
function delete_return(q_id)
{
  var base_url=$("#base_url").val();
   if(confirm("Do You Wants to Delete Record ?")){
    $(".box").append('<div class="overlay"><i class="fa fa-refresh fa-spin"></i></div>');
    $.post(base_url+"sales_return/delete_return",{q_id:q_id},function(result){
   //alert(result);return;
     if(result=="success")
        {
          toastr["success"]("Record Deleted Successfully!");
          $('#example2').DataTable().ajax.reload();
        }
        else if(result=="failed"){
          toastr["error"]("Failed to Delete .Try again!");
        }
        else{
           toastr["error"](result);
        }
        $(".overlay").remove();
        return false;
   });
   }//end confirmation
}
//Delete Record end
function multi_delete(){
  var base_url=$("#base_url").val();
    var this_id=this.id;
    
    if(confirm("Are you sure ?")){
      data = new FormData($('#table_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+'sales_return/multi_delete',
      data: data,
      cache: false,
      contentType: false,
      processData: false,
      success: function(result){
        result=result;
  //alert(result);return;
        if(result=="success")
        {
          toastr["success"]("Record Deleted Successfully!");
          success.currentTime = 0; 
            success.play();
          $('#example2').DataTable().ajax.reload();
          $(".delete_btn").hide();
          $(".group_check").prop("checked",false).iCheck('update');
        }
        else if(result=="failed")
        {
           toastr["error"]("Sorry! Failed to save Record.Try again!");
           failed.currentTime = 0; 
           failed.play();
        }
        else
        {
          toastr["error"](result);
          failed.currentTime = 0; 
            failed.play();
        }
        $("#"+this_id).attr('disabled',false);  //Enable Save or Update button
        $(".overlay").remove();
       }
       });
  }
  //e.preventDefault
}

function pay_now(return_id){
  var base_url=$("#base_url").val();
  $.post(base_url+'sales_return/show_pay_now_modal', {return_id: return_id}, function(result) {
    $(".pay_now_modal").html('').html(result);
    //Date picker
    $('.datepicker').datepicker({
      autoclose: true,
    format: 'dd-mm-yyyy',
     todayHighlight: true
    });
    $('#pay_now').modal('toggle');

  });
}
function view_payments(return_id){
  var base_url=$("#base_url").val();
  $.post(base_url+'sales_return/view_payments_modal', {return_id: return_id}, function(result) {
    $(".view_payments_modal").html('').html(result);
    $('#view_payments_modal').modal('toggle');
  });
}

function save_payment(return_id){
  var base_url=$("#base_url").val();

    //Initially flag set true
    var flag=true;

    function check_field(id)
    {

      if(!$("#"+id).val() ) //Also check Others????
        {

            $('#'+id+'_msg').fadeIn(200).show().html('Required Field').addClass('required');
           // $('#'+id).css({'background-color' : '#E8E2E9'});
            flag=false;
        }
        else
        {
             $('#'+id+'_msg').fadeOut(200).hide();
             //$('#'+id).css({'background-color' : '#FFFFFF'});    //White color
        }
    }


   //Validate Input box or selection box should not be blank or empty
    check_field("amount");
    check_field("payment_date");


    var payment_date=$("#payment_date").val();
    var amount=$("#amount").val();
    var payment_type=$("#payment_type").val();
    var payment_note=$("#payment_note").val();
    var account_id=$("#account_id").val();
    var customer_id=$("#customer_id").val();

    if(amount == 0){
      toastr["error"]("Please Enter Valid Amount!");
      return false; 
    }

    if(amount > parseFloat($("#due_amount_temp").html())){
      toastr["error"]("Entered Amount Should not be Greater than Due Amount!");
      return false;
    }

    $(".box").append('<div class="overlay"><i class="fa fa-refresh fa-spin"></i></div>');
    $(".payment_save").attr('disabled',true);  //Enable Save or Update button
    $.post(base_url+'sales_return/save_payment', {customer_id:customer_id,account_id:account_id,return_id: return_id,payment_type:payment_type,amount:amount,payment_date:payment_date,payment_note:payment_note}, function(result) {
      result=result;
  //alert(result);return;
        if(result=="success")
        {
          $('#pay_now').modal('toggle');
          toastr["success"]("Payment Recorded Successfully!");
          success.currentTime = 0; 
          success.play();
          $('#example2').DataTable().ajax.reload();
        }
        else if(result=="failed")
        {
           toastr["error"]("Sorry! Failed to save Record.Try again!");
           failed.currentTime = 0; 
           failed.play();
        }
        else
        {
          toastr["error"](result);
          failed.currentTime = 0; 
          failed.play();
        }
        $(".payment_save").attr('disabled',false);  //Enable Save or Update button
        $(".overlay").remove();
    });
}

function delete_sales_payment(payment_id){
 if(confirm("Do You Wants to Delete Record ?")){
    var base_url=$("#base_url").val();
    $(".box").append('<div class="overlay"><i class="fa fa-refresh fa-spin"></i></div>');
   $.post(base_url+"sales_return/delete_payment",{payment_id:payment_id},function(result){
   //alert(result);return;
   result=result;
     if(result=="success")
        {
          $('#view_payments_modal').modal('toggle');
          toastr["success"]("Record Deleted Successfully!");
          success.currentTime = 0; 
          success.play();
          $('#example2').DataTable().ajax.reload();
        }
        else if(result=="failed"){
          toastr["error"]("Failed to Delete .Try again!");
          failed.currentTime = 0; 
          failed.play();
        }
        else{
          toastr["error"](result);
          failed.currentTime = 0; 
          failed.play();
        }
        $(".overlay").remove();
   });
   }//end confirmation   
  }

  function restrict_quantity(item_id) {
  	var rowcount=$("#hidden_rowcount").val();
  	var available_qty = 0;
  	var count_item_qty = 0;
  	var selected_item_id = 0;
      for(i=1;i<=rowcount;i++){
        if(document.getElementById("tr_item_id_"+i)){
        	selected_item_id = $("#tr_item_id_"+i).val();
            if(parseInt(item_id)==parseInt(selected_item_id)){
	             available_qty = parseFloat($("#tr_available_qty_"+i+"_13").val());
	             count_item_qty += parseFloat($("#td_data_"+i+"_3").val());
          }
        }
      }//end for
      if(available_qty!=0 && count_item_qty>=available_qty){
        toastr["warning"]("Only "+available_qty+" Items in Stock!!");
        failed.currentTime = 0; 
        failed.play();
      	return false;
      }
      return true;
  }

  /*$("#warehouse_id").on("change",function(event) {
    $('#sales_table tbody').html('');
    final_total();
    if($("#warehouse_id").val()!=''){
      $("#item_search").attr({ disabled: false,});
    }
    else{
     $("#item_search").attr({ disabled: true,}); 
    }
  });*/


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: 'return', 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").removeClass('hide');
      
      if(json.expire_status=='Valid'){
        $(".msg_color").removeClass('alert-warning').addClass('alert-success');
      }
      else{
       $(".msg_color").removeClass('alert-success').addClass('alert-warning'); 
      }
      $("#coupon_code_msg").text(json.message);

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

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


$("#coupon_code, #customer_id").on("change",function() {
  get_coupon_details();
  // Check customer currency when customer changes
  if($(this).attr('id') === 'customer_id') {
    checkCustomerCurrencyReturn($(this).val());
  }
});
$('#coupon_code').keypress(function (e) {
 var key = e.which;
 // the enter key code
 if(key == 13){
    get_coupon_details();  
  }
});

// Currency handling functions for sales return
var last_checked_customer_id_return = null;

// Function to update currency symbols in summary
function updateCurrencySymbols(currency_symbol) {
    $('.currency_symbol').text(currency_symbol);
}

// Function to update all summary currency symbols (same as sales.js)
function update_summary_currency_symbols(symbol) {
    $(".currency_symbol").each(function() {
        $(this).text(symbol);
    });
}

// Function to check customer currency and update display
function checkCustomerCurrencyReturn(customer_id) {
    // Skip if same customer was already checked
    if (customer_id === last_checked_customer_id_return) {
        return;
    }
    
    last_checked_customer_id_return = customer_id;
    
    // Hide both currency displays initially
    $("#customer_currency_info").hide();
    $("#walkin_currency_info").hide();
    
    if (!customer_id || customer_id === '' || customer_id === '1') {
        var baseCurrency = 'USD';
        var baseCode = 'USD';
        var baseSymbol = '$';
        
        $("#walkin_currency_name").text(baseCurrency + " (" + baseCode + ")");
        $("#walkin_currency_info").show();
        
        // Update currency symbols
        update_summary_currency_symbols(baseSymbol);
        return;
    }
    
    var base_url = $("#base_url").val();
    
    $.ajax({
        url: base_url + 'sales_return/get_customer_currency',
                    type: 'POST',
                    data: { customer_id: customer_id },
                    dataType: 'json',
                    success: function(currency_response) {
            if (currency_response.status && currency_response.currency_name) {
                var customer_currency_text = currency_response.currency_name + ' (' + currency_response.currency_code + ')';
                            $("#customer_currency_name").text(customer_currency_text);
                $("#customer_currency_info").show().removeClass('label-danger').addClass('label-info');
                            
                            // Change currency symbols in table headers
                var symbol = currency_response.currency_symbol || currency_response.currency_code || '$';
                            update_summary_currency_symbols(symbol);
                        } else {
                            $("#customer_currency_info").hide();
                            // Reset to base currency symbol
                update_summary_currency_symbols('$');
            }
        },
        error: function() {
            $("#customer_currency_info").hide();
            // Reset to base currency symbol
            update_summary_currency_symbols('$');
        }
    });
}

// Call currency check when customer changes
$(document).on('change', '#customer_id', function() {
    var customer_id = $(this).val();
    checkCustomerCurrencyReturn(customer_id);
});

// Initialize currency on page load
$(document).ready(function() {
    // Try multiple times to detect customer ID
    var attempts = 0;
    var maxAttempts = 5;
    
    function tryDetectCustomer() {
        attempts++;
        
        var customer_id = $('#customer_id').val();
        
        if (customer_id && customer_id !== '' && customer_id !== '1') {
            checkCustomerCurrencyReturn(customer_id);
        } else if (attempts < maxAttempts) {
            setTimeout(tryDetectCustomer, 500);
        } else {
            updateCurrencySymbols('$');
        }
    }
    
    // Start detection after initial delay
    setTimeout(tryDetectCustomer, 500);
});

// Test function - can be called from browser console
window.testCurrencyUpdate = function(symbol) {
    update_summary_currency_symbols(symbol);
};

// Test function to check current customer
window.testCustomerCheck = function() {
    var customer_id = $('#customer_id').val();
    checkCustomerCurrencyReturn(customer_id);
};

// Manual trigger function - can be called from browser console
window.triggerCurrencyCheck = function() {
    var customer_id = $('#customer_id').val();
    if (customer_id) {
        checkCustomerCurrencyReturn(customer_id);
    }
};

// Initialize currency on page load
$(document).ready(function() {
    // Try multiple times to detect customer ID
    var attempts = 0;
    var maxAttempts = 5;
    
    function tryDetectCustomer() {
        attempts++;
        
        var customer_id = $('#customer_id').val();
        
        if (customer_id && customer_id !== '' && customer_id !== '1') {
            checkCustomerCurrencyReturn(customer_id);
        } else if (attempts < maxAttempts) {
            setTimeout(tryDetectCustomer, 500);
        } else {
            update_summary_currency_symbols('$');
        }
    }
    
    // Start detection after initial delay
    setTimeout(tryDetectCustomer, 100);
});

// Test function to manually check currency
window.testCurrencyCheck = function() {
    var customer_id = $('#customer_id').val();
    checkCustomerCurrencyReturn(customer_id);
};  