<?php
defined('BASEPATH') OR exit('No direct script access allowed');
$producttotalrows = 1;
$currdt = date('Y-m-d');
if($info4edit["info"]) $producttotalrows = count($info4edit["info"]);
?>

      <div class="main my-0">
        <div class="row mt-3 mx-0">
          <div class="col-md-6">
            <h3><?php echo $pgheading;?></h3>
          </div>
          <div class="col-md-5 text-right">
            &nbsp;
          </div>
        </div>
        
        <div class="container_fluid mt-2 px-3">
		<form name="frmgeneral" method="post" action="warehouse/<?php echo $mgmtname;?>/managedata?<?php echo $_SERVER['QUERY_STRING'];?>" enctype="multipart/form-data" onsubmit="return validateFrm();">
		<input type="hidden" name="rsrcid" id="rsrcid" value="<?php echo $rsrcid;?>">                
        <table class="webforms mt-0 table-responsive-sm">
		<tr>
          
          <td width="6%"><label>Outlet:</label></td>
          <td width="35%">
		  <select name="outletid" id="outletid" required>
		  <option value="">Select Outlet</option>
						<?php
						if(is_array($outletlist) && count(array_filter($outletlist))>0)
						{

							foreach($outletlist as $outletrow)
							{
								$sel_outlet ="";
								if($info4edit["main"]->fld_outletid==$outletrow->fld_id)
								{
									$sel_outlet = 'selected="selected"';
								}				
									?>
											<option value="<?php echo $outletrow->fld_id;?>" <?php echo $sel_outlet;?>><?php echo $outletrow->fld_name;?></option>
									<?php
								
							}
						}
						?> 
		  </select>
		  </td>
         <?php
         if($info4edit["main"])
         {
         ?>
          <td width="12%"><label>Challan No.:</label></td>
          <td width="15%"><input type="text" name="refno" id="refno" value="<?php if($info4edit["main"]) { echo $info4edit["main"]->fld_refno; }?>" required  placeholder="Challan No."></td>
  
          <td width="17%"><label>Challan Date:</label></td>
          <td width="15%"><input type="date" name="refdate" id="refdate" value="<?php if($info4edit["main"]) { echo $info4edit["main"]->fld_refdate; }else { echo $currdt;}?>" required ></td>
         <?php
		}
		else
		{
         ?>
         <td colspan="4"></td>
       <?php
		}
       ?>
         </tr> 
		 <tr>
             <td colspan="6" class="text-center">&nbsp;
			 <h5 id="frmerrormsg" class=""></h5>
			 </td>
             
         </tr> 
		
		<tr><td colspan="6" ><h5>Product Info.</h5></td></tr>
		 <tr>
             <td colspan="6" id="divwarehousestockinfo">
			<table class="webforms mt-0 table-responsive-sm">
			 <tbody id="productrowbox">
			 <tr>
				<th width="50%">Product</th>
				<th width="10%">Instock</th>
				<th width="10%">Qty. (Case)</th>
				<th width="10%">Qty. (Bottle)</th>
				<th width="20%">&nbsp;</th>
			</tr>
			<?php
			
					if($info4edit["info"])
					{
						for($iix=0;$iix<count($info4edit["info"]);$iix++)
						{
							$rowidx = $iix+1;
							$rowinfo = $info4edit["info"][$iix];
				?>
					  
				<tr id="productrow_<?php echo $rowidx;?>">
				<td>
					<input type="hidden" name="transactioninfoids[]" id="transactioninfoids<?php echo $rowidx;?>" value="<?php echo $rowinfo->fld_id;?>"> 				
					<select  id="productid<?php echo $rowidx;?>" name="productid[]" required onchange="showproductinstock(this);" class="js-example-basic-single nxtinput" >
                                                                <option value="">--Select Product Name--</option>
						<?php
						if(is_array($productlist) && count(array_filter($productlist))>0)
						{	
							foreach($productlist as $itemrow)
							{
								$sel_item ="";
								$instock = $itemrow['instock'];
								if($rowinfo->fld_productid==$itemrow['productid'])
								{
									$sel_item = 'selected="selected"';
									$instock = ($itemrow['instock']+$rowinfo->fld_qty);
									$instocktoshow = $instock; 
								}	
								?>
										<option value="<?php echo $itemrow['productid']."_".$instock."_".$itemrow['noofbottlesincase'];?>"  <?php echo $sel_item;?>><?php echo $itemrow['name'];?></option>
								<?php
							}
						}
						?> 
				</select>
			</td>
			<td id="instockproductid<?php echo $rowidx;?>"><?php echo $instocktoshow;?>
			</td>
			<td><input type="text" name="qty_case[]" id="qty_case<?php echo $rowidx;?>"  placeholder="Quanity" value="<?php echo $rowinfo->fld_qty_case;?>" onchange="checkQtyRCVD('<?php echo $rowidx;?>');" onblur="checkQtyRCVD('<?php echo $rowidx;?>');" onkeypress='return event.charCode >= 48 && event.charCode <= 57 || event.charCode==46'>

			<span id="qty_caseemsg<?php echo $rowidx;?>" class=""></span></td>
			<td><input type="text" name="qty_bottle[]" id="qty_bottle<?php echo $rowidx;?>"  placeholder="Quanity" value="<?php echo $rowinfo->fld_qty_bottle;?>" onchange="checkQtyRCVD('<?php echo $rowidx;?>');" onblur="checkQtyRCVD('<?php echo $rowidx;?>');" onkeypress='return event.charCode >= 48 && event.charCode <= 57 || event.charCode==46'>

			<span id="qty_bottleemsg<?php echo $rowidx;?>" class=""></span></td>
			<td  id="rowid<?php echo $rowidx;?>"></td>
			</tr>					  
				<?php
						}
				?>
				<?php
					}
					else
					{
				?>
			 <tr id="productrow_1">
				<td><select  id="productid1" name="productid[]" required onchange="showproductinstock(this);" class="js-example-basic-single nxtinput" >
                                                                <option value="">--Select Product Name--</option>
						<?php
						if(is_array($productlist) && count(array_filter($productlist))>0)
						{	
							foreach($productlist as $itemrow)
							{
								if($itemrow['instock']>0)
								{
								?>
										<option value="<?php echo $itemrow['productid']."_".$itemrow['instock']."_".$itemrow['noofbottlesincase'];?>"  ><?php echo $itemrow['name'];?> </option>
								<?php
								}
							}
						}
						?>                                      
</select></td>
<td id="instockproductid1"><span id="rcvdmsg1" class=""></span></td>
<td><input type="text" name="qty_case[]" id="qty_case1"  placeholder="Quanity" value="0" required="required" data-validation-required-message="This field is required" aria-invalid="false" onchange="checkQtyRCVD('1');" onblur="checkQtyRCVD('1');" onkeypress='return event.charCode >= 48 && event.charCode <= 57 || event.charCode==46'>
<span id="qty_caseemsg1" class=""></span></td>
<td><input type="text" name="qty_bottle[]" id="qty_bottle1"  placeholder="Quanity" value="0" required="required" data-validation-required-message="This field is required" aria-invalid="false" onchange="checkQtyRCVD('1');" onblur="checkQtyRCVD('1');" onkeypress='return event.charCode >= 48 && event.charCode <= 57 || event.charCode==46'>
<span id="qty_bottleemsg1" class=""></span></td>
<td>&nbsp;</td>
</tr>
	
<?php
					}
		 ?>
		 
		</tbody> 
		</table> 
		<table class="webforms mt-0 table-responsive-sm">
			 <tbody>
			 <tr>
				 <td width="50%"></td>
				 <td width="20%" id="totalcasesid" class="text-center"></td>
				 <td width="20%" id="totalbottlesid" class="text-center"></td>
				 <td width="10%" class="text-right"><a class="btn btn-success text-white" style="cursor:pointer" onclick="return addrow('<?php echo base_url();?>');"><i class="fa fa-plus"></i> Row</a></td>
			 </tr>
			 <tr>
				 <td></td>
				 <td colspan="5" class="text-right"><button class="btn btn-danger">Submit</button></td>
			 </tr>
		 </tbody> 
		</table> 			 
			 </td>
             
         </tr>         
			

		<input type="hidden" name="producttotalrows" id="producttotalrows" value="<?php echo $producttotalrows;?>"  />
         </table>
         </form> 
	         <div class="clearfix"></div>          
        </div>
       </div>
