function sub_total()
{
	var totals=0;
	$('.li_prd_total').each(function(e){
		totals +=parseFloat($(this).text());
	});
	return totals;
}
function pedit_gtotal()
{
	var totals=0;
	$('.epur-total').each(function(e){
		totals +=parseFloat($(this).text());
	});
	$('#epur-gtotal').text(totals.toFixed(3));
}
$(document).ready(function(){
	
	$('#transferTable').DataTable({
		ajax: {
            url:  base_url+'stock/transfer/show',
            type: "GET", // or 'POST' if needed
        },
        language: {
            lengthMenu: "_MENU_",
        },
        pageLength: 100,
        order: [],
        responsive: true,
    });

	$('#trf-details').on('show.bs.modal',function(e){
		var invoice = e.relatedTarget.id;
		$('#invoice_number').text(invoice);
		var form_data = new FormData();
		form_data.append('invoice',invoice);
		$.ajax({
			url:base_url+'stock/transfer/details',
			type:'POST',
			processData:false,
			contentType: false,
			data:form_data,
			success:function(response)
			{
				var res = $.parseJSON(response)
				$('#trf-mbody').html('');
				$('#trf-mbody').html(res[0]);
			}
		});
	});


	$('#purchase-edit-modal').on('show.bs.modal',function(e){
		var invoice = e.relatedTarget.id;
		$('#pedit_invoice_number').text(invoice);
		var token_name   = "<?php echo $this->security->get_csrf_token_name();?>";
		var token_value  = $('#my_csrf').val();
		var form_data = new FormData();
		form_data.append('invoice',invoice);
		form_data.append(token_name,token_value);
		$.ajax({
			url:base_url+'stock/purchase_invoice_edit_details',
			type:'POST',
			processData:false,
			contentType: false,
			data:form_data,
			success:function(response)
			{
				var res = $.parseJSON(response)
				$('#my_csrf').val(res[0]);
				$('#pedit-mbody').html('');
				$('#pedit-mbody').html(res[1]);
			}
		});
	});
	
	$(document).on('keyup','.epur-price',function(e){
		var price = parseFloat($(this).val());
		var qty   = parseFloat($(this).closest('tr').find('.epur-qty').val());
		if(isNaN(price)){price=0;}
		if(isNaN(qty)){qty=0;}
		var total = price*qty;
		$(this).closest('tr').find('.epur-total').text(total.toFixed(3));
		pedit_gtotal();
	});

	$(document).on('keyup','.epur-qty',function(e){
		var price = parseFloat($(this).closest('tr').find('.epur-price').val());
		var qty   = parseFloat($(this).val());
		if(isNaN(price)){price=0;}	
		if(isNaN(qty)){qty=0;}
		var total = price*qty;
		$(this).closest('tr').find('.epur-total').text(total.toFixed(3));
		pedit_gtotal();
	});

	$('#btn-update-purchase').on('click',function(e){
		var invoice    = $('#pedit_invoice_number').text();
		var sub_total  = $('#epur-gtotal').text();
		var item_name  = [];
		var item_price = [];
		var item_qty   = [];
		$('.epur-item').each(function(e){
			item_name.push($(this).text());
			item_price.push($(this).closest('tr').find('.epur-price').val());
			item_qty.push($(this).closest('tr').find('.epur-qty').val());
		});
		var token_name   = "<?php echo $this->security->get_csrf_token_name();?>";
		var token_value  = $('#my_csrf').val();
		var form_data = new FormData();
		form_data.append('invoice',invoice);
		form_data.append('sub_total',sub_total);
		form_data.append('item_name',JSON.stringify(item_name));
		form_data.append('item_price',JSON.stringify(item_price));
		form_data.append('item_qty',JSON.stringify(item_qty));
		form_data.append(token_name,token_value);
		$.ajax({
			url:base_url+'stock/update_purchases',
			type:'POST',
			processData:false,
			contentType: false,
			data:form_data,
			success:function(response)
			{
				var res = $.parseJSON(response)
				$('#my_csrf').val(res[0]);
				if(res[1]==1)
				{
					$('#ifnotify-success').text(' Updated');
					$('#ifnotify-success').trigger('click');
				}
				else
				{
					$('#ifnotify-error').text(' Error Try Again !');
					$('#ifnotify-error').trigger('click');
				}
				$('#purchaseTable').DataTable().ajax.reload();
			}
		});
	});

	$('#purchaseTable').on('click','.ifdel',function(e){
	  e.preventDefault();
	  var href = $(this).attr('href');
	  if(typeof(href) != "undefined" && href !== null)
	  {
		  swal({
		      title:"Are you sure?",
		      text: "You will not be able to recover this data!",
		      type: "warning",
		      showCancelButton: true,
		      confirmButtonClass: 'btn-danger btn-md waves-effect waves-light',
		      confirmButtonColor: "#DD6B55",
		      confirmButtonText: "Yes, delete it!",
		      cancelButtonText: "No, cancel it!",
		      closeOnConfirm: true,
		      closeOnCancel: true
		  }, function (isConfirm) {
		      if (isConfirm) 
		      {
		    	window.location=href;
		      } 
		      else 
		      {
		          return false;
		      }
		  });
	  }
	});

	var abc = 0; 

	$('#prd_stk').on('keydown',function(e){
			if (e.keyCode == 74 && e.ctrlKey) {
				abc=1;
				return false;
 		    }
	});
	
	$("#prd_stk").autocomplete({
       source: base_url+'purchases/search-prd',
       minLength: 2,
       autoFocus: true,
       focus: function(event, ui) {
       	     event.preventDefault();
       	     if(abc==1)
       	     {
	             $(this).val(ui.item.value);
	             $('#prd_stk_qty').focus();
	             // $('#btn-add-prd-stk-atl').trigger('click');
	         }
       },
    });

	$('#prd_stk_qty').on('focusin',function(e){
		abc=0;
	});

	$('#prd_stk_qty').on('keypress',function(e){
		var key = e.which;
		if(key==13)
		{
			$('#btn-add-prd-stk-atl').trigger('click');
		}
	});
	// $("#prd_stk").autocomplete({
 //       source: base_url+'stock/search_prd',
 //       minLength: 2
 //    });

	$('#btn-add-prd-stk-atl').on('click',function(){
		$('#req-msg').hide();
		var select_from = $('#select_from').val();
		var select_to = $('#select_to').val();

		var prd_stk 	= $('#prd_stk').val();
		var prd_stk_qty = $('#prd_stk_qty').val();
		var total_branches = 0;
		$('.trf_br_chk').each(function(e){
			if($(this).is(':checked'))
			{
				total_branches++;
			}
		});
		var flag=0;	
		if(prd_stk==""){$('#req-msg').html('Enter item').fadeIn('slow');return false;}
		if(prd_stk_qty==""){$('#req-msg').html('Enter Quantity').fadeIn('slow'); return false;}
		if(select_from=="" && total_branches==0){$('#req-msg').html('Select Branch(es)').fadeIn('slow');return false;}
		var form_data = new FormData();
		form_data.append('prd_stk',prd_stk);
		form_data.append('prd_stk_qty',prd_stk_qty);
		form_data.append('total_branches',total_branches);
		form_data.append('select_from',select_from);
		$.ajax({
			url:base_url+'stock/transfer/add_items_to_transfer_list',
			type:'POST',
			processData:false,
			contentType: false,
			data:form_data,
			success:function(response)
			{
				var res = $.parseJSON(response)
				if(res[1]!='no')
				{

					if(res['qty_avl']=='no')
					{
						if(res['ttype']=='admin')
						{
							swal('Not Enough Quantity','Available :'+res['stk_qty']+' Required :'+res['qty_required']+' for '+total_branches+' Branch(es)','warning');
							$flag=1;
						}
						else if(res['ttype']=='inter')
						{
							swal('Not Enough Quantity','Available :'+res['stk_qty']+' Required :'+res['qty_required'],'warning');
							$flag=1;	
						}
					}
					else
					{
						$('#prd_stk_tbody').append('<tr><td></td><td class="li_prd_stk">'+prd_stk+'</td><td><span class="li_prd_qty">'+prd_stk_qty+'</span></td><td class="li_prd_price">'+res['sprice']+'</td><td class="li_prd_total">'+eval(prd_stk_qty*res['sprice'])+'</td><td><a href="#" class="tr-rmv"><i class="fa fa-close"></a></td></tr>');
							$('#spl_hid').val($('#prd_spl').val());
							$('#prd_spl').prop('disabled',true); 
							$('#sub_total').text(sub_total().toFixed(2));
							recalcId();
							$('#prd_stk_qty').val("");
							$('.trf_br_chk').prop('disabled',true);
							$('#select_from').prop('disabled',true);
							$('#select_to').prop('disabled',true);
							$('#prd_stk').val("");
							$('#prd_stk').focus();
							var e = jQuery.Event("keydown", { keyCode: 20 });
							$("#prd_stk").trigger( e );
					}
				}
				else
				{
					swal('Not Available','ITEM NOT AVAILABLE','warning');
					$flag=1;
				}
			}
		});
	});

	$(document).on('click','.tr-rmv',function(e){
		$(this).closest('tr').remove();
		$('#sub_total').text(sub_total().toFixed(2));
		recalcId();
	});

	$('#payments').on('keyup',function(e){
		var sub_total = parseFloat($('#subtotal').text());
		var payments  = parseFloat($(this).val());

		if(isNaN(sub_total)){sub_total=0;}
		if(isNaN(payments)){payments=0;}
		var change    = (sub_total-payments).toFixed(2);
		$('#change').text(change);
	});

	$('#btn-process-items').on('click',function(){
		var select_from = $('#select_from').val();
		var select_to = $('#select_to').val();
		var subtotal = sub_total().toFixed(2);
		var branches = [];
		var item_name=[];
		var item_price=[];
		var item_qty =[];
		var item_total=[];
		$('.trf_br_chk').each(function(e){
			if($(this).is(':checked'))
			{
				branches.push($(this).val());
			}
		})
		$('.li_prd_stk').each(function(){
			item_name.push($(this).text());
			item_price.push($(this).closest('tr').find('.li_prd_price').text());
			item_qty.push($(this).closest('tr').find('.li_prd_qty').text());
			item_total.push($(this).closest('tr').find('.li_prd_total').text());
		});
		if(select_from =="" && select_to=="" && branches.length==0)
		{
			swal('Type Action Required','Please select type of transfer "From" or "To" ','info');
			return false;	
		}
		if(select_to !="" && select_from=="")
		{
			swal('Action Required','Please select transfer from also','info');
			return false;		
		}
	
		if(item_name.length==0)
		{
			swal('Add Some Items','Please add some items to continue','info');
			return false;
		}
		if(select_from!="" && select_to!="" && branches.length==0)
		{
			var ttype = 'inter';
		}
		if(select_from=="" && select_to=="" && branches.length!=0)
		{
			var ttype = 'admin';
		}
		
		var form_data = new FormData();
		form_data.append('subtotal',subtotal);
		form_data.append('ttype',ttype);
		form_data.append('select_from',select_from);
		form_data.append('select_to',select_to);
		form_data.append('branches',JSON.stringify(branches));
		form_data.append('item_name',JSON.stringify(item_name));
		form_data.append('item_price',JSON.stringify(item_price));
		form_data.append('item_qty',JSON.stringify(item_qty));
		form_data.append('item_total',JSON.stringify(item_total));
		
		$.ajax({
			url:base_url+'stock/transfer/process_transfer_items',
			type:'POST',
			processData:false,
			contentType: false,
			async:false,
			data:form_data,
			success:function(response)
			{
				var res = $.parseJSON(response)
				$('#my_csrf').val(res[0]);
				if(res[1]==1)
				{
					
					$('#ifnotify-success').text(' Processed');
					$('#ifnotify-success').trigger('click');
					$('#prd_stk_tbody').html("");
					$('#subtotal').text(0);
					$('.trf_br_chk').prop('disabled',false);
					$('.trf_br_chk').prop('checked',false);
					$('#select_from').prop('disabled',false);
					$('#select_to').prop('disabled',false);
					for(var i=0;i<res[2].length;i++)
					{
						// alert(res[2][i]);
						window.open(base_url+'stock/invoice/'+res[2][i]);
					}
				}
				else
				{
					$('#ifnotify-error').text(' Error try again');
					$('#ifnotify-error').trigger('click');
				}
			}
		});
	});

	$('#select_from').on('change',function(e){
		if($(this).val()=="")
		{
			// var opts = $(this).html();
			$('.trf_br_chk').prop('disabled',false);
			$('#select_to option').remove();
			$('#select_to').append('<option value="" selected> Select </option>');
			$('#select_to').append('<option value="0"> Admin </option>');	
			return false;
		}
		$('.trf_br_chk').prop('checked',false);
		$('.trf_br_chk').prop('disabled',true);
		var opts = $(this).html();
		$('#select_to').append(opts);
		$('#select_to option[value=""]').remove();
		$('#select_to option[value="'+$(this).val()+'"]').remove();
	});
});// End Ready Function
