<!DOCTYPE html>
<?php
require_once('../Db/dbconfig.php');
@$name=$_GET['username'];
@$userid=$_GET['userid'];
?>
<html>
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.4/css/jquery.dataTables.min.css">
<script src="https://kit.fontawesome.com/c17eae44a3.js" crossorigin="anonymous"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.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://cdn.datatables.net/1.10.4/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/plug-ins/1.10.24/api/sum().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;
}

@media only screen and (max-height: 700px) {
	.child{
	  width:1000px;
	  float:left;
	  font-size:15px;
	  font-family:arial;
	  padding:10px;
	  cursor: pointer;
	}
}
</style>
</head>
<body>
<div class="card">
	<div class="page-header">
      <h3 class="page-title"  >
        <span class="page-title-icon bg-gradient-primary text-white mr-2">
          <i class="fas fa-trash fa-xs" style="color: black"></i>
        </span><b>F-39 Out</b></h3>
        <input type="hidden" id="username" value="<?php echo @$name;?>">
	</div>
	<div class="card-body child" style="overflow: auto;">
			<table id="datatableid" class="table table-striped table-bordered table-hover">
			<thead class="thead-dark">
				<tr style="background-color:#336699">
					<th>Sr. No</th>
					<th>Sent To</th>
					<th>Final Product</th>
					<th>Waste Type</th>
					<th>Quantity Type</th>
					<th>Quantity</th>	
					<th>Sent DateTime</th>
					
					
				</tr>
			</thead>
			<tbody>
			<?php 
				
				$sql = "select adh.id,adh.send_to ,fp.item as finalprodct , adh.waste,adh.send_to_qtny_type ,adh.send_to_quantity,adh.created_at,d.depart as todpt,qt.q_name 
				from admin_dpts_history adh,department d,final_product fp,quantity_type qt 
				where adh.send_to = d.id and adh.final_product = fp.id and adh.send_to_qtny_type = qt.id and send_from =5 and adh.updated_by is null and adh.deleted_by is null union
				select admrh.id,admrh.send_to, fp.item as finalprodct, admrh.waste, admrh.send_to_qtny_type, admrh.send_to_quantity,admrh.created_at,d.depart as todpt,qt.q_name
				from admin_dpts_mul_raw_history admrh,admin_dpts_mul_raw_child_history admrch ,department d,final_product fp ,quantity_type qt where admrh.send_to_qtny_type = qt.id and 
				admrh.final_product = fp.id and admrh.send_to = d.id and admrh.id = admrch.admr_parent_id and send_from =5 and admrh.updated_by is null and admrh.deleted_by is null";
				
				$result = $con->query($sql);

				if ($result && $result->num_rows > 0) 
				{
				    // output data of each row
					$wasteId='';
		    		while($row = $result->fetch_assoc()) 
		    		{
						//echo"<pre>";print_r($row);
						$wasteId = $row['waste'];
			?>
			<tr style="background-color:#AFF3CA">
				<td>
					<p><?php echo $row['id']?></p>
				</td>
				<td>
					<p><?php echo $row['todpt']?></p>
				</td>
				<td>
					<p><?php echo $row['finalprodct']?></p>
				</td>
				<td>
					<p><?php 
					
				    $sql1="select GROUP_CONCAT(name) as name1 from waster_type p where id in(".$wasteId.")";
				   $res=mysqli_query($con,$sql1);
				   if (isset($res->num_rows) && $res->num_rows > 0){
					   while($row1 = mysqli_fetch_array($res))
					   {
						   echo isset($row1['name1'])?$row1['name1']:'';
					   } 
				   }
					?></p>
				</td>
				<td>
					<p><?php echo $row['q_name']?></p>
				</td>
				<td>
					<p><?php 

					if($row['send_to_qtny_type'] == '1' or $row['send_to_qtny_type'] == '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 
						$date = new DateTime($row['created_at'], new DateTimeZone('MST'));
						$date->setTimezone(new DateTimeZone('Asia/Kolkata'));
						echo $date->format('Y-m-d H:i:s');
						?></p>
				</td>
			</tr>
			<?php
					}
				}

			?>
			</tbody>
		</table>
				
	</div>
</div>

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


	$('#othrdept').on('click',function() {
			
		$('#ad_dpt').modal('show');
	});

	$('#datatableid').on('click','.sendbtn',function() {
			
		
		$('#single_send').modal('show');

		$tr = $(this).closest('tr');

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

		$('#issendfromsingle').val(data[11].trim());

		$('#adminId').val(data[0].trim());
		$('#item').val(data[3].trim());
		$('#revcdFinalProdct').val(data[4].trim());
		$('#quan').val(data[7].trim());
		$('#qty_typ').val(data[6].trim());

		$('#qty_typId').val(data[9].trim());
		$('#wtype').val(data[5].trim());
		
		changeInitialQtyType();
		
	});

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

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

		var adminId = data[0].trim();

		var isSingle = data[11].trim();

		var url = '../controller/admin_controller.php';

		if(isSingle == '0'){
			url = '../controller/multiple_raw_material_controller.php';
		}

		$.ajax( {
	        url: url,
	        method: 'POST',
	        data:'type=validateProductIsProcessed&adminId='+adminId,
	        
	        success: function(data1){
	          console.log('Msg',data1);
	          if(data1.status == true){
		        alert('This Product has been processed furthur, first please delete from processed departments to Edit this!.'); 
		      }else{
		      	
		      	$('#issendfromsingleedit').val(isSingle);
		      	$('#editModal').modal('show');
				$('#editadminId').val(data[0].trim());
				$('#edititem').val(data[3].trim());
				$('#editfin_product').val(data[4].trim());
				$('#oldqty').val(data[7].trim());
				$('#oldqtytype').html(data[6].trim());
				$('#editwtype').val(data[10].trim());

				$('#editsendqty_typ').val(data[9].trim());
				
				changefuncEdit();
	      	  	
	      	  }
	        },
	        error: function(r) {
	          alert('Unable To Edit Product'); 
	        }
	      } );

		
	});

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

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

		var adminId = datatb[0].trim();
		if (confirm("Are You Sure?")) {
			var isSingle = datatb[11].trim();

			var url = '../controller/admin_controller.php';

			if(isSingle == '0'){
				url = '../controller/multiple_raw_material_controller.php';
			}	
		$.ajax( {
	        url: url,
	        method: 'POST',
	        data:'type=validateProductIsProcessed&adminId='+adminId,
	        
	        success: function(data1){
	          console.log('Msg',data1);
	          if(data1.status == true){
		        alert('This Product has been processed furthur, first please delete from processed departments to delete this!.'); 
		      }else{

		      	$.ajax( {
			        url: url,
			        method: 'POST',
			        data:'type=scrapDelete&adminId='+adminId+'&userId='+userid,
			        
			        success: function(data2){
			          console.log('Msg',data2);
			          if(data2.status == true){
			          	alert('Product deleted Successfully'); 
			          	window.location.reload();
			      	  }else{
			      	  	alert('Failed To Delete Product'); 
			      	  }
			        },
			        error: function(r) {
			          alert('Unable To Delete Product'); 
			        }
			      } );
	      	  	
	      	  }
	        },
	        error: function(r) {
	          alert('Unable To Edit Product'); 
	        }
	      } );
		}
	});

	$("#adminForm").submit(function(e) {
    document.getElementById("adminSend").disabled=true;
    //prevent Default functionality
    e.preventDefault();
    //do your own request an handle the results
   	
	var totalqt = parseFloat($('#quan').val());
	var selectedValue3 = $('#qty_typId').val();
	if(selectedValue3 == "1")
	{
		var kilogrm = (parseInt($('#iko').val()) * 1000)+parseInt($('#igr').val());
		$('#initialqty').val(kilogrm);
		totalqt = totalqt * 1000;
	}else if(selectedValue3 == "3")
	{	var milliltr = (parseInt($('#ilitr').val()) * 1000)+parseInt($('#imltr').val());
		$('#initialqty').val(milliltr);
		totalqt = totalqt * 1000;
	}else if(selectedValue3 == "2")
	{
		$('#initialqty').val($('#ipiec').val());
	}else if(selectedValue3 == "4")
	{
		$('#initialqty').val($('#imtr').val());
		
	}else if(selectedValue3 == "5")
	{
		$('#initialqty').val($('#ift').val());
	}
	
	var formData = new FormData(this);
	
	formData.append('type','scrapSend');
	formData.append('userId',userid);
	
	var sendqty = parseFloat($('#initialqty').val());
	console.log('sendqty data',sendqty);

	if(isNaN($('#initialqty').val()) || $('#initialqty').val() == ''){
		alert('Invalid or Empty Value in Input Quantity');
    document.getElementById("adminSend").disabled=false;
	}else if(sendqty > totalqt){
    	alert('Send Quantity cannot exceed Total Quantity');
    	document.getElementById("adminSend").disabled=false;
    }else if(sendqty == 0){
		alert('Input Quantity cannot be 0');
		document.getElementById("adminSend").disabled=false;
    }else{
    	var url = '';
    	if($('#issendfromsingle').val() == '1'){
    		url = '../controller/admin_controller.php';
    	}else{
    		url = '../controller/multiple_raw_material_controller.php';
    	}

	     $.ajax( {
	        url: url,
	        type: 'POST',
	        data: formData,
	        processData: false,
	        contentType: false,

	        success: function(data){
	          console.log('Msghi',data);
	          if(data.status == true){
		        	alert('Product sent to '+data.dpt); 
		        	window.location.reload();
	      	  }else{
	      	  	alert('Failed To Send Product'); 
	      	  	document.getElementById("adminSend").disabled=false;
							window.location.reload();
	      	  }
	        },
	        error: function(r) {
	          alert('Unable To Send Product'); 
	          document.getElementById("adminSend").disabled=false;
			  		window.location.reload();
	        }
	      } );
	}
});

	$("#editForm").submit(function(e) {
    document.getElementById("updateProds").disabled=true;
    //prevent Default functionality
    e.preventDefault();
    //do your own request an handle the results
   	
   	var selectedValue = $('#wqtytype').val();
   	
    if(selectedValue == "1")
	{
		var kilogrm = (parseInt($('#eko').val()) * 1000)+parseInt($('#egr').val());
		$('#wasteqty').val(kilogrm);
	}else if(selectedValue == "3")
	{
		var milliltr = (parseInt($('#elitr').val()) * 1000)+parseInt($('#emltr').val());
		$('#wasteqty').val(milliltr);
	}else if(selectedValue == "2")
	{
		$('#wasteqty').val($('#epiec').val());
	}else if(selectedValue == "4")
	{
		$('#wasteqty').val($('#emtr').val());
		
	}else if(selectedValue == "5")
	{
		$('#wasteqty').val($('#eft').val());
	}
	
	var formData = new FormData(this);
	
	formData.append('type','scrapEdit');
	formData.append('userId',userid);
		var url = '';
    	if($('#issendfromsingleedit').val() == '1'){
    		url = '../controller/admin_controller.php';
    	}else{
    		url = '../controller/multiple_raw_material_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('Product Updated!'); 
	        window.location.reload();
      	  }else{
      	  	alert(data.msg); 
      	  	document.getElementById("updateProds").disabled=false;
			window.location.reload();
      	  }
        },
        error: function(r) {
          alert('Unable To Update Product'); 
          document.getElementById("updateProds").disabled=false;
		  window.location.reload();
        }
    } );
	
});

	$('#add_dptbtn').click(function(){
		var data=$('#dpt_form').serialize()+'&type=add_other_department';
		var productnm = $('#dname').val();
		$.ajax({
			url:'../controller/storage_controller.php',
			type:'POST',
			data:data,
			success:function(response){
				console.log('Result',response);
				if(response.status == true){
					alert(response.msg);
					$('#dpt').append($('<option>', {
					    value: response.rowId,
					    text: productnm
					}));
					
					$('#add_dptbtn').modal('hide');
					clearForm('dpt_form');
					$('#single_send').modal('show');

				}else{
					alert(response.msg);
				}
			}
		});
	});
});

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

	if(formname == 'user_form'){
		$('#mesg').text('');
		$('#add_product').show();
	}else if(formname == 'dpt_form'){
		$('#mesgdpt').text('');
		$('#add_dptbtn').show();
	}
}

