<!DOCTYPE html>
<?php
require_once('../Db/dbconfig.php');
@$userid=$_GET['userid'];
@$multipleraw=$_GET['multipleraw'];
?>
<html>
<head>
<link href="../css/styles.css" rel="stylesheet" />
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.4/css/jquery.dataTables.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.10.4/js/jquery.dataTables.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
<script src="https://kit.fontawesome.com/c17eae44a3.js" crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.1/css/bootstrap-select.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.1/js/bootstrap-select.min.js"></script>

<style type="text/css">
select.rou{
 border: 1px solid #ccc;
  -moz-border-radius: 10px;
-webkit-border-radius: 10px;
border-radius: 10px;

-moz-box-shadow: 2px 2px 3px #666;
-webkit-box-shadow: 2px 2px 3px #666;
box-shadow: 2px 2px 3px #666;
font-size: 18px;
padding: 4px 7px;
outline: 0;
-webkit-appearance: none;
}
#round{
 border: 1px solid #ccc;
 -moz-border-radius: 10px;
 -webkit-border-radius: 10px;
 border-radius: 10px;
	
 -moz-box-shadow: 2px 2px 3px #666;
 -webkit-box-shadow: 2px 2px 3px #666;
 box-shadow: 2px 2px 3px #666;
 font-size: 15px;
 padding: 4px 7px;
 outline: 0;
 -webkit-appearance: none;
}
</style>
</head>
<body>
<div class="page-header">
  <h3 class="page-title"  >
    <span class="page-title-icon bg-gradient-primary text-white mr-2">
    <i class="fas fa-cart-arrow-down fa-xs" style="color: black"></i>
    </span><b>Multiple Product Send To Stock</b></h3>
</div>
 <div class="card-body" style="background-color:#F0FFFF;overflow: auto;">
 <form action="" method="post" enctype='multipart/form-data' id="packageForm">
