<!DOCTYPE html>
<?php
require_once('../Db/dbconfig.php');
@$name=$_GET['username'];
@$userid=$_GET['userid'];
@$itemCatVal = $_GET['itemCatId'];

@$dptId=$_GET['dptId'];
?>
<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;
}
/* Style the tab */
.tab {
  overflow: hidden;
  border: 1px solid #ccc;
  background-color: #f1f1f1;
}

/* Style the buttons inside the tab */
.tab button {
  background-color: inherit;
  float: left;
  border: none;
  outline: none;
  cursor: pointer;
  padding: 14px 16px;
  transition: 0.3s;
  font-size: 17px;
}

/* Change background color of buttons on hover */
.tab button:hover {
  background-color: #ddd;
}

/* Create an active/current tablink class */
.tab button.active {
  background-color: #ccc;
}

/* Style the tab content */
.tabcontent {
  display: none;
  padding: 6px 12px;
  border: 1px solid #ccc;
  border-top: 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-box-open fa-xs" style="color: black"></i>
        </span><b>Storage</b></h3>
        <input type="hidden" id="username" value="<?php echo @$name;?>">
	</div>
	<div class=" card-header d-flex flex-row-reverse">
		<select id="itemCatList" onchange="onchangeItemCatList()" class="rou">
		   <?php 
		   $sql1="SELECT id, item FROM product;";
			 $res=mysqli_query($con,$sql1);
		   		   
			 while($row1 = mysqli_fetch_array($res))
				{
        	if($itemCatVal == 0){
        		$itemCatVal = $row1['id'];
        	}
			?>
			<option value="<?php echo $row1['id']; ?>"><?php echo $row1['item']; ?></option> 
			<?php
	        	
				}
			?>
		</select>
		<label for="itemCatList" class="form-label p-2"><b>Item Category :</b></label>
	</div>
	
	<div class="card-body child" style="overflow: auto;">
		<div class="tab">
			<button class="tablinks" onclick="openTabs(event, 'comefrmPur')" id="defaultOpen">From Purchase / F-39</button>
		    <button class="tablinks" onclick="openTabs(event, 'comefrmDepart')" id="dptOpenTab">From Departments</button>
		</div>
		<div id="comefrmPur" class="tabcontent">
			<div style="text-align: right;"><label id="totalqt"></label></div>  
			<table id="datatableid" class="table table-striped table-bordered table-hover">
			<thead class="thead-dark">
				<tr style="background-color:#091a09">
					<th class="center">
						
					</th>
					<th>Sr. No</th>
					<th>Product Name</th>
					<th>Product Type</th>
					<th>Quantity Type</th>
					<th style="display: none">Quantity Type id</th>
					<th>Quantity</th>	
					<th>Updated Time</th>
					<th>View</th>
					<th>Send</th>
					<?php
						if(@$name == 'superadmin'){
					?>
					<th>Delete</th>
					<?php
						}
					?>
				</tr>
			</thead>
			<tbody>
			<?php 
				$sql = "select p3.item as ptype,tpq.id, p2.description as item, tpq.quantity,qt.q_name as quantity_type,qt.id as qtytypeId ,tpq.updated_by 
				from total_purchase_qty tpq,quantity_type qt,productitem p2,productype p3,product p4 where
				tpq.item = p2.id and tpq.ptype = p3.id and tpq.quantity_type = qt.id and tpq.quantity > 0 
				and p2.item = p4.id and p4.id = ".$itemCatVal." group by tpq.item,tpq.quantity_type,tpq.ptype order by tpq.updated_by desc;";
				$result = $con->query($sql);

				if ($result->num_rows > 0) 
				{
				    // output data of each row
		    		while($row = $result->fetch_assoc()) 
		    		{
			?>
			<tr style="background-color:#AFF3CA">
				<td class="center">
					
					<p style="display: none"><?php echo $row['id']?></p>
				</td>
				<td>
					<p><?php echo $row['id']?></p>
				</td>
				<td>
					<p><?php echo $row['item']?></p>
				</td>
				<td>
					<p><?php echo $row['ptype']?></p>
				</td>
				<td>
					<p><?php echo $row['quantity_type']?></p>
				</td>
				<td style="display: none">
					<p><?php echo $row['qtytypeId']?></p>
				</td>
				<td>
					<p><?php 

					if($row['qtytypeId'] == '1' or $row['qtytypeId'] == '3'){
						if($row['quantity'] != 0){
							echo ($row['quantity']/1000);
						}else{
							echo $row['quantity'];
						}
					}else{
						echo $row['quantity'];
					}
					?>
					</p>
				</td>
				<td>
					<p><?php 
						$date = new DateTime($row['updated_by'], 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 viewbtn"><i class="ace-icon fa fa-search-plus bigger-130"></i></button>
				</td>
				<td>
					<button type="button" class="btn btn-primary sendbtn"><i class="ace-icon fa fa-plus bigger-130"></i></button>
				</td>
				<?php
					if(@$name == 'superadmin'){
				?>
				<td>
					<button type="button" class="btn btn-primary deletebtn" title="Delete"><i class="ace-icon fa fa-trash-o"></i></button>
				</td>
				<?php
					}
				?>
				
			</tr>
			<?php
					}
				}

			?>
			</tbody>
		</table>
		</div>
		<div id="comefrmDepart" class="tabcontent">
			<div style="text-align: right;"><label id="totalqtFromDpts"></label></div>  
			<table id="datatableid2" class="table table-striped table-bordered table-hover">
			<thead class="thead-dark">
				<tr style="background-color:#091a09">
					<th class="center">
						
					</th>
					<th>Sr. No</th>
					<th>Final Product</th>
					<th>Quantity</th>	
					<th>Type</th>
					<th>Sent DateTime</th>
					<th style="display: none;"></th>
					<th style="display: none;"></th>
					<th style="display: none;"></th>
					<th style="display: none;"></th>
					<th style="display: none;"></th>
					<th>Send To</th>
					<?php
						if(@$name == 'superadmin'){
					?>
					<th>Delete</th>
					<th>View</th>
					<?php
						}
					?>
					
				</tr>
			</thead>
			<tbody>
			<?php 
				$sql = "select '1' as is_single,s.senddttime,s.ids,s.finalproductId,s.ptypeId,s.id,s.productItem_id,s.waste,s.finalprodct,s.send_to_quantity,s.q_name,s.qtytypeid,s.water_wt from(select group_concat(ad.id order by ad.id asc) as ids,fp.id as finalproductId
				,group_concat(ad.ptype) as ptypeId,ad.id ,group_concat(ad.productItem_id) as productItem_id,ad.waste ,
				fp.item as finalprodct,sum(ad.send_to_quantity) as send_to_quantity,sendqt.q_name,sendqt.id as qtytypeid,
				ad.created_at as senddttime ,ad.water_wt 
				from admin_dpts ad ,final_product fp ,
				quantity_type sendqt
				where ad.final_product = fp.id and 
				ad.send_to_qtny_type = sendqt.id and ad.send_to = '4' and ad.send_to_quantity > 0
				group by ad.final_product ,ad.send_to_qtny_type,ad.ptype having sum(ad.send_to_quantity) > 0) as s
				union 
				select '0' as is_single,m.senddttime,m.ids,m.finalproductId,m.ptypeId,m.id,m.productItem_id,m.waste,m.finalprodct,m.send_to_quantity,m.q_name,m.qtytypeid,m.water_wt from(select group_concat(ad.id order by ad.id asc) as ids,fp.id as finalproductId
				,group_concat(admrc.ptype) as ptypeId,ad.id ,group_concat(admrc.productItem_id) as productItem_id,ad.waste ,
				fp.item as finalprodct,sum(ad.send_to_quantity) as send_to_quantity,sendqt.q_name,sendqt.id as qtytypeid,
				ad.created_at as senddttime ,admrc.water_wt 
				from admin_dpts_mul_raw ad ,final_product fp ,
				quantity_type sendqt,admin_dpts_mul_raw_child admrc 
				where ad.final_product = fp.id and 
				ad.send_to_qtny_type = sendqt.id and ad.id = admrc.admr_parent_id  and ad.send_to = '4' and ad.send_to_quantity > 0
				group by ad.final_product ,ad.send_to_qtny_type,admrc.ptype having sum(ad.send_to_quantity) > 0) as m";
				$result = $con->query($sql);

				if ($result->num_rows > 0) 
				{
				    // output data of each row
		    		while($row = $result->fetch_assoc()) 
		    		{
						$sql1 = "select description from productitem p where id in (".$row['productItem_id'].") and item = ".$itemCatVal." limit 1;";
						$result1 = $con->query($sql1);

						if ($result1->num_rows > 0) 
						{
						
			?>
			<tr style="background-color:#AFF3CA">
				<td class="center">
					
					<p style="display: none"><?php echo $row['ids']?></p>
				</td>
				<td>
					<p><?php echo $row['id']?></p>
				</td>
				<td>
					<p><?php 
					$sql1="select group_concat(description) as items from productitem p where id in (".$row['productItem_id'].");";
					$res=mysqli_query($con,$sql1);
					while($row1 = mysqli_fetch_array($res))
					{
						echo $row1['items'];
					}
					?></p>
				</td>
				<td>
					<p><?php 

					if($row['qtytypeid'] == '1' or $row['qtytypeid'] == '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 style="display: none;">
				<?php 
					$sql1="select group_concat(item) as items from productype p where id in (".$row['ptypeId'].");";
					$res=mysqli_query($con,$sql1);
					while($row1 = mysqli_fetch_array($res))
					{
						echo $row1['items'];
					} 
				?></td>
				<td style="display: none;"><?php echo $row['ptypeId']?></td>
				<td style="display: none;"><?php echo $row['qtytypeid']?></td>
				<td style="display: none;"><?php echo $row['finalProdId']?></td>
				<td style="display: none;"><?php echo $row['is_single']?></td>
				<td>
					<button type="button" name="sendbtn" class="btn btn-primary sendbtn" title="Send"><i class="ace-icon fa fa-plus bigger-130"></i></button>
				</td> 
				<?php
					if(@$name == 'superadmin'){
				?>
				<td>
					<button type="button" name="deletebtn" class="btn btn-primary deletebtn" title="Delete"><i class="ace-icon fa fa-trash-o"></i></button>
				</td>
				<td>
					<button type="button" name="edit" class="btn btn-primary editbtn" title="View"><i class="ace-icon fa fa-search-plus bigger-130"></i></button>
				</td>
				<?php
					}
				?>
			</tr>
			<?php
							
						}
					}
				}

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

<!--Send Modal-->
<div id="single_send" class="modal fade" role="dialog" tabindex="-1" aria-hidden="true"> 
  <div class="modal-dialog">
    <!-- Modal content-->
    <div class="modal-content">
      <div class="modal-header">
	  <h4 class="modal-title">Send</h4>
        <button type="button" class="close" onclick="clearForm('storageForm')" data-dismiss="modal">&times;</button>
        
      </div>
      <div class="modal-body">
       
		<form id="storageForm">
		<input type="hidden" class="form-control" id="storageId" name="storageId">
		<input type="hidden" class="form-control" id="fromPurchase" name="fromPurchase"><!--used to identify if modal opened from datatable 1 or datatable2-->
		<input type="hidden" class="form-control" id="is_single" name="is_single" value="1">
		<div class="form-group">
            <label style="width:150px;" for="dat">Date</label>
            <input style="width:200px;" type="date" id="dat" name="dat"  required>
        </div>
	    <div class="form-group">
	        <label style="width:150px;" for="time">Time</label>
	        <input style="width:200px;" type="time" id="time" name="time"  required>
        </div>
		<div class="form-group">
		    <label for="item">Product Name : </label>
		    <input type="text" class="form-control" id="item" name="item" readonly>
		</div>	
		<div class="form-group" id="productTypeDiv">
			<label style="width:150px;" for="product_type">Product Type : </label>
		    <input style="width:100px;" type="text" class="rounded" id="product_type" name="product_type" disabled>
		</div>
		<div class="form-group">
		    <label style="width:150px;" for="quan">Total Quantity : </label>
			<input style="width:100px;" type="text" id="quan" name="quan" class="rounded" disabled>
			<input type="text" class="rounded" style="width:100px;"  id="qty_typ" name="qty_typ" disabled>
		</div>	
		<div class="form-group">
	        <label style="width:150px;" for="no">Send To Department:</label>
	        <select style="width:170px;" id="dpt" name="dpt" onchange="departmentCheck()" class="rou" required>
	        <?php 
				$sql1="select * from department where id not in (2,3,4,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>
			<button type="button" class="btn btn-primary" style="display: none" id="othrdept" data-toggle="tooltip" data-placement="bottom" title="Add Other Department" ><i class="ace-icon fa fa-plus bigger-130"></i></button>
        
		</div>		
		<div class="dropdown-divider"></div>
		<div class="form-group">
		    <input style="width:150px;" type="hidden" id="send_to_quantity" name="send_to_quantity">
		    <input style="width:150px;" type="hidden" id="send_to_qtny_type" name="send_to_qtny_type" disabled>
		<div class="form-group" id="qty11" >
			<label style="width:150px;" for="qty"><b>Send Quantity :</b></label>
		    <input type="text" style="width:120px;" maxlength="6" class="rounded" id="ko" 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" pattern="^(0|[1-9][0-9]*)$" value ="0"><label>gram</label>
			
		</div>
		<div class="form-group" id="qty12" style="display:none">
			<label style="width:150px;" for="qty"><b>Send Quantity :</b></label>
			<input type="text" style="width:150px;" maxlength="6" class="rounded" id="piec" pattern="^[0-9]+(\.[0-9]{1,4})?$" title="Enter a Valid Input" value="0"><label>Pieces</label>
		</div>
		<div class="form-group" id="qty13" style="display:none">
			<label style="width:150px;" for="qty"><b>Send Quantity :</b></label>
			<input type="text" style="width:120px;" maxlength="6" class="rounded" id="litr" 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" pattern="^(0|[1-9][0-9]*)$" value ="0">ml
		</div>
		<div class="form-group" id="qty14" style="display:none">
			<label style="width:150px;" for="qty"><b>Send Quantity :</b></label>
			<input type="text" style="width:150px;" maxlength="6" class="rounded" id="mtr" pattern="^[0-9]+(\.[0-9]{1,4})?$" title="Enter a Valid Input" value="0"><label>Meter</label>
		</div>
		<div class="form-group" id="qty15" style="display:none">
			<label style="width:150px;" for="qty"><b>Send Quantity :</b></label>
			<input type="text" style="width:150px;" maxlength="6" class="rounded" id="ft" pattern="^[0-9]+(\.[0-9]{1,4})?$" title="Enter a Valid Input" value="0"><label>Feet</label>
		</div>
		</div>

	  <button type="submit" name="storageSend" id="storageSend" class="p-1 mb-1 bg-primary text-white rounded">Submit</button>
	  <button type="button" class="p-1 mb-2 bg-danger text-white rounded" data-dismiss="modal" onclick="clearForm('storageForm')">Close</button>
	</form> 

      </div>
      <div class="modal-footer">
        
      </div>
    </div>

  </div>
</div>

<!--Edit Modal-->
<div id="editModal" class="modal fade" role="dialog" tabindex="-1" aria-hidden="true"> 
  <div class="modal-dialog">
    <!-- Modal content-->
    <div class="modal-content">
      <div class="modal-header">
	  <h4 class="modal-title">Edit Product</h4>
        <button type="button" class="close" onclick="clearForm('editForm')" data-dismiss="modal">&times;</button>
        
      </div>
      <div class="modal-body">
       
	<form id="editForm">
	<input type="hidden" class="form-control" id="editadminId" name="editadminId">
	<input type="hidden" class="form-control" id="editis_single" name="editis_single">
		<div class="form-group" >
            <label  style="width:150px;"for="no"><b>Final Product :</b></label>
            <select name="editfin_product" id="editfin_product" class="rou" disabled>
			<?php 
			 $sql1="select * from final_product";
			   $res=mysqli_query($con,$sql1);
				while($row1 = mysqli_fetch_array($res))
				{
				?>

				<option value="<?php echo $row1['id']; ?>"><?php echo $row1['item']; ?></option> 

				<?php
				}
			?>
			</select>
			
		</div>	
		<div class="form-group">
		<label style="width:150px;" for="qty"><b>Old Quantity :</b></label>
			<input type="text" style="width:150px;" maxlength="6" class="rounded" id="oldqty" disabled><label id="oldqtytype"></label>
		</div>
	  <div class="form-group">
		    <label style="width:150px;"><b>Quantity Type</b></label>
		    <select style="width:150px;" class="rou" id="editsendqty_typ" name="editsendqty_typ" onchange="changefuncEdit()" required>
			  <?php 
				$sql1="select * from quantity_type";
			    $res=mysqli_query($con,$sql1);
				while($row1 = mysqli_fetch_array($res))
				{
				?>
				<option value="<?php echo $row1['id']; ?>"><?php echo $row1['q_name']; ?></option> 
			    <?php
				}
				?>
		    </select>
		</div>
		<div class="form-group">
		    <input style="width:150px;" type="hidden" id="editsend_to_quantity" name="editsend_to_quantity">
		<div class="form-group" id="qty31" >
			<label style="width:150px;" for="qty"><b>Quantity :</b></label>
		    <input type="text" style="width:120px;" maxlength="6" class="rounded" id="eko" 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="egr" pattern="^(0|[1-9][0-9]*)$" value ="0"><label>gram</label>
			
		</div>
		<div class="form-group" id="qty32" style="display:none">
			<label style="width:150px;" for="qty"><b>Quantity :</b></label>
			<input type="text" style="width:150px;" maxlength="6" class="rounded" id="epiec" pattern="^[0-9]+(\.[0-9]{1,4})?$" title="Enter a Valid Input" value="0"><label>Pieces</label>
		</div>
		<div class="form-group" id="qty33" style="display:none">
			<label style="width:150px;" for="qty"><b>Quantity :</b></label>
			<input type="text" style="width:120px;" maxlength="6" class="rounded" id="elitr" 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="emltr" pattern="^(0|[1-9][0-9]*)$" value ="0">ml
		</div>
		<div class="form-group" id="qty34" style="display:none">
			<label style="width:150px;" for="qty"><b>Quantity :</b></label>
			<input type="text" style="width:150px;" maxlength="6" class="rounded" id="emtr" pattern="^[0-9]+(\.[0-9]{1,4})?$" title="Enter a Valid Input" value="0"><label>Meter</label>
		</div>
		<div class="form-group" id="qty35" style="display:none">
			<label style="width:150px;" for="qty"><b>Quantity :</b></label>
			<input type="text" style="width:150px;" maxlength="6" class="rounded" id="eft" pattern="^[0-9]+(\.[0-9]{1,4})?$" title="Enter a Valid Input" value="0"><label>Feet</label>
		</div>
		</div>

      <button type="submit" id = "updateProds" name="updateProds" class="btn btn-gradient-primary mr-2">Update</button>
		  <button type="button" class="btn btn-default" data-dismiss="modal" onclick="clearForm('editForm')">Close</button>
	</form> 

      </div>
     
    </div>

  </div>
</div>

<!-- Add Other Departments Modal -->
<div id="ad_dpt" class="modal fade" role="dialog" tabindex="-1" aria-hidden="true"> 
  <div class="modal-dialog">
    <!-- Modal content-->
    <div class="modal-content">
      <div class="modal-header">
        <h4 class="modal-title">Add Other Department</h4>
		<button type="button" class="close" data-dismiss="modal" onclick="clearForm('dpt_form')">&times;</button>
        
      </div>
      <div class="modal-body">
       
		<form method="POST" id="dpt_form">
		
		<div class="form-group">
            <label>Department Name</label>
            <input type="text" class="form-control" id="dname" name="dname" required>
        </div>
        <b id="mesgdpt"></b>
		<input type="button" name="add_dptbtn" id="add_dptbtn" style="background-color:#FF6666" class="btn btn-default" value="Submit"/>
		<button type="button" style="background:radial-gradient(#FFF176, #ff3300)" class="btn btn-default" data-dismiss="modal" onclick="clearForm('dpt_form')">Close</button>
		</form> 

      </div>
      <div class="modal-footer">
       
      </div>
    </div>

  </div>
</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">Product Details</h4>
		 <button type="button" class="close" data-dismiss="modal">&times;</button>
       	<input type="hidden" id="maintablerow" readonly>
      </div>
      <div class="modal-body">
       	<table id="datatableid3" class="table table-striped table-bordered table-hover">
			<thead class="thead-dark">
				<tr style="background-color:#048065">
					<th>Sr. No</th>
					<th>Sent To</th>
					<th>Product/Final Product</th>
					<th>Quantity</th>	
					<th>Quantity Type</th>
					<th>Sent DateTime</th>
				</tr>
			</thead>
			<tbody>
			
			</tbody>
		</table>
	  </div>
      <div class="modal-footer">
       
      </div>
    </div>

  </div>
</div>

<!-- Add Table Modal -->
<div id="tableModalD" 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">Product Details</h4>
		 <button type="button" class="close" data-dismiss="modal">&times;</button>
       	<input type="hidden" id="maintablerow" readonly>
      </div>
      <div class="modal-body">
       	<table id="datatableid4" class="table table-striped table-bordered table-hover">
			<thead class="thead-dark">
				<tr style="background-color:#048065">
					<th>Sr. No</th>
					<th>Sent From</th>
					<th>Final Product</th>
					<th>Quantity</th>	
					<th>Type</th>
					<th>Sent DateTime</th>
					<th style="display: none;"></th>
					<th style="display: none;"></th>
					<th style="display: none;"></th>
					<th style="display: none;"></th>
					<?php
						if(@$name == 'superadmin'){
					?>
					<th>Edit</th>
					<?php
						}
					?>
				</tr>
			</thead>
			<tbody>
			
			</tbody>
		</table>
	  </div>
      <div class="modal-footer">
       
      </div>
    </div>

  </div>
</div>

</body>

<script type="text/javascript">
	$(document).ready(function(){
	var userid = '<?php echo @$userid; ?>';

	var itemCatId = '<?php echo @$itemCatVal; ?>';

	if(itemCatId != 0){
		$('#itemCatList').val(itemCatId);
	}

	var t = $('#datatableid').DataTable( {
		rowReorder: true,
		"order": [[ 5, "desc" ]],
        columnDefs: [
            { orderable: true, targets: '_all' }
            
        ]
    } );

	var t2 = $('#datatableid2').DataTable( {
		rowReorder: true,
		"order": [[ 6, "desc" ]],
        columnDefs: [
            { orderable: true, targets: '_all' }
            
        ]
    } );

	var modalTbl = $('#datatableid3').DataTable( {
		rowReorder: true,
		"order": [[ 5, "desc" ]],
        columnDefs: [
            { orderable: true, targets: '_all' }
            
        ]
    } );

	var t4 = $('#datatableid4').DataTable( {
		rowReorder: true,
		"order": [[ 6, "desc" ]],
        columnDefs: [
            { orderable: true, targets: '_all' }
            
        ]
    } );

	
    document.getElementById("defaultOpen").click();
    
    $("#totalqt").html("<b>Total Quantity</b>: "+t.column(6).data().sum());

	 t.on( 'search.dt', function () {
    //console.log('Hellow',t.search());
    $("#totalqt").html("<b>Total Quantity</b>: "+t.column(6,{filter:'applied'}).data().sum());
	} );

	 $("#totalqtFromDpts").html("<b>Total Quantity</b>: "+t2.column(3).data().sum());

	 t2.on( 'search.dt', function () {
    //console.log('Hellow',t.search());
    $("#totalqtFromDpts").html("<b>Total Quantity</b>: "+t2.column(3,{filter:'applied'}).data().sum());
	} );
	
	$('#othrdept').on('click',function() {
			
		$('#ad_dpt').modal('show');
	});

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

		$('#dat').val(new Date().toDateInputValue());

		$('#time').val(formatTime(new Date()));

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

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

		$('#storageId').val(data[0].trim());
		$('#item').val(data[2].trim());
		$('#product_type').val(data[3].trim());
		$('#quan').val(data[6].trim());
		$('#qty_typ').val(data[4].trim());
		$('#send_to_qtny_type').val(data[5].trim());
		$('#fromPurchase').val('1');
		changefunc();
	});

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

		$('#dat').val(new Date().toDateInputValue());

		$('#time').val(formatTime(new Date()));

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

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

		document.getElementById('productTypeDiv').style.display = 'block';
		$('#storageId').val(data[0].trim());
		$('#item').val(data[2].trim());
		$('#product_type').val(data[6].trim());
		$('#quan').val(data[3].trim());
		$('#qty_typ').val(data[4].trim());
		$('#send_to_qtny_type').val(data[8].trim());
		$('#fromPurchase').val('0');
		$('#is_single').val(data[10].trim());
		changefunc();
	});

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

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

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

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

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

		var tableEle = t4;

		if(isSingle == '0'){
			url = '../controller/multiple_raw_material_controller.php';
		}
		
		$.ajax( {
			url:url,
			type: 'POST',
			data: 'id='+adminIds+'&type=viewAdmin',

			success: function(data){
				
				if(data.status == true){
					//console.log(data.data);
					var rows = tableEle
					.rows()
					.remove()
					.draw();
					
					$.each(data.data,function(i,item){

						var finalqty = 0;
						if(item.qtytypeid == '1' || item.qtytypeid == '3'){
							finalqty = item.send_to_quantity/1000;
						}else{
							finalqty = item.send_to_quantity;
						}
						
						var rowNode = tableEle
						.row.add( [item.id, item.frmdpt,item.finalprodct,finalqty,item.q_name,item.senddttime,item.ptypeId,item.qtytypeid,item.finalproductId,isSingle,'<button type="button" name="edit" class="btn btn-primary editbtn" title="Edit"><i class="ace-icon fa fa-edit"></i></button>'])
						.draw()
						.node();
					
					});

					tableEle.columns([6,7,8,9]).visible(false);

					$('#tableModalD').modal('show');
					

				}
			
			},
			error: function(r) {
			console.log(r);
			var rows = tableEle
					.rows()
					.remove()
					.draw();
			}
		});	
		
	});

	$('#datatableid4').on('click','.editbtn',function() {
			
		$('#tableModalD').modal('hide');
		$('#editModal').modal('show');

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

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

		$('#editadminId').val(data[0].trim());
		$('#editfin_product').val(t4.column(8).data()[0]);
		$('#oldqty').val(data[3].trim());
		$('#oldqtytype').html(data[4].trim());
		
		$('#editsendqty_typ').val(t4.column(7).data()[0]);
		$('#editis_single').val(t4.column(9).data()[0]);
		
		changefuncEdit();
		
	});

	$('#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);
				}
			}
		});
	});

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

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

      var storageId = data[0].trim();
      if (confirm("Product will be deleted from Purchase too! Are You Sure?")) {
      	 $.ajax({
            url: '../controller/storage_controller.php',
            method: 'POST',
            data:'type=validateStorageIsProcessed&storageId='+storageId,
            
            success: function(msg) {
              if(msg.status == true){
                alert(msg.msg);
              }else{
                 $.ajax({
		            url: '../controller/storage_controller.php',
		            method: 'POST',
		            data:'type=deleteFromStorage&storageId='+storageId+'&deletedBy='+$('#username').val()+'&userId='+userid,
		            
		            success: function(msg) {
		              console.log('deleteStorageProduct',msg);
		              console.log("deleteStorageProduct typeof msg : ", typeof msg);
		              if(msg.status == true){
		                alert('Product Deleted Successfully');
		                location.reload();
		              }else{
		                alert('Failed to delete Product!');
		              }
		            },

		            error: function (request, status, error) {
		              console.log("request : ", request);
		              console.log("status  : ", status);
		              console.log("error   : ", error);
		              alert('Failed to delete Product');
		            }             
		        });
              }
            },

            error: function (request, status, error) {
              console.log("request : ", request);
              console.log("status  : ", status);
              console.log("error   : ", error);
              alert('Failed get Product from Storage');
            }             
        });
      
      //$('#weight').val(data[5].trim());
	}
    });

    $('#datatableid2').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 = data[10].trim();

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

		var tableEle = t4;

		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=adminDelete&adminId='+adminId+'&userId='+userid,
			        
			        success: function(data2){
			          console.log('Msg',data2);
			          if(data2.status == true){
			          	alert('Product deleted and Quantity reverted to '+data2.revertDpt); 
			          	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'); 
	        }
	      } );
		}
	});

	$("#storageForm").submit(function(e) {
    document.getElementById("storageSend").disabled=true;
    //prevent Default functionality
    e.preventDefault();
    //do your own request an handle the results
    var selectedValue = $('#send_to_qtny_type').val();
    var totalqt = parseFloat($('#quan').val());
	
    if(selectedValue == "1")
	{
		var kilogrm = (parseInt($('#ko').val()) * 1000)+parseInt($('#gr').val());
		$('#send_to_quantity').val(kilogrm);
		totalqt = totalqt * 1000;
	}else if(selectedValue == "3")
	{
		var milliltr = (parseInt($('#litr').val()) * 1000)+parseInt($('#mltr').val());
		$('#send_to_quantity').val(milliltr);
		totalqt = totalqt * 1000;
	}else if(selectedValue == "2")
	{
		$('#send_to_quantity').val($('#piec').val());
	}else if(selectedValue == "4")
	{
		$('#send_to_quantity').val($('#mtr').val());
		
	}else if(selectedValue == "5")
	{
		$('#send_to_quantity').val($('#ft').val());
	}

	if(isNaN($('#send_to_quantity').val()) || $('#send_to_quantity').val() == ''){
			alert('Invalid or Empty Value in Sending Quantity');
	    document.getElementById("storageSend").disabled=false;
	}else if(parseFloat($('#send_to_quantity').val()) > totalqt){
    	alert('Send Quantity cannot exceed Total Quantity');
    	document.getElementById("storageSend").disabled=false;
    }else if(parseFloat($('#send_to_quantity').val()) == 0){
		alert('Send Quantity cannot be 0');
		document.getElementById("storageSend").disabled=false;
    }else{
	   	var formData = new FormData(this);

		formData.append('type','sendFromStorage');
		formData.append('userId',userid);
		var url = '';

		if($('#fromPurchase').val() == '2'){
			url ='../controller/multiple_raw_material_controller.php';
		}else{
			url ='../controller/storage_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 sent to '+data.dpt); 
		        window.location.reload();
	      	  }else{
	      	  	alert('Failed To Send Product'); 
	      	  	document.getElementById("storageSend").disabled=false;
	      	  	window.location.reload();
	      	  }
	        },
	        error: function(r) {
	          alert('Unable to Send Product'); 
	          document.getElementById("storageSend").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 = $('#editsendqty_typ').val();
	   	console.log('Slected data',selectedValue);
	   if(selectedValue == "1")
		{
			var kilogrm = (parseInt($('#eko').val()) * 1000)+parseInt($('#egr').val());
			$('#editsend_to_quantity').val(kilogrm);
		}else if(selectedValue == "3")
		{
			var milliltr = (parseInt($('#elitr').val()) * 1000)+parseInt($('#emltr').val());
			$('#editsend_to_quantity').val(milliltr);
		}else if(selectedValue == "2")
		{
			$('#editsend_to_quantity').val($('#epiec').val());
		}else if(selectedValue == "4")
		{
			$('#editsend_to_quantity').val($('#emtr').val());
			
		}else if(selectedValue == "5")
		{
			$('#editsend_to_quantity').val($('#eft').val());
		}
		
		var formData = new FormData(this);
		
		formData.append('type','storageEditFromDpts');
		formData.append('userId',userid);

		var isSingle = $('#editis_single').val();

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

		if(isSingle == '0'){
			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();
	        }
	    } );
		
	});

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

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

		var storageId = data[0].trim();
		
		getHistory(storageId,modalTbl);
		
	});
	
});