function changeInitialQtyType() {
	
	var selectedValue = $('#qty_typId').val();
	
	if(selectedValue == "1")
	{
		$('#qty21').show();
		$('#qty22').hide();
		$('#qty23').hide();
		$('#qty24').hide();
		$('#qty25').hide();
		
	}else if(selectedValue == "2")
	{
		$('#qty22').show();
		$('#qty21').hide();
		$('#qty23').hide();
		$('#qty24').hide();
		$('#qty25').hide();
		
	}else if(selectedValue == "4")
	{
		$('#qty22').hide();
		$('#qty21').hide();
		$('#qty23').hide();
		$('#qty24').show();
		$('#qty25').hide();
		
	}else if(selectedValue == "5")
	{
		$('#qty22').hide();
		$('#qty21').hide();
		$('#qty23').hide();
		$('#qty24').hide();
		$('#qty25').show();
		
	}else
	{
		$('#qty23').show();
		$('#qty21').hide();
		$('#qty22').hide();
		$('#qty24').hide();
		$('#qty25').hide();
		
	}
}

function changefunc() {
	var y = document.getElementById("sendqty_typ");
	var selectedValue = y.options[y.selectedIndex].value;
	
	if(selectedValue == "1")
	{
		$('#qty11').show();
		$('#qty12').hide();
		$('#qty13').hide();
		$('#qty14').hide();
		$('#qty15').hide();
		
	}else if(selectedValue == "2")
	{
		$('#qty12').show();
		$('#qty11').hide();
		$('#qty13').hide();
		$('#qty14').hide();
		$('#qty15').hide();
		
	}else if(selectedValue == "4")
	{
		$('#qty12').hide();
		$('#qty11').hide();
		$('#qty13').hide();
		$('#qty14').show();
		$('#qty15').hide();
		
	}else if(selectedValue == "5")
	{
		$('#qty12').hide();
		$('#qty11').hide();
		$('#qty13').hide();
		$('#qty14').hide();
		$('#qty15').show();
		
	}else
	{
		$('#qty13').show();
		$('#qty11').hide();
		$('#qty12').hide();
		$('#qty14').hide();
		$('#qty15').hide();
		
	}
}