<table id="item_table" class="table table-condensed">
<tr id="row0">
	<td>
		<div class="form-group">
		    <label  style="width:120px;"for="finalProdct"><b>Final Product:</b></label>
		    <input style="width:200px;" type="text" class="rounded" id="finalProdctVal0" name="finalProdctVal[]" readonly required>
		    <input type="hidden" class="rounded" style="width:100px;"  id="adminId0" name="adminId[]">
			<input type="hidden" class="rounded" style="width:100px;"  id="is_single0" name="is_single[]">
			<button id="opentablbtn0" onclick="openTableM(0)" type="button" class="btn btn-primary" data-toggle="tooltip" data-placement="bottom" title="Add Final Product" style="background-color: #b134eb;"><i class="ace-icon fa fa-plus bigger-130"></i></button>
		</div>
	</td>
	<td>
		<div class="form-group">
		    <label><b>Total Quantity : </b></label>
		    <input type="text" style="width:100px;" class="rounded" id="totalQty0" disabled>
		    <label id="totalQtyType0"></label>
			<input type="hidden" class="rounded" style="width:100px;"  id="qty0" name="qty[]" readonly>
			<input type="hidden" class="rounded" style="width:100px;"  id="sqty0" name="sqty[]" readonly>
			<input type="hidden" class="rounded" style="width:100px;"  id="wqty0" name="wqty[]" readonly>
			<input type="hidden" class="rounded" style="width:100px;"  id="qtytypeId0" readonly>
		</div>
	</td>
	<td>
		<div class="form-group" id="qty110">
			<div class="row" style="margin-left: 0 !important;">
			<label style="width:116px;" for="qty"><b>Input Quantity:</b></label>
		    <input type="text" style="width:120px;" maxlength="6" class="rounded" id="ko0" pattern="^(0|[1-9][0-9]*)$" title="Enter a Valid Input" value="0"><label>Kilo</label>
		    <input type="text" style="width:100px;" maxlength="3" class="rounded" id="gr0" pattern="^(0|[1-9][0-9]*)$" value ="0"><label>gram</label>
			</div>
		</div>
		<div class="form-group" id="qty120" style="display:none;">
			<label style="width:116px;" for="qty"><b>Input Quantity:</b></label>
			<input type="text" style="width:150px;" maxlength="6" class="rounded" id="piec0" pattern="^[0-9]+(\.[0-9]{1,4})?$" title="Enter a Valid Input" value="0"><label>Pieces</label>
		</div>
		<div class="form-group" id="qty130" style="display:none;">
			<label style="width:116px;" for="qty"><b>Input Quantity:</b></label>
			<div class="row" style="margin-left: 0 !important;">
			<input type="text" style="width:120px;" maxlength="6" class="rounded" id="litr0" pattern="^(0|[1-9][0-9]*)$" title="Enter a Valid Input" value="0"><label>Litre</label>
			<input type="text" style="width:100px;" maxlength="3" class="rounded" id="mltr0" pattern="^(0|[1-9][0-9]*)$" value ="0">ml
			</div>
		</div>
		<div class="form-group" id="qty140" style="display:none;">
			<label style="width:116px;" for="qty"><b>Input Quantity:</b></label>
			<input type="text" style="width:150px;" maxlength="6" class="rounded" id="mtr0" pattern="^[0-9]+(\.[0-9]{1,4})?$" title="Enter a Valid Input" value="0"><label>Meter</label>
		</div>
		<div class="form-group" id="qty150" style="display:none;">
			<label style="width:116px;" for="qty"><b>Input Quantity:</b></label>
			<input type="text" style="width:150px;" maxlength="6" class="rounded" id="ft0" pattern="^[0-9]+(\.[0-9]{1,4})?$" title="Enter a Valid Input" value="0"><label>Feet</label>
		</div>
	</td>
	<td>
		<div class="form-group" id="qty210">
			<div class="row" style="margin-left: 0 !important;">
			<label style="width:132px;" for="qty"><b>Per Box Quantity:</b></label>
		    <input type="text" style="width:120px;" maxlength="6" class="rounded" id="pko0" pattern="^(0|[1-9][0-9]*)$" title="Enter a Valid Input" value="0"><label>Kilo</label>
		    <input type="text" style="width:100px;" maxlength="3" class="rounded" id="pgr0" pattern="^(0|[1-9][0-9]*)$" value ="0"><label>gram</label>
			</div>
		</div>
		<div class="form-group" id="qty220" style="display:none;">
			<label style="width:132px;" for="qty"><b>Per Box Quantity:</b></label>
			<input type="text" style="width:150px;" maxlength="6" class="rounded" id="ppiec0" pattern="^[0-9]+(\.[0-9]{1,4})?$" title="Enter a Valid Input" value="0"><label>Pieces</label>
		</div>
		<div class="form-group" id="qty230" style="display:none;">
			<label style="width:132px;" for="qty"><b>Per Box Quantity:</b></label>
			<div class="row" style="margin-left: 0 !important;">
			<input type="text" style="width:120px;" maxlength="6" class="rounded" id="plitr0" pattern="^(0|[1-9][0-9]*)$" title="Enter a Valid Input" value="0"><label>Litre</label>
			<input type="text" style="width:100px;" maxlength="3" class="rounded" id="pmltr0" pattern="^(0|[1-9][0-9]*)$" value ="0">ml
			</div>
		</div>
		<div class="form-group" id="qty240" style="display:none;">
			<label style="width:132px;" for="qty"><b>Per Box Quantity:</b></label>
			<input type="text" style="width:150px;" maxlength="6" class="rounded" id="pmtr0" pattern="^[0-9]+(\.[0-9]{1,4})?$" title="Enter a Valid Input" value="0"><label>Meter</label>
		</div>
		<div class="form-group" id="qty250" style="display:none;">
			<label style="width:132px;" for="qty"><b>Per Box Quantity:</b></label>
			<input type="text" style="width:150px;" maxlength="6" class="rounded" id="pft0" pattern="^[0-9]+(\.[0-9]{1,4})?$" title="Enter a Valid Input" value="0"><label>Feet</label>
		</div>
	</td>
	<td>
		<div class="form-group" id="qty310">
			<div class="row" style="margin-left: 0 !important;">
			<label style="width:121px;" for="qty"><b>Waste Quantity:</b></label>
		    <input type="text" style="width:120px;" maxlength="6" class="rounded" id="wko0" pattern="^(0|[1-9][0-9]*)$" title="Enter a Valid Input" value="0"><label>Kilo</label>
		    <input type="text" style="width:100px;" maxlength="3" class="rounded" id="wgr0" pattern="^(0|[1-9][0-9]*)$" value ="0"><label>gram</label>
			</div>
		</div>
		<div class="form-group" id="qty320" style="display:none;">
			<label style="width:121px;" for="qty"><b>Waste Quantity:</b></label>
			<input type="text" style="width:150px;" maxlength="6" class="rounded" id="wpiec0" pattern="^[0-9]+(\.[0-9]{1,4})?$" title="Enter a Valid Input" value="0"><label>Pieces</label>
		</div>
		<div class="form-group" id="qty330" style="display:none;">
			<label style="width:121px;" for="qty"><b>Waste Quantity:</b></label>
			<div class="row" style="margin-left: 0 !important;">
			<input type="text" style="width:120px;" maxlength="6" class="rounded" id="wlitr0" pattern="^(0|[1-9][0-9]*)$" title="Enter a Valid Input" value="0"><label>Litre</label>
			<input type="text" style="width:100px;" maxlength="3" class="rounded" id="wmltr0" pattern="^(0|[1-9][0-9]*)$" value ="0">ml
			</div>
		</div>
		<div class="form-group" id="qty340" style="display:none;">
			<label style="width:121px;" for="qty"><b>Waste Quantity:</b></label>
			<input type="text" style="width:150px;" maxlength="6" class="rounded" id="wmtr0" pattern="^[0-9]+(\.[0-9]{1,4})?$" title="Enter a Valid Input" value="0"><label>Meter</label>
		</div>
		<div class="form-group" id="qty350" style="display:none;">
			<label style="width:121px;" for="qty"><b>Waste Quantity:</b></label>
			<input type="text" style="width:150px;" maxlength="6" class="rounded" id="wft0" pattern="^[0-9]+(\.[0-9]{1,4})?$" title="Enter a Valid Input" value="0"><label>Feet</label>
		</div>
	</td>
	<td>
		<div class="form-group">
			<label style="width:105px;" for="qty"><b>No. of Boxes :</b></label>
			<input type="text" style="width:150px;" maxlength="6" class="rounded" id="packaging_qt0" name="packaging_qt[]" pattern="^(0|[1-9][0-9]*)$" value ="0">
		</div>
	</td>
	<td>
		<div class="form-group">
			<input type="hidden" id="wastedpt0" name="wastedpt[]">
			<label style="width:122px;" for="qty"><b>Send Rejection To Department :</b></label>
			 <select style="width:170px;" id="wastedptS0" class="rou" required>
	      	 <option value="0" disabled selected>Please select....</option>
	        <?php 
	        $sql1="select * from department where id not in (2,3,5)";
					
					$res=mysqli_query($con,$sql1);
				while($row1 = mysqli_fetch_array($res))
				{
		        	
			?>
			<option value="<?php echo $row1['id']; ?>"><?php echo $row1['depart']; ?></option> 
			<?php
	        	
				}
			?>
	        </select>
		</div>
	</td>
	<td><button type="button" name="addpp" id="addpp" class="btn btn-success" style="margin-top: 25%;">Add More</button></td>
	