<script>

document.addEventListener('keyup', function(event) {
	var producttotalrows = $("#producttotalrows").val();
	 eidname =   event.target.name;	
	//alert(event.keyCode);
	//alert(eidname);
if (event.shiftKey==false)
{
if (event.keyCode == 46)
 {
	eid =   event.target.id;
	if(eidname=='productid[]')
	{			
		var eidindex = eid.split("productid");			
	}
	else if(eidname=='qty_case[]')
	{			 
		var eidindex = eid.split("qty_case");			
	}
	else if(eidname=='qty_bottle[]')
	{			
		var eidindex = eid.split("qty_bottle");			
	}
	
	indexno  = eidindex[1];
	indexno = parseInt(indexno);		
	if(indexno>1)
	 {		
		transactioninfoids = $("#transactioninfoids"+indexno).val();
		transactioninfoids = parseInt(transactioninfoids);
		//alert(transactioninfoids);
		if(transactioninfoids>0)
		 {
			removerow(indexno,'product','edit','<?php echo base_url();?>');
		 }
		 else
		 {
			removerow(indexno,'product','add','<?php echo base_url();?>');
		 }
	 }
 }	

	  if (event.keyCode == 9 && eidname=="qty_bottle[]") {

		 eid =   event.target.id;
		 var eidindex = eid.split("qty_bottle");
		 indexno  = eidindex[1];
		 indexno = parseInt(indexno);
		 if(producttotalrows==indexno)
		  {
			 addrow('<?php echo base_url();?>');
		  }
		 indexno = indexno+1;
		indexno = parseInt(indexno);
		 
	  }
  
}
  
});
		function showproductinstock(event)
		{	
			prodval = event.value;
			prodidindex = event.id;			
			var proddata = prodval.split("_");
			var stock = proddata[1];			
			$("#instock"+prodidindex).html(stock);
			
		}
		function getwarehousestockinfo(basePath)
		{
			var warehouseid = $("#warehouseid").val();
			var rsrcid = $("#rsrcid").val();
			
			  if(warehouseid!="")
			  { 
				$.ajax({
					url: basePath+"warehouse/getwarehousestockinfo",
					data: {'warehouseid': warehouseid,'rsrcid': rsrcid}, 
					type: "post",
					beforeSend: function() {
						//$("#divindentinfo").html('<img src="'+basePath+'assets/images/loader.gif" style="width: 40px;" />');	
					},
					success: function(data){
						
						//$("#divwarehousestockinfo").css('display','block');				
						html = data.trim();
						//alert(html);		
						$("#divwarehousestockinfo").html(html);
					}
				});

			  }	
		}
		</script>