function changefunc() {
	var selectedValue = $('#send_to_qtny_type').val();
	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 = $('#editsendqty_typ').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 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 departmentCheck(){
  var x = document.getElementById("dpt").value;

  if( x == '5'){
    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";
}

function onchangeItemCatList(){
	var userid = '<?php echo @$userid; ?>';
	var username = '<?php echo @$name; ?>';
	console.log('userID',userid);
	location.href = "../view/storage.php?username="+username+"&itemCatId="+$('#itemCatList').val()+"&userid="+userid;
}

function getHistory(prId,modalTbl){
	 $.ajax({
        url: '../controller/purchase_history_controller.php',
        method: 'POST',
        data:'type=getProcessedProducts&storageId='+prId,
        
        success: function(msg) {
          console.log('getProcessedProducts',msg);
          console.log("getProcessedProducts typeof msg : ", typeof msg);
          if(msg.status == true){
          	modalTbl.clear().draw();
            $.each(msg.dataAry, function (i, item) {
		        	
		        	var totalqt = parseFloat(item.qty);
		        	if(item.qtytypeId == 1 || item.qtytypeId == 3){
								totalqt = totalqt/1000;
							}
		        	modalTbl.row.add([item.id,item.dpt,item.prodt,totalqt,item.qtyType,item.date]).draw();
	        	});

	        	$('#tableModal').modal('show');
	      }else{
          	modalTbl.clear().draw();
          	$('#tableModal').modal('show');
          }
        },

        error: function (request, status, error) {
          console.log("request : ", request);
          console.log("status  : ", status);
          console.log("error   : ", error);
        }             
    });
}

Date.prototype.toDateInputValue = (function() {
    var local = new Date(this);
    local.setMinutes(this.getMinutes() - this.getTimezoneOffset());
    return local.toJSON().slice(0,10);
});

const getTwoDigits = (value) => value < 10 ? `0${value}` : value;

const formatTime = (date) => {
  const hours = getTwoDigits(date.getHours());
  const mins = getTwoDigits(date.getMinutes());

  return `${hours}:${mins}`;
}
</script>
</html>