</tr>
</table>
    <button type="submit"  class="btn btn-primary" id = "packageSubmit" name="submit">Submit</button>
    <!-- <button class="btn btn-danger">Cancel</button> -->
</form>
</div>

<!-- Add Table Modal -->
<div id="tableModal" class="modal fade" role="dialog" tabindex="-1" aria-hidden="true" style="overflow: auto;text-align: center;"> 
  <div class="modal-dialog" style="text-align: left; max-width: 100%;width: auto !important; display: inline-block;">
    <!-- Modal content-->
    <div class="modal-content">
      <div class="modal-header">
         <h4 class="modal-title">Select Final Product</h4>
		 <button type="button" class="close" data-dismiss="modal">&times;</button>
       	<input type="hidden" id="maintablerow" readonly>
      </div>
      <div class="modal-body">
       	<table id="datatableid" class="table table-striped table-bordered table-hover">
			<thead class="thead-dark">
				<tr style="background-color:#048065">
					<th class="center">
						
					</th>
					<th>Sr. No</th>
					<th>Sent From</th>
					<th>Final Product</th>
					<th>Quantity</th>	
					<th>Quantity Type</th>
					<th>Sent DateTime</th>
					<th>Select</th>
					<th style="display: none;"></th>
					<th style="display: none;"></th>
					<th style="display: none;"></th>
					
				</tr>
			</thead>
			<tbody>
			<?php 
				
				$sql = "SELECT '1' AS is_single, ad.id as ids,frmd.depart AS frmdpt,p.item AS finalProdname,p.id AS finalprodID, sendqt.q_name,sendqt.id AS qttypeId, ad.lotnumber, ad.productItem_id, ad.send_to_quantity AS send_to_quantity,
						ad.created_at AS senddttime, ad.water_wt AS water_wt, ad.final_product
						FROM admin_dpts ad ,department frmd,final_product p ,quantity_type sendqt
						WHERE ad.send_from = frmd.id AND ad.final_product = p.id AND ad.send_to_qtny_type = sendqt.id AND ad.send_to = 2 AND ad.send_to_quantity > 0 group by ad.lotnumber 
						UNION
						SELECT '0' AS is_single, ad.id as ids,frmd.depart AS frmdpt,p.item AS finalProdname,p.id AS finalprodID, sendqt.q_name,sendqt.id AS qttypeId, ad.lotnumber, GROUP_CONCAT(distinct(admrc.productItem_id) SEPARATOR ',') as productItem_id, ad.send_to_quantity AS send_to_quantity,
						ad.created_at AS senddttime, admrc.water_wt AS water_wt, ad.final_product
						FROM admin_dpts_mul_raw ad ,department frmd,final_product p ,quantity_type sendqt,admin_dpts_mul_raw_child admrc 
						WHERE ad.send_from = frmd.id AND ad.final_product = p.id AND ad.send_to_qtny_type = sendqt.id and ad.lotnumber = admrc.lotnumber AND ad.send_to = 2 AND ad.send_to_quantity > 0 group by p.id,ad.lotnumber";
					
				$result = $con->query($sql);

				if ($result->num_rows > 0) 
				{
				    // output data of each row
		    		while($row = $result->fetch_assoc()) 
		    		{
			?>
			<tr style="background-color:#AFF3CA" id="t<?php echo $row['ids'];?>">
				<td class="center">
					
					<p style="display: none"><?php echo $row['ids'];?></p>
				</td>
				<td>
					<p><?php 
					if($row['is_single'] == '1'){
						echo $row['ids']."-S";
					}else{
						echo $row['ids']."-M";
					}
					?></p>
				</td>
				<td>
					<p><?php echo $row['frmdpt'];?></p>
				</td>
				<td>
					<p><?php echo $row['finalProdname'];?></p>
				</td>
				<td>
					<p><?php 

					if($row['qttypeId'] == '1' or $row['qttypeId'] == '3'){
						if($row['send_to_quantity'] != 0){
							echo ($row['send_to_quantity']/1000);
						}else{
							echo $row['send_to_quantity'];
						}
					}else{
						echo $row['send_to_quantity'];
					}
					?>
					</p>
				</td>
				<td>
					<p><?php echo $row['q_name'];?></p>
				</td>
				<td>
					<p><?php 
						$date = new DateTime($row['senddttime'], new DateTimeZone('MST'));
						$date->setTimezone(new DateTimeZone('Asia/Kolkata'));
						echo $date->format('Y-m-d H:i:s');
					?></p>
				</td>
				<td>
					<button type="button" class="btn btn-primary sendbtn"><i class="ace-icon fa fa-check bigger-130"></i></button>
				</td>
				<td style="display: none;"><?php echo $row['finalprodID'];?></td>
				<td style="display: none;"><?php echo $row['qttypeId'];?></td>
				<td style="display: none;"><?php echo $row['is_single'];?></td>
			</tr>
			<?php
					}
				}

			?>
			</tbody>
		</table>
	  </div>
      <div class="modal-footer">
       
      </div>
    </div>

  </div>