<?php
/*
if($rsrcid>0)
{
	?>
		<script>
		setTimeout(function(){
			getwarehousestockinfo('<?php echo base_url();?>');
		},3000);

	</script>
<?php
}*/
?>
<script>	
function validateFrm()
{
	var totalrows = $("#producttotalrows").val();
	totalrows = parseInt(totalrows);
	errorstatus = 1;
	alert(totalrows);
	for(ix=1;ix<=totalrows;ix++)
	{			
		//checkQtyRCVD(ix);
		var qty_case = $("#qty_case"+ix).val();	
		qty_case = parseInt(qty_case);
		if(qty_case>0)
		{
			errorstatus = 0;
		}
		var qty_bottle = $("#qty_bottle"+ix).val();	
		qty_bottle = parseInt(qty_bottle);
		if(qty_bottle>0)
		{
			errorstatus = 0;
		}
	}
	if(errorstatus==1)
	{		
		$("#frmerrormsg").html('Please create at least single row to proceed!');
		$("#frmerrormsg").addClass('alert alert-danger');
		setTimeout(function(){
		$("#frmerrormsg").removeClass('alert alert-danger');			
		$("#frmerrormsg").html("");
		},4000);
		return false;
	}
	else
	{
		return true;	  
	}
		
}

function addrow(base_url)
{
	var id = $("#producttotalrows").val();
	
	var productlist = $("#productid1").html();
	
	id = parseInt(id) + 1;
	$("#producttotalrows").val(id);	
		
	$("#productrowbox").append('<tr id="productrow_'+id+'"><td><select id="productid'+id+'" name="productid[]"  onchange="showproductinstock(this);" class="js-example-basic-single nxtinput">'+productlist+'</select></td><td id="instockproductid'+id+'"></td><td><input type="text" name="qty_case[]" id="qty_case'+id+'" placeholder="Quanity" value="0" onchange="checkQtyRCVD('+id+');" onblur="checkQtyRCVD('+id+');" onkeypress="return event.charCode >= 48 &amp;&amp; event.charCode <= 57 || event.charCode==46"><span id="qty_caseemsg'+id+'" class=""></span></td><td><input type="text" name="qty_bottle[]" id="qty_bottle'+id+'" placeholder="Quanity" value="0" onchange="checkQtyRCVD('+id+');" onkeypress="return event.charCode >= 48 &amp;&amp; event.charCode <= 57 || event.charCode==46"><span id="qty_bottleemsg'+id+'" class=""></span></td><td id="rowid'+id+'"><a class="btn btn-danger text-white" style="cursor:pointer" onclick="return removerow('+id+',\'product\',\'add\',\''+base_url+'\')">x</a></td></tr>');
	$('.js-example-basic-single').select2();

}
function removerow(rowId,actionFor,actionType,base_url)
{
	totalRowIdname = '#'+actionFor+'totalrows';
	removerowId= '#'+actionFor+'row_'+rowId;
	if(actionType == "add")
	{
			totalRow = $(totalRowIdname).val();
			//alert(totalRow);
			$(removerowId).remove();
			
			for(i=eval(rowId+1); i<=totalRow; i++)
			{
				if(actionFor=="product")
				{
					addremovelink = '<a class="btn btn-danger text-white" style="cursor:pointer" onclick="return removerow('+eval(i-1)+',\'product\',\'add\',\''+base_url+'\')">x</a>';
					$("#productrow_"+i).attr('id','productrow_'+eval(i-1));
					$("#instockproductid"+i).attr('id','instockproductid'+eval(i-1));
					$("#productid"+i).attr('id','productid'+eval(i-1));
					$("#qty_case"+i).attr('id','qty_case'+eval(i-1));
					$("#qty_bottle"+i).attr('id','qty_bottle'+eval(i-1));	
					$("#rowid"+i).html(addremovelink);	
					$("#rowid"+i).attr('id','rowid'+eval(i-1));						
				}
						
			}
			
			var id = $(totalRowIdname).val();
			id = parseInt(id) - 1;
			$(totalRowIdname).val(id);
		
	}
	if(actionType == "edit")
	{
		if(!confirm('Action will delete the row!\nAre you sure?')) return false;			
				if(actionFor=="product")
				{
					delrowid = $("#transactioninfoids"+rowId).val();
				}				
		//alert(delrowid);
		$.ajax({
			url: base_url+"warehouse/removecommonrow",
			data: {'task': actionFor, 'rowid': delrowid},
			type: "post",

			beforeSend: function() {
				//$("#row"+rowId).html('<img src="'+base_url+'assets/images/loader.gif" width="40" style="margin-left: 141px; margin-top: 11px;" />');
			},
			success: function(data){
				var msg = data.trim();
				//alert(msg);
				if(msg=="success")
				{					
					totalRow = $(totalRowIdname).val();
					
					for(i=eval(rowId+1); i<=totalRow; i++)
					{
						if(actionFor=="product")
						{	
							addremovelink = '<a class="btn btn-danger text-white" style="cursor:pointer" onclick="return removerow('+eval(i-1)+',\'product\',\'add\',\''+base_url+'\')">x</a>';
							$("#productrow_"+i).attr('id','productrow_'+eval(i-1));
							$("#instockproductid"+i).attr('id','instockproductid'+eval(i-1));
							$("#productid"+i).attr('id','productid'+eval(i-1));
							$("#qty_case"+i).attr('id','qty_case'+eval(i-1));
							$("#qty_bottle"+i).attr('id','qty_bottle'+eval(i-1));
							$("#rowid"+i).html(addremovelink);	
							$("#rowid"+i).attr('id','rowid'+eval(i-1));								
						}
					}					
					setTimeout(function(){ 
						$(removerowId).remove();
						var id = $(totalRowIdname).val();
						id = parseInt(id) - 1;
						$(totalRowIdname).val(id);
			
					}, 500);
					
				}
			}
		});
	}
	calctotalquantity();
	
	
}