function changefuncEdit(){
	var selectedValue = $('#wqtytype').val();
	
	if(selectedValue == "1")
	{
		$('#qty31').show();
		$('#qty32').hide();
		$('#qty33').hide();
		$('#qty34').hide();
		$('#qty35').hide();
		
	}else if(selectedValue == "2")
	{
		$('#qty32').show();
		$('#qty31').hide();
		$('#qty33').hide();
		$('#qty34').hide();
		$('#qty35').hide();
		
	}else if(selectedValue == "4")
	{
		$('#qty32').hide();
		$('#qty31').hide();
		$('#qty33').hide();
		$('#qty34').show();
		$('#qty35').hide();
		
	}else if(selectedValue == "5")
	{
		$('#qty32').hide();
		$('#qty31').hide();
		$('#qty33').hide();
		$('#qty34').hide();
		$('#qty35').show();
		
	}else
	{
		$('#qty33').show();
		$('#qty31').hide();
		$('#qty32').hide();
		$('#qty34').hide();
		$('#qty35').hide();
		
	}
}

function departmentCheck(){
  var x = document.getElementById("dpt").value;

  if( x == '12'){
    document.getElementById("othrdept").style.display = "initial";
  }else{
    document.getElementById("othrdept").style.display = "none";
  }
}

function openTabs(evt, tbName) {
  var i, tabcontent, tablinks;
  tabcontent = document.getElementsByClassName("tabcontent");
  for (i = 0; i < tabcontent.length; i++) {
    tabcontent[i].style.display = "none";
  }
  tablinks = document.getElementsByClassName("tablinks");
  for (i = 0; i < tablinks.length; i++) {
    tablinks[i].className = tablinks[i].className.replace(" active", "");
  }
  document.getElementById(tbName).style.display = "block";
  evt.currentTarget.className += " active";
}
</script>
</html>