</div>

</body>

<script>
$(document).ready(function(){
	var userid = '<?php echo @$userid; ?>';
	
	var userid = '<?php echo @$userid; ?>';
	var t = $('#datatableid').DataTable( {
	rowReorder: true,
	"order": [[ 6, "desc" ]],
	columnDefs: [
	    { orderable: true, targets: '_all' }
	    
	]
	} );

	addMoreItems(t);

	$('.addpurchaser').on('click',function() {
			
		$('#add_sup').modal('show');
	});

	$('#datatableid').on('click','.sendbtn',function() {
		
		$tr = $(this).closest('tr');

		var data = $tr.children('td').map(function(){
			return $(this).text();
		}).get();

		var mainrowId = $('#maintablerow').val();
		if($('#adminId'+mainrowId).val() !=''){
			console.log('adminId',$('#adminId'+mainrowId).val());
			var tablerow = document.getElementById('t'+$('#adminId'+mainrowId).val());
			if(!$('#t'+$('#adminId'+mainrowId).val()).is(':visible')){
				tablerow.style.display = "revert";
			}
			
		}

		$('#adminId'+mainrowId).val(data[0].trim());
		$('#finalProdctVal'+mainrowId).val(data[3].trim());
		
		$('#totalQty'+mainrowId).val(data[4].trim());

		$('#totalQtyType'+mainrowId).html(data[5].trim());
		
		$('#qtytypeId'+mainrowId).val(data[9].trim());
		$('#is_single'+mainrowId).val(data[10].trim());
		
		changefunc(mainrowId,1);
		changefunc(mainrowId,2);
		changefunc(mainrowId,3);
		$('#tableModal').modal('hide');	

	});

	$("#packageForm").submit(function(e) {
    document.getElementById("packageSubmit").disabled=true;
    //prevent Default functionality
    e.preventDefault();
    //do your own request an handle the results

    var totalBoxes = 0;
    var totalsendngQty = 0;

	var rowid =$("#item_table").find("tr").last().attr('id').replace("row", "");
	var selectedValue = $('#qtytypeId'+rowid).val();
	var totalqt  = $('#totalQty'+rowid).val();
	if(selectedValue == "1")
	{
		var kilogrm = (parseInt($('#ko'+rowid).val()) * 1000)+parseInt($('#gr'+rowid).val());
		$('#qty'+rowid).val(kilogrm);
		totalqt = totalqt * 1000;

		var pkilogrm = (parseInt($('#pko'+rowid).val()) * 1000)+parseInt($('#pgr'+rowid).val());
		$('#sqty'+rowid).val(pkilogrm);

		var wkilogrm = (parseInt($('#wko'+rowid).val()) * 1000)+parseInt($('#wgr'+rowid).val());
		$('#wqty'+rowid).val(wkilogrm);
	}else if(selectedValue == "3")
	{
		var milliltr = (parseInt($('#litr'+rowid).val()) * 1000)+parseInt($('#mltr'+rowid).val());
		$('#qty'+rowid).val(milliltr);
		totalqt = totalqt * 1000;

		var pmilliltr = (parseInt($('#plitr'+rowid).val()) * 1000)+parseInt($('#pmltr'+rowid).val());
		$('#sqty'+rowid).val(pmilliltr);

		var wmilliltr = (parseInt($('#wlitr'+rowid).val()) * 1000)+parseInt($('#wmltr'+rowid).val());
		$('#wqty'+rowid).val(wmilliltr);
	}else if(selectedValue == "2")
	{
		$('#qty'+rowid).val($('#piec'+rowid).val());
		$('#sqty'+rowid).val($('#ppiec'+rowid).val());
		$('#wqty'+rowid).val($('#wpiec'+rowid).val());
	}else if(selectedValue == "4")
	{
		$('#qty'+rowid).val($('#mtr'+rowid).val());
		$('#sqty'+rowid).val($('#pmtr'+rowid).val());
		$('#wqty'+rowid).val($('#wmtr'+rowid).val());
	}else if(selectedValue == "5")
	{
		$('#qty'+rowid).val($('#ft'+rowid).val());
		$('#sqty'+rowid).val($('#pft'+rowid).val());
		$('#wqty'+rowid).val($('#wft'+rowid).val());
	}

	var totalsendngQty = parseFloat($('#qty'+rowid).val());
	if(totalsendngQty > totalqt){
		alert('Sending Quantity cannot exceed Total Quantity');
		document.getElementById("packageSubmit").disabled=false;
	}else if(totalsendngQty == 0 || isNaN(totalsendngQty)){
		alert('Input Quantity cannot be 0 or Empty');
		document.getElementById("packageSubmit").disabled=false;
	}else if(parseFloat($('#sqty'+rowid).val()) == 0){
		alert('Sending Quantity cannot be 0');
		document.getElementById("packageSubmit").disabled=false;
	}else if(parseFloat($('#packaging_qt'+rowid).val()) == 0){
		alert('Boxes cannot be 0');
		document.getElementById("packageSubmit").disabled=false;
	}else if(parseFloat($('#wqty'+rowid).val()) != 0 && $('#wastedpt'+rowid).val() == null){
		alert('Please Select a department to send rejected quantity');
		document.getElementById("packageSubmit").disabled=false;
	}else if((parseFloat($('#sqty'+rowid).val()) * parseFloat($('#packaging_qt'+rowid).val())) > totalsendngQty){
		alert('Total Quantity in boxes cannot exceed input quantity');
		document.getElementById("packageSubmit").disabled=false;
	}else if(((parseFloat($('#sqty'+rowid).val()) * parseFloat($('#packaging_qt'+rowid).val()))+ parseFloat($('#wqty'+rowid).val())) > totalsendngQty){
		alert('Overall Quantity cannot exceed input quantity');
		document.getElementById("packageSubmit").disabled=false;
	}else{
		$('#wastedpt'+rowid).val($('#wastedptS'+rowid).val());
		var formData = new FormData(this);
		formData.append('type','multiPackageSendToStock');
		formData.append('userId',userid);

		var url='../controller/admin_controller.php'
		
	     $.ajax( {
	        url: url,
	        type: 'POST',
	        data: formData,
	        processData: false,
	        contentType: false,

	        success: function(data){
	          console.log('Msg',data);
	          if(data.status == true){
		        	alert(data.msg); 
		       	 window.location.reload();
	      	  }else{
	      	  	alert(data.msg); 
	      	  	document.getElementById("packageSubmit").disabled=false;
	      	  	window.location.reload();
	      	  }
	        },
	        error: function(r) {
	          alert('Unable to Add Items'); 
	          document.getElementById("packageSubmit").disabled=false;
	          window.location.reload();
	        }
	      } );
	}
   	
	});

});