function checkQtyRCVD(indexno)
{
	//alert(indexno);
	 total_qty =0;
	 instock = parseFloat(instock);
	 var qty_case = $("#qty_case"+indexno).val();	
	 qty_case = parseFloat(qty_case);

	prodval = $("#productid"+indexno).val();	
	var proddata = prodval.split("_");
	var noofbottlesincase = proddata[2];	
	noofbottlesincase = parseFloat(noofbottlesincase);
	var instock = proddata[1];
	//alert(noofbottlesincase);
	var qty_bottle = $("#qty_bottle"+indexno).val();	
	qty_bottle = parseFloat(qty_bottle);
	if(qty_case>0)
	{
		if(noofbottlesincase>0)
		{
			total_qty = (qty_case*noofbottlesincase);
		}
		else
		{
			total_qty = qty_case;
		}
	}
	if(qty_bottle>0)
	{
		total_qty = total_qty+qty_bottle;
	}
	
	calctotalquantity();
	
	//total_qty = (qty_bottle+qty_case);
	//alert(total_qty);
	if(instock<total_qty)
	{
		$("#frmerrormsg").html('Quantity should not exceed Instock');
		$("#frmerrormsg").addClass('alert alert-danger');
		setTimeout(function(){
		$("#frmerrormsg").removeClass('alert alert-danger');			
		$("#frmerrormsg").html("");
		},4000);
		//alert(checkrqty);
		//$("#qtymsg"+indexno).html('Quantity should not exceed Instock');
		//$("#qty_caseemsg"+indexno).addClass('alert alert-danger');
		$('#qty_case'+indexno).css('border-color', 'red');
		$('#qty_bottle'+indexno).css('border-color', 'red');
		setTimeout(function(){
			//$("#qty_caseemsg"+indexno).removeClass('alert alert-danger');			
			//$("#qtymsg"+indexno).html("");
			$('#qty_case'+indexno).css('border-color', '');
			$('#qty_bottle'+indexno).css('border-color', '');
		},4000);
		$("#qty_case"+indexno).val(0);
		$("#qty_bottle"+indexno).val(0);
		return false;
	}
	else
	{
		return true;
	}
}