function openTableM(rowid){
	$('#maintablerow').val(rowid);
	$('#tableModal').modal('show');

}

function changefunc(rowid,divNum) {
	console.log('RowId',rowid);
	
	var selectedValue = $('#qtytypeId'+rowid).val();
	console.log('RowId',selectedValue);
	if(selectedValue == "1")
	{
		$('#qty'+divNum+'1'+rowid).show();
		$('#qty'+divNum+'2'+rowid).hide();
		$('#qty'+divNum+'3'+rowid).hide();
		$('#qty'+divNum+'4'+rowid).hide();
		$('#qty'+divNum+'5'+rowid).hide();
		
	}else if(selectedValue == "2")
	{
		$('#qty'+divNum+'2'+rowid).show();
		$('#qty'+divNum+'1'+rowid).hide();
		$('#qty'+divNum+'3'+rowid).hide();
		$('#qty'+divNum+'4'+rowid).hide();
		$('#qty'+divNum+'5'+rowid).hide();
		
	}else if(selectedValue == "4")
	{
		$('#qty'+divNum+'2'+rowid).hide();
		$('#qty'+divNum+'1'+rowid).hide();
		$('#qty'+divNum+'3'+rowid).hide();
		$('#qty'+divNum+'4'+rowid).show();
		$('#qty'+divNum+'5'+rowid).hide();
		
	}else if(selectedValue == "5")
	{
		$('#qty'+divNum+'2'+rowid).hide();
		$('#qty'+divNum+'1'+rowid).hide();
		$('#qty'+divNum+'3'+rowid).hide();
		$('#qty'+divNum+'4'+rowid).hide();
		$('#qty'+divNum+'5'+rowid).show();
		
	}else
	{
		$('#qty'+divNum+'3'+rowid).show();
		$('#qty'+divNum+'1'+rowid).hide();
		$('#qty'+divNum+'2'+rowid).hide();
		$('#qty'+divNum+'4'+rowid).hide();
		$('#qty'+divNum+'5'+rowid).hide();
		
	}
}

function disableDivs(rowid,divNum) {
	console.log('disableRowId',rowid);
	
	var selectedValue = $('#qtytypeId'+rowid).val();
	
	if(selectedValue == "1")
	{
		console.log('selectedValue',selectedValue);
		$('#qty'+divNum+'1'+rowid).find('*').prop('disabled',true);
		
	}else if(selectedValue == "2")
	{
		$('#qty'+divNum+'2'+rowid).children().prop('disabled',true);
	}else if(selectedValue == "4")
	{
		$('#qty'+divNum+'4'+rowid).children().prop('disabled',true);
	}else if(selectedValue == "5")
	{
		$('#qty'+divNum+'5'+rowid).children().prop('disabled',true);
	}else
	{
		$('#qty'+divNum+'3'+rowid).find('*').prop('disabled',true);
	}

	$('#packaging_qt'+rowid).prop('readonly',true);
	document.getElementById('wastedptS'+rowid).disabled = true;
}

function enableDivs(rowid,divNum) {
	console.log('enableRowId',rowid);
	
	var selectedValue = $('#qtytypeId'+rowid).val();
	
	if(selectedValue == "1")
	{
		$('#qty'+divNum+'1'+rowid).find('*').prop('disabled',false);
		
	}else if(selectedValue == "2")
	{
		$('#qty'+divNum+'2'+rowid).children().prop('disabled',false);
	}else if(selectedValue == "4")
	{
		$('#qty'+divNum+'4'+rowid).children().prop('disabled',false);
	}else if(selectedValue == "5")
	{
		$('#qty'+divNum+'5'+rowid).children().prop('disabled',false);
	}else
	{
		$('#qty'+divNum+'3'+rowid).find('*').prop('disabled',false);
	}

	$('#packaging_qt'+rowid).prop('readonly',false);
	document.getElementById('wastedptS'+rowid).disabled = false;

}

function clearForm(formname){
	$("#"+formname).trigger("reset");

	if(formname == 'user_form'){
		$('#mesg').text('');
		$('#add_product').show();
	}else if(formname == 'user_form2'){
		$('#mesg2').text('');
		$('#productype').show();
	}
}

function addMoreItems(table){
	var i=1;
	$('#addpp').click(function(){
		var rowid =$("#item_table").find("tr").last().attr('id').replace("row", "");
		if($('#totalQty'+rowid).val() ==''){
			alert('First please select a final product to add more');
		}else{
			var totalqt  = $('#totalQty'+rowid).val();
			var selectedValue = $('#qtytypeId'+rowid).val();

			if(selectedValue == "1")
			{
				var kilogrm = (parseInt($('#ko'+rowid).val()) * 1000)+parseInt($('#gr'+rowid).val());
				$('#qty'+rowid).val(kilogrm);
				totalqt = totalqt * 1000;

				var pkilogrm = (parseInt($('#pko'+rowid).val()) * 1000)+parseInt($('#pgr'+rowid).val());
				$('#sqty'+rowid).val(pkilogrm);

				var wkilogrm = (parseInt($('#wko'+rowid).val()) * 1000)+parseInt($('#wgr'+rowid).val());
				$('#wqty'+rowid).val(wkilogrm);
			}else if(selectedValue == "3")
			{
				var milliltr = (parseInt($('#litr'+rowid).val()) * 1000)+parseInt($('#mltr'+rowid).val());
				$('#qty'+rowid).val(milliltr);
				totalqt = totalqt * 1000;

				var pmilliltr = (parseInt($('#plitr'+rowid).val()) * 1000)+parseInt($('#pmltr'+rowid).val());
				$('#sqty'+rowid).val(pmilliltr);

				var wmilliltr = (parseInt($('#wlitr'+rowid).val()) * 1000)+parseInt($('#wmltr'+rowid).val());
				$('#wqty'+rowid).val(wmilliltr);
			}else if(selectedValue == "2")
			{
				$('#qty'+rowid).val($('#piec'+rowid).val());
				$('#sqty'+rowid).val($('#ppiec'+rowid).val());
				$('#wqty'+rowid).val($('#wpiec'+rowid).val());
			}else if(selectedValue == "4")
			{
				$('#qty'+rowid).val($('#mtr'+rowid).val());
				$('#sqty'+rowid).val($('#pmtr'+rowid).val());
				$('#wqty'+rowid).val($('#wmtr'+rowid).val());
			}else if(selectedValue == "5")
			{
				$('#qty'+rowid).val($('#ft'+rowid).val());
				$('#sqty'+rowid).val($('#pft'+rowid).val());
				$('#wqty'+rowid).val($('#wft'+rowid).val());
			}

			var totalsendngQty = parseFloat($('#qty'+rowid).val());
			
			console.log('Sending Qty',totalsendngQty);
			if(totalsendngQty > totalqt){
				alert('Sending Quantity cannot exceed Total Quantity');
				console.log('kilogram',totalsendngQty);
				console.log('totalqt',totalqt);
			}else if(totalsendngQty == 0 || isNaN(totalsendngQty)){
				alert('Input Quantity cannot be 0 or Empty');
			}else if(parseFloat($('#sqty'+rowid).val()) == 0){
				alert('Sending Quantity cannot be 0');
			}else if(parseFloat($('#packaging_qt'+rowid).val()) == 0){
				alert('Boxes cannot be 0');
			}else if(parseFloat($('#wqty'+rowid).val()) != 0 && $('#wastedptS'+rowid).val() == null){
				alert('Please Select a department to send rejected quantity');
			}else if((parseFloat($('#sqty'+rowid).val()) * parseFloat($('#packaging_qt'+rowid).val())) > totalsendngQty){
				alert('Total Quantity in boxes cannot exceed input quantity');
			}else if(((parseFloat($('#sqty'+rowid).val()) * parseFloat($('#packaging_qt'+rowid).val()))+ parseFloat($('#wqty'+rowid).val())) > totalsendngQty){
				alert('Overall Quantity cannot exceed input quantity');
			}else{
				$('#wastedpt'+rowid).val($('#wastedptS'+rowid).val());
				var tablerow = document.getElementById('t'+$('#adminId'+rowid).val())
				if(tablerow != null){
					tablerow.style.display ="none";
				}
				i++;                                                
				$('#item_table').append('<tr id="row'+i+'"><td><div class="form-group"> <label style="width:120px;"for="finalProdct"><b>Final Product:</b></label> <input style="width:200px;" type="text" class="rounded" id="finalProdctVal'+i+'" name="finalProdctVal[]" readonly required> <input type="hidden" class="rounded" style="width:100px;" id="adminId'+i+'" name="adminId[]"><input type="hidden" class="rounded" style="width:100px;"  id="is_single'+i+'" name="is_single[]"><button id="opentablbtn'+i+'" onclick="openTableM('+i+')" type="button" class="btn btn-primary" data-toggle="tooltip" data-placement="bottom" title="Add Final Product" style="background-color: #b134eb;"><i class="ace-icon fa fa-plus bigger-130"></i></button></div></td><td><div class="form-group"> <label><b>Total Quantity : </b></label> <input type="text" style="width:100px;" class="rounded" id="totalQty'+i+'" disabled> <label id="totalQtyType'+i+'"></label><input type="hidden" class="rounded" style="width:100px;" id="qty'+i+'" name="qty[]" readonly><input type="hidden" class="rounded" style="width:100px;" id="qtytypeId'+i+'" readonly><input type="hidden" class="rounded" style="width:100px;"  id="sqty'+i+'" name="sqty[]" readonly><input type="hidden" class="rounded" style="width:100px;"  id="wqty'+i+'" name="wqty[]" readonly></div></td><td><div class="form-group" id="qty11'+i+'"><div class="row" style="margin-left: 0 !important;"><label style="width:116px;" for="qty"><b>Input Quantity:</b></label> <input type="text" style="width:120px;" maxlength="6" class="rounded" id="ko'+i+'" pattern="^(0|[1-9][0-9]*)$" title="Enter a Valid Input" value="0"><label>Kilo</label> <input type="text" style="width:100px;" maxlength="3" class="rounded" id="gr'+i+'" pattern="^(0|[1-9][0-9]*)$" value ="0"><label>gram</label></div></div><div class="form-group" id="qty12'+i+'" style="display:none;"><label style="width:116px;" for="qty"><b>Input Quantity:</b></label><input type="text" style="width:150px;" maxlength="6" class="rounded" id="piec'+i+'" pattern="^[0-9]+(\.[0-9]{1,4})?$" title="Enter a Valid Input" value="0"><label>Pieces</label></div><div class="form-group" id="qty13'+i+'" style="display:none;"><label style="width:116px;" for="qty"><b>Input Quantity:</b></label><div class="row" style="margin-left: 0 !important;"><input type="text" style="width:120px;" maxlength="6" class="rounded" id="litr'+i+'" pattern="^(0|[1-9][0-9]*)$" title="Enter a Valid Input" value="0"><label>Litre</label><input type="text" style="width:100px;" maxlength="3" class="rounded" id="mltr'+i+'" pattern="^(0|[1-9][0-9]*)$" value ="0">ml</div></div><div class="form-group" id="qty14'+i+'" style="display:none;"><label style="width:116px;" for="qty"><b>Input Quantity:</b></label><input type="text" style="width:150px;" maxlength="6" class="rounded" id="mtr'+i+'" pattern="^[0-9]+(\.[0-9]{1,4})?$" title="Enter a Valid Input" value="0"><label>Meter</label></div><div class="form-group" id="qty15'+i+'" style="display:none;"><label style="width:116px;" for="qty"><b>Input Quantity:</b></label><input type="text" style="width:150px;" maxlength="6" class="rounded" id="ft'+i+'" pattern="^[0-9]+(\.[0-9]{1,4})?$" title="Enter a Valid Input" value="0"><label>Feet</label></div></td><td><div class="form-group" id="qty21'+i+'"><div class="row" style="margin-left: 0 !important;"><label style="width:132px;" for="qty"><b>Per Box Quantity:</b></label> <input type="text" style="width:120px;" maxlength="6" class="rounded" id="pko'+i+'" pattern="^(0|[1-9][0-9]*)$" title="Enter a Valid Input" value="0"><label>Kilo</label> <input type="text" style="width:100px;" maxlength="3" class="rounded" id="pgr'+i+'" pattern="^(0|[1-9][0-9]*)$" value ="0"><label>gram</label></div></div><div class="form-group" id="qty22'+i+'" style="display:none;"><label style="width:132px;" for="qty"><b>Per Box Quantity:</b></label><input type="text" style="width:150px;" maxlength="6" class="rounded" id="ppiec'+i+'" pattern="^[0-9]+(\.[0-9]{1,4})?$" title="Enter a Valid Input" value="0"><label>Pieces</label></div><div class="form-group" id="qty23'+i+'" style="display:none;"><label style="width:132px;" for="qty"><b>Per Box Quantity:</b></label><div class="row" style="margin-left: 0 !important;"><input type="text" style="width:120px;" maxlength="6" class="rounded" id="plitr'+i+'" pattern="^(0|[1-9][0-9]*)$" title="Enter a Valid Input" value="0"><label>Litre</label><input type="text" style="width:100px;" maxlength="3" class="rounded" id="pmltr'+i+'" pattern="^(0|[1-9][0-9]*)$" value ="0">ml</div></div><div class="form-group" id="qty24'+i+'" style="display:none;"><label style="width:132px;" for="qty"><b>Per Box Quantity:</b></label><input type="text" style="width:150px;" maxlength="6" class="rounded" id="pmtr'+i+'" pattern="^[0-9]+(\.[0-9]{1,4})?$" title="Enter a Valid Input" value="0"><label>Meter</label></div><div class="form-group" id="qty25'+i+'" style="display:none;"><label style="width:132px;" for="qty"><b>Per Box Quantity:</b></label><input type="text" style="width:150px;" maxlength="6" class="rounded" id="pft'+i+'" pattern="^[0-9]+(\.[0-9]{1,4})?$" title="Enter a Valid Input" value="0"><label>Feet</label></div></td><td><div class="form-group" id="qty31'+i+'"><div class="row" style="margin-left: 0 !important;"><label style="width:121px;" for="qty"><b>Waste Quantity:</b></label> <input type="text" style="width:120px;" maxlength="6" class="rounded" id="wko'+i+'" pattern="^(0|[1-9][0-9]*)$" title="Enter a Valid Input" value="0"><label>Kilo</label> <input type="text" style="width:100px;" maxlength="3" class="rounded" id="wgr'+i+'" pattern="^(0|[1-9][0-9]*)$" value ="0"><label>gram</label></div></div><div class="form-group" id="qty32'+i+'" style="display:none;"><label style="width:121px;" for="qty"><b>Waste Quantity:</b></label><input type="text" style="width:150px;" maxlength="6" class="rounded" id="wpiec'+i+'" pattern="^[0-9]+(\.[0-9]{1,4})?$" title="Enter a Valid Input" value="0"><label>Pieces</label></div><div class="form-group" id="qty33'+i+'" style="display:none;"><label style="width:121px;" for="qty"><b>Waste Quantity:</b></label><div class="row" style="margin-left: 0 !important;"><input type="text" style="width:120px;" maxlength="6" class="rounded" id="wlitr'+i+'" pattern="^(0|[1-9][0-9]*)$" title="Enter a Valid Input" value="0"><label>Litre</label><input type="text" style="width:100px;" maxlength="3" class="rounded" id="wmltr'+i+'" pattern="^(0|[1-9][0-9]*)$" value ="0">ml</div></div><div class="form-group" id="qty34'+i+'" style="display:none;"><label style="width:121px;" for="qty"><b>Waste Quantity:</b></label><input type="text" style="width:150px;" maxlength="6" class="rounded" id="wmtr'+i+'" pattern="^[0-9]+(\.[0-9]{1,4})?$" title="Enter a Valid Input" value="0"><label>Meter</label></div><div class="form-group" id="qty35'+i+'" style="display:none;"><label style="width:121px;" for="qty"><b>Waste Quantity:</b></label><input type="text" style="width:150px;" maxlength="6" class="rounded" id="wft'+i+'" pattern="^[0-9]+(\.[0-9]{1,4})?$" title="Enter a Valid Input" value="0"><label>Feet</label></div></td><td><div class="form-group"><label style="width:105px;" for="qty"><b>No. of Boxes :</b></label><input type="text" style="width:150px;" maxlength="6" class="rounded" id="packaging_qt'+i+'" name="packaging_qt[]" pattern="^(0|[1-9][0-9]*)$" value ="0"></div></td><td><div class="form-group"><input type="hidden" id="wastedpt'+i+'" name="wastedpt[]"><label style="width:122px;" for="qty"><b>Send Rejection To Department :</b></label> <select style="width:170px;" id="wastedptS'+i+'" class="rou" required> </select></div></td><td><button name="remove" id="'+i+'" class="btn btn-danger btn_remove">X</button></td></tr>');

				document.getElementById('opentablbtn'+rowid).disabled = true;
				disableDivs(rowid,1);
				disableDivs(rowid,2);
				disableDivs(rowid,3);

				var $options = $("#wastedptS0 > option").clone();
    		$('#wastedptS'+i).empty();
    		$('#wastedptS'+i).append($options);
				
			}
			
		}
		 
	});
	$(document).on('click','.btn_remove',function(){
		var button_id=$(this).attr("id");

		var adminId ='t'+ $('#adminId'+button_id).val();
		var currentTotalQty = $('#totalQty'+button_id).val();
		$("#row"+button_id+"").remove();

		if(currentTotalQty !=''){
			var table = document.getElementById('item_table');

			var rowLength = table.rows.length;

			var isPresent = false;

			for(var i=0; i<rowLength; i+=1){
				var row = table.rows[i];

				var rowid = row.id.replace("row", "");
				
				if('t'+$('#adminId'+i).val() == adminId){
					isPresent =true;
					break;
				}
			}

			console.log('Ispresent',isPresent);
			if(!isPresent){
				document.getElementById(adminId).style.display ="revert";
			}
		}

		var lastrowid =$("#item_table").find("tr").last().attr('id').replace("row", "");
		
		enableDivs(lastrowid,1);
		enableDivs(lastrowid,2);
		enableDivs(lastrowid,3);
		document.getElementById('opentablbtn'+lastrowid).disabled = false;

		
		
	});
}

</script>
</html>