function calctotalquantity()
{
	// calc total
	var totalrows = $("#producttotalrows").val();
	totalrows = parseInt(totalrows);
	var totalcases = 0;
	var totalbottles = 0;

	for(ix=1;ix<=totalrows;ix++)
	{
		var qty_case = $("#qty_case"+ix).val();	
		qty_case = parseInt(qty_case);
		if(qty_case>0)
		{
			totalcases = totalcases + qty_case;
		}
		var qty_bottle = $("#qty_bottle"+ix).val();	
		qty_bottle = parseInt(qty_bottle);
		if(qty_bottle>0)
		{
			totalbottles = totalbottles + qty_bottle;
		}
	}
	$("#totalcasesid").html("<strong>TOTAL CASES: " + totalcases + "</strong>");
	$("#totalbottlesid").html("<strong>TOTAL BOTTLES: " + totalbottles + "</strong>");
	// end of calc total
}

/*
function validateFrm()
{
	
		erroralert = 1;
		var producttotalrows = $("#producttotalrows").val();
		for(c=1; c<=producttotalrows; c++)
		{
			var qty_case = $("#qty_case"+c).val();	
			qty_case = parseFloat(qty_case);
			var qty_bottle = $("#qty_bottle"+c).val();	
			qty_bottle = parseFloat(qty_bottle);
			if(qty_case>0)
			{
			
				erroralert = 0;
			}
			if(qty_bottle>0)
			{
			
				erroralert = 0;
			}
			
		}
		//alert(erroralert);
		if(erroralert==1)
		{			
			errorvalmsg ='Please enter qty greater then 0';
			$("#frmerrormsg").html(errorvalmsg);
			$("#frmerrormsg").css('color', 'red');
			$("#frmerrormsg").css('border-color', 'red');
			setTimeout(function(){
			$("#frmerrormsg").html('');
			$("#frmerrormsg").css('color', '');
			$("#frmerrormsg").css('border-color', '');
			},4000);
			alert(errorvalmsg);
		
	
			
			return false;
		}


}*/
</script>
