<?php
require_once('../Db/dbconfig.php');

if($_POST['type'] == 'adminSend')
{
	$lotnumber=$_POST['lotnumber'];
	$adminId=$_POST['adminId'];
	$sendFrom=$_POST['sendFrom'];
	$inputQty=$_POST['initialqty'];
	$send_to_quantity=$_POST['send_to_quantity'];
	$send_to_qtny_type=$_POST['sendqty_typ'];
	$waste_type =$_POST['wtype'];
	$waste_qty_type = $_POST['waste_qty_typ'];
	$waste_qty = isset($_POST['waste_qty']) && !empty($_POST['waste_qty']) ? $_POST['waste_qty'] : '0';
	$extrawaterwt = isset($_POST['extrawaterwt']) && !empty($_POST['extrawaterwt']) ? $_POST['extrawaterwt'] : '0';
		
	$fin_product=isset($_POST['fin_product']) && !empty($_POST['fin_product']) ? $_POST['fin_product'] : '0';
	$send_to=$_POST['dpt'];
	$userId=$_POST['userId'];
	$is_single=$_POST['is_single'];

	$status = false;
	$sql = "";
	
	if($is_single != 0){
		$tableNm = "admin_dpts";
		$adminparentColumnNm = "admindpt_parent_id";
		$sql="select * from ".$tableNm." where id in (".$adminId.") order by send_to_quantity desc;";
	}else{
		$tableNm = "admin_dpts_mul_raw";
		$adminparentColumnNm = "admindptml_parentId";
		$sql="select adp.*, `productItem_id`, `initial_quantity`, `initial_qnty_type`, `inputQty`, `ptype`, `admindpt_parent_id`, `admindptml_parentId`, `storageId`, `water_wt` from ".$tableNm." adp, admin_dpts_mul_raw_child admrc where adp.lotnumber = admrc.lotnumber and adp.id in (".$adminId.") order by adp.send_to_quantity desc;";
	}
	
	
	$res=mysqli_query($con,$sql);
	if (mysqli_num_rows($res) > 0) 
	{
		$additionalQty = 0;
		$admindpt_parent_id ='';
		$producItemId = '';
		$initialQty='';
		$initialQtyType='';
		$ptype='';
		$storageId='';
		$insertedQty = $inputQty;
		$updateAdminArry = array();
		
		while($insertedQty > 0){
			while($rows=mysqli_fetch_assoc($res)){
				$totalqty = $rows["send_to_quantity"];
				
				if($rows["send_from"] == 4){
					$producItemId = $rows["productItem_id"];
				}else{
					if(strpos($producItemId, $rows["productItem_id"]) === false){
						$producItemId.= $rows["productItem_id"].",";
					}
				}

				$initialQty.=$rows["initial_quantity"].",";
				$initialQtyType.=$rows["initial_qnty_type"].",";

				if(strpos($ptype, $rows["ptype"]) === false){
					$ptype.=$rows["ptype"].",";
				}
				$storageId.=$rows["storageId"].",";

				if($fin_product == '0'){
					$fin_product = $rows["final_product"];
				}

				if($additionalQty == 0){
					if($inputQty <= $totalqty){
						$tquantity=$totalqty-$inputQty;

						$updateAdminArry[] =  $rows["id"]."-".$tquantity;

						$admindpt_parent_id .=$rows["id"]."-".$inputQty;
						$insertedQty = 0;
						break;

					}else{
						$additionalQty = $inputQty - $totalqty;

						$updateAdminArry[] =  $rows["id"]."-0";

						$admindpt_parent_id=$rows["id"]."-".$totalqty.",";

					}
				}else{
					$tquantity=$totalqty-$additionalQty;

					$updateAdminArry[] =  $rows["id"]."-".$tquantity;

					$insertedQty = 0;
					$admindpt_parent_id .=$rows["id"]."-".$additionalQty.",";
					break;

				}
				
			}
		}

		if(substr($admindpt_parent_id,-1) == ','){
			$admindpt_parent_id = substr($admindpt_parent_id,0,strlen($admindpt_parent_id)-1);
		}

		if(substr($producItemId,-1) == ','){
			$producItemId = substr($producItemId,0,strlen($producItemId)-1);
		}

		if(substr($ptype,-1) == ','){
			$ptype = substr($ptype,0,strlen($ptype)-1);
		}

		if(substr($initialQty,-1) == ','){
			$initialQty = substr($initialQty,0,strlen($initialQty)-1);
		}

		if(substr($initialQtyType,-1) == ','){
			$initialQtyType = substr($initialQtyType,0,strlen($initialQtyType)-1);
		}

		if(substr($storageId,-1) == ','){
			$storageId = substr($storageId,0,strlen($storageId)-1);
		}

		if($is_single == 0){
			$query = "INSERT INTO admin_dpts_mul_raw
						(lotnumber, send_from, send_to,final_product, send_to_quantity, send_to_qtny_type, wtype, wasteqty, waste, status,author)
						VALUES('".$lotnumber."', '".$sendFrom."', '".$send_to."', '".$fin_product."', '".$send_to_quantity."', 
						'".$send_to_qtny_type."', '".$waste_qty_type."', ".$waste_qty.", '".$waste_type."', 1,".$userId.");";
					
				$queryrun = mysqli_query($con, $query);
				
				if($queryrun >0){
					$last_id = mysqli_insert_id($con);
					$query = "INSERT INTO admin_dpts_mul_raw_history
					(lotnumber,send_from, send_to,final_product, send_to_quantity, send_to_qtny_type, wtype,wasteqty, waste, status,author,parent_id)
				VALUES('".$lotnumber."','".$sendFrom."', '".$send_to."', '".$fin_product."', '".$send_to_quantity."',
				'".$send_to_qtny_type."', '".$waste_qty_type."',".$waste_qty.", '".$waste_type."', 1,".$userId.",".$last_id.");";
					
					$queryrun = mysqli_query($con, $query);
						
					if($queryrun >0){
						$query = "INSERT INTO admin_dpts_mul_raw_child
						(lotnumber, productItem_id, initial_quantity,initial_qnty_type, inputQty, ptype, admindptml_parentId, storageId,water_wt,admr_parent_id)
						VALUES('".$lotnumber."', '".$producItemId."', '".$initialQty."', '".$initialQtyType."', '".$inputQty."','".$ptype."', 
						'".$admindpt_parent_id."','".$storageId."',".$extrawaterwt.",".$last_id.");";
					
						$queryrun = mysqli_query($con, $query);
						
						if($queryrun >0){
							$last_idh = mysqli_insert_id($con);
							$query = "INSERT INTO admin_dpts_mul_raw_child_history
							(lotnumber, productItem_id, initial_quantity,initial_qnty_type, inputQty, ptype, admindptml_parentId, storageId,admin_dpts_mul_raw_child_parent,water_wt,admr_parent_id)
						VALUES('".$lotnumber."', '".$producItemId."', '".$initialQty."', '".$initialQtyType."', '".$inputQty."','".$ptype."', 
						'".$admindpt_parent_id."','".$storageId."',".$last_idh.",".$extrawaterwt.",".$last_id.");";
							
							$queryrun = mysqli_query($con, $query);
								
							if($queryrun >0){
								$updatedCounter = count($updateAdminArry);

								foreach($updateAdminArry as $item) {
									$updateAdminQtAry = explode('-',$item);

									$query2 = "update ".$tableNm." set send_to_quantity = ".$updateAdminQtAry[1]." where id=".$updateAdminQtAry[0] ;
									
									$querysrun2 = mysqli_query($con, $query2);
									if($querysrun2 >0)
									{	
										$updatedCounter--;
									}
								}

								if($updatedCounter == 0){
									$status = true;
								}
							}
						}
					}
				}
		}else{
			$query = "INSERT INTO ".$tableNm."
			(lotnumber, send_from, send_to, productItem_id, initial_quantity, initial_qnty_type,inputQty, ptype, final_product, send_to_quantity, send_to_qtny_type, wtype,wasteqty, waste, status, 
			water_wt, ".$adminparentColumnNm.",storageId,author)
			VALUES('".$lotnumber."', '".$sendFrom."', '".$send_to."', '".$producItemId."', '".$initialQty."', '".$initialQtyType."', ".$inputQty.",'".$ptype."', 
			'".$fin_product."', ".$send_to_quantity.", ".$send_to_qtny_type.", '".$waste_qty_type."',".$waste_qty.", '".$waste_type."', 1, ".$extrawaterwt.", '".$admindpt_parent_id."',
			'".$storageId."',".$userId.");";
           
		   
			$queryrun = mysqli_query($con, $query);
			
			if($queryrun >0){
				$last_id = mysqli_insert_id($con);
				$query = "INSERT INTO ".$tableNm."_history
				(lotnumber,send_from, send_to, productItem_id, initial_quantity, initial_qnty_type,inputQty, ptype, final_product, send_to_quantity, send_to_qtny_type, wtype,wasteqty, waste,
				 status, water_wt, ".$adminparentColumnNm.",storageId,parent_id,author)
			VALUES('".$lotnumber."','".$sendFrom."', '".$send_to."', '".$producItemId."', '".$initialQty."', '".$initialQtyType."',".$inputQty." ,
			'".$ptype."', '".$fin_product."', ".$send_to_quantity.", ".$send_to_qtny_type.", '".$waste_qty_type."',".$waste_qty.", '".$waste_type."', 1, ".$extrawaterwt.", 
			'".$admindpt_parent_id."','".$storageId."',".$last_id.",".$userId.");";
				 
				$queryrun = mysqli_query($con, $query);
				
				if($queryrun >0){
						
					$updatedCounter = count($updateAdminArry);

					foreach($updateAdminArry as $item) {
						$updateAdminQtAry = explode('-',$item);

						$query2 = "update ".$tableNm." set send_to_quantity = ".$updateAdminQtAry[1]." where id=".$updateAdminQtAry[0] ;
						
						$querysrun2 = mysqli_query($con, $query2);
						if($querysrun2 >0)
						{	
							$updatedCounter--;
						}
					}

					if($updatedCounter == 0){
						$status = true;
					} 						
					
				}
			}
		}
										
	}
	
	$myObj = [ 'status' => $status,'dpt'=> getDepartmentNameById($con,$send_to)];
	mysqli_close($con);
	header('Content-type: application/json');
	
	echo json_encode($myObj);
}else if($_POST['type'] == 'adminPackageSendToStock'){
	$adminIds=$_POST['adminId'];
	
	$per_box_quantity=$_POST['send_to_quantity'];
		
	$waste_qty = isset($_POST['waste_qty']) && !empty($_POST['waste_qty']) ? $_POST['waste_qty'] : '0';
	
	$totalBoxs = isset($_POST['packaging_qt']) && !empty($_POST['packaging_qt']) ? $_POST['packaging_qt'] : '0';
	
	if($waste_qty != '0'){
		$send_to=$_POST['wastedpt'];
	}
	$userId=$_POST['userId'];

	$status = false;

	//$adId = explode(",",$adminIds);

	$insertcount = 0;

	$additonalQty = 0;

	$balanceQty = 0;

	$admindpt_parent_details ='';

	$tempBoxvar = $totalBoxs;

	$sql="select * from admin_dpts where id in (".$adminIds.") order by send_to_quantity desc;";
	$res=mysqli_query($con,$sql);
	if (mysqli_num_rows($res) > 0) 
	{
		while($rows=mysqli_fetch_assoc($res)){
			$totalqty = $rows["send_to_quantity"];
			$lotnumber = $rows["lotnumber"];
			if($insertcount == 0 and $waste_qty != '0'){
				$producItemId=$rows["productItem_id"];
				$initialQty = $rows["initial_quantity"];
				$initialQtyType=$rows["initial_qnty_type"];
				$send_to_qtny_type=$rows["send_to_qtny_type"];
				$ptype = $rows["ptype"];
				$finalProductId = $rows["final_product"];
				$storageId = $rows["storageId"];
				$wasteAdminId = $rows["id"];
				
				$query = "INSERT INTO admin_dpts
				(lotnumber,send_from, send_to, productItem_id, initial_quantity, initial_qnty_type,inputQty, ptype, final_product, send_to_quantity, send_to_qtny_type, waste, status, admindpt_parent_id,storageId,author)
				VALUES('".$lotnumber."','2', '".$send_to."', '".$producItemId."', '".$initialQty."', '".$initialQtyType."', ".$waste_qty.",'".$ptype."', '".$finalProductId."', ".$waste_qty.", ".$send_to_qtny_type.", '4', 1,".$wasteAdminId.",'".$storageId."',".$userId.");";

				$queryrun = mysqli_query($con, $query);
				
				if($queryrun >0){
					$last_id = mysqli_insert_id($con);
					$query = "INSERT INTO admin_dpts_history
					(lotnumber,send_from, send_to, productItem_id, initial_quantity, initial_qnty_type,inputQty, ptype, final_product, send_to_quantity, send_to_qtny_type, waste, status, admindpt_parent_id,storageId,parent_id,author)
				VALUES('".$lotnumber."','2', '".$send_to."', '".$producItemId."', '".$initialQty."', '".$initialQtyType."', ".$waste_qty.",'".$ptype."', '".$finalProductId."', ".$waste_qty.", ".$send_to_qtny_type.", '4', 1,".$wasteAdminId.",'".$storageId."',".$last_id.",".$userId.");";
					 
					$queryrun = mysqli_query($con, $query);
					
					if($queryrun >0){
						$totalqty = $totalqty-$waste_qty;
						$query2 = "update admin_dpts set send_to_quantity = ".$totalqty." where id=".$wasteAdminId ;
						
						$querysrun2 = mysqli_query($con, $query2);
						
					}
				}
			}

			if($tempBoxvar !=0){
				if(($per_box_quantity * $tempBoxvar) <= $totalqty){
					while($tempBoxvar !=0){
						$query = "INSERT INTO package_to_stock
						(lotnumber,final_product, send_to_quantity, send_to_qtny_type, status, totalBoxs, admindpt_parent_details, storageId, author)
						VALUES('".$lotnumber."','".$rows["final_product"]."', ".$per_box_quantity.", ".$rows["send_to_qtny_type"].", 1, ".$tempBoxvar.",'".$rows["id"]."-".$per_box_quantity."' ,'".$rows["storageId"]."', ".$userId.");";

						$queryrun = mysqli_query($con, $query);
							
						if($queryrun >0){
							$last_id = mysqli_insert_id($con);
							$query = "INSERT INTO package_to_stock_history
							(lotnumber,final_product, send_to_quantity, send_to_qtny_type, status, totalBoxs, admindpt_parent_details, storageId, author,parent_id)
							VALUES('".$lotnumber."','".$rows["final_product"]."', ".$per_box_quantity.", ".$rows["send_to_qtny_type"].", 1, ".$tempBoxvar.",'".$rows["id"]."-".$per_box_quantity."', '".$rows["storageId"]."', ".$userId.",".$last_id.");";
							 
							$queryrun = mysqli_query($con, $query);
							
							if($queryrun >0){
								$tquantity=$totalqty-($per_box_quantity * $tempBoxvar);

								$query2 = "update admin_dpts set send_to_quantity = ".$tquantity." where id=".$rows["id"] ;
								
								$querysrun2 = mysqli_query($con, $query2);
								if($querysrun2 >0)
								{	
									$totalqty = $tquantity;
									$insertcount += $tempBoxvar;	
									$tempBoxvar = 0;
														
								}
							}
						}
						
					}
				}else{

					if($balanceQty == 0 and $per_box_quantity <=$totalqty){
						$tquantity =0;
						$insertedboxes = 0;
						while($totalqty >= $per_box_quantity){
							
							$tquantity=$totalqty-$per_box_quantity;
							$totalqty = $tquantity;
							$insertcount++;	
							$tempBoxvar--;
							
							$insertedboxes++;
							if($tempBoxvar == 0){
								break;
							}
							
						}
						
						$query = "INSERT INTO package_to_stock
							(lotnumber,final_product, send_to_quantity, send_to_qtny_type, status, totalBoxs, admindpt_parent_details, storageId, author)
							VALUES('".$lotnumber."','".$rows["final_product"]."', ".$per_box_quantity.", ".$rows["send_to_qtny_type"].", 1, ".$insertedboxes.",'".$rows["id"]."-".$per_box_quantity."' , '".$rows["storageId"]."', ".$userId.");";

						$queryrun = mysqli_query($con, $query);
							
						if($queryrun >0){
							$last_id = mysqli_insert_id($con);
							$query = "INSERT INTO package_to_stock_history
							(lotnumber,final_product, send_to_quantity, send_to_qtny_type, status, totalBoxs, admindpt_parent_details, storageId, author,parent_id)
							VALUES('".$lotnumber."','".$rows["final_product"]."', ".$per_box_quantity.", ".$rows["send_to_qtny_type"].", 1, ".$insertedboxes.",'".$rows["id"]."-".$per_box_quantity."', '".$rows["storageId"]."', ".$userId.",".$last_id.");";
							
							$queryrun = mysqli_query($con, $query);
							
							if($queryrun >0){
								
								$query2 = "update admin_dpts set send_to_quantity = ".$tquantity." where id=".$rows["id"] ;
								
								$querysrun2 = mysqli_query($con, $query2);
								if($querysrun2 >0)
								{	
									$admindpt_parent_details = $rows["id"];	
									
								}
							}
						}

						if($tempBoxvar !=0 and $totalqty !=0){
							$balanceQty = $totalqty;
						}
											
					}else if($balanceQty < $per_box_quantity){
						$additonalQty = $per_box_quantity - $balanceQty;
						$totalqty=$totalqty - $additonalQty;
						
						$query = "INSERT INTO package_to_stock
						(lotnumber,final_product, send_to_quantity, send_to_qtny_type, status, totalBoxs, admindpt_parent_details, storageId, author)
						VALUES('".$lotnumber."','".$rows["final_product"]."', ".$per_box_quantity.", ".$rows["send_to_qtny_type"].", 1, 1,'".$rows["id"]."-".$additonalQty.",".$admindpt_parent_details."-".$balanceQty."' , '".$rows["storageId"]."', ".$userId.");";

						$queryrun = mysqli_query($con, $query);
							
						if($queryrun >0){
							$last_id = mysqli_insert_id($con);
							$query = "INSERT INTO package_to_stock_history
							(lotnumber,final_product, send_to_quantity, send_to_qtny_type, status, totalBoxs, admindpt_parent_details, storageId, author,parent_id)
							VALUES('".$lotnumber."','".$rows["final_product"]."', ".$per_box_quantity.", ".$rows["send_to_qtny_type"].", 1, 1,'".$rows["id"]."-".$additonalQty.",".$admindpt_parent_details."-".$balanceQty."','".$rows["storageId"]."', ".$userId.",".$last_id.");";
							 
							$queryrun = mysqli_query($con, $query);
							
							$querysrun2 = mysqli_query($con, $query);
							if($querysrun2 >0)
							{	
								$query2 = "update admin_dpts set send_to_quantity = ".$totalqty." where id=".$rows["id"];
							
								$querysrun2 = mysqli_query($con, $query2);
								if($querysrun2 >0)
								{
									$insertcount++;	
									$tempBoxvar--;
								}
							}
							
						}

						$tquantity =0;
						$insertedboxes = 0;
						while($totalqty >= $per_box_quantity){
							
							$tquantity=$totalqty-$per_box_quantity;
							$totalqty = $tquantity;
							$insertcount++;	
							$tempBoxvar--;
							
							$insertedboxes++;
							if($tempBoxvar == 0){
								break;
							}
							
						}
						
						$query = "INSERT INTO package_to_stock
							(lotnumber,final_product, send_to_quantity, send_to_qtny_type, status, totalBoxs, admindpt_parent_details, storageId, author)
							VALUES('".$lotnumber."','".$rows["final_product"]."', ".$per_box_quantity.", ".$rows["send_to_qtny_type"].", 1, ".$insertedboxes.",'".$rows["id"]."-".$per_box_quantity."' , '".$rows["storageId"]."', ".$userId.");";

						$queryrun = mysqli_query($con, $query);
							
						if($queryrun >0){
							$last_id = mysqli_insert_id($con);
							$query = "INSERT INTO package_to_stock_history
							(lotnumber,final_product, send_to_quantity, send_to_qtny_type, status, totalBoxs, admindpt_parent_details, storageId, author,parent_id)
							VALUES('".$lotnumber."','".$rows["final_product"]."', ".$per_box_quantity.", ".$rows["send_to_qtny_type"].", 1, ".$insertedboxes.",'".$rows["id"]."-".$per_box_quantity."', '".$rows["storageId"]."', ".$userId.",".$last_id.");";
							
							$queryrun = mysqli_query($con, $query);
							
							if($queryrun >0){
								
								$query2 = "update admin_dpts set send_to_quantity = ".$tquantity." where id=".$rows["id"] ;
								
								$querysrun2 = mysqli_query($con, $query2);
								if($querysrun2 >0)
								{	
									$admindpt_parent_details = $rows["id"];	
									
								}
							}
						}
					}
				}
			}
			
		}

	}
	

	if($insertcount == $totalBoxs){
		$status = true;		
	}
	
	$myObj = [ 'status' => $status];
	mysqli_close($con);
	header('Content-type: application/json');
	
	echo json_encode($myObj);
}else if($_POST['type'] == 'multiPackageSendToStock')
{		
	$send_to_quantity=$_POST['sqty'];
		
	$waste_qty =$_POST['wqty'] ;
	
	$noofboxs =  $_POST['packaging_qt'];
	
	$number= count($_POST["adminId"]);

	$userId=$_POST['userId'];

	$insertedCount =0;
	if($number > 0)
	{
		
    	for($j=0; $j < $number; $j++)
		{
			$adminIdml=mysqli_real_escape_string($con,$_POST["adminId"][$j]);
			$per_box_quantity=mysqli_real_escape_string($con,$_POST["sqty"][$j]);
			$totalBoxs=mysqli_real_escape_string($con,$_POST["packaging_qt"][$j]);
			$waste_qty=mysqli_real_escape_string($con,$_POST["wqty"][$j]);
			$is_single=mysqli_real_escape_string($con,$_POST["is_single"][$j]);
			

			if($waste_qty != '0'){
				$send_to=mysqli_real_escape_string($con,$_POST["wastedpt"][$j]);
			}

			$internalinsert = 0;

			$additonalQty = 0;

			$balanceQty = 0;

			$admindpt_parent_details ='';

			$tempBoxvar = $totalBoxs;

			if($is_single == 1){
				$sql="select * from admin_dpts where id in (".$adminIdml.") order by send_to_quantity desc;";
				$res=mysqli_query($con,$sql);
				if (mysqli_num_rows($res) > 0) 
				{
					while($rows=mysqli_fetch_assoc($res)){
						$totalqty = $rows["send_to_quantity"];
						$lotnumber = $rows["lotnumber"];
						if($internalinsert == 0 and $waste_qty != '0'){
							$producItemId=$rows["productItem_id"];
							$initialQty = $rows["initial_quantity"];
							$initialQtyType=$rows["initial_qnty_type"];
							$send_to_qtny_type=$rows["send_to_qtny_type"];
							$ptype = $rows["ptype"];
							$finalProductId = $rows["final_product"];
							$storageId = $rows["storageId"];
							$wasteAdminId = $rows["id"];
							

							$query = "INSERT INTO admin_dpts
							(lotnumber,send_from, send_to, productItem_id, initial_quantity, initial_qnty_type,inputQty, ptype, final_product, send_to_quantity, send_to_qtny_type, waste, status, admindpt_parent_id,storageId,author)
							VALUES('".$lotnumber."','2', '".$send_to."', '".$producItemId."', '".$initialQty."', '".$initialQtyType."', ".$waste_qty.",'".$ptype."', '".$finalProductId."', ".$waste_qty.", ".$send_to_qtny_type.", '4', 1,".$wasteAdminId.",'".$storageId."',".$userId.");";

							$queryrun = mysqli_query($con, $query);
							
							if($queryrun >0){
								$last_id = mysqli_insert_id($con);
								$query = "INSERT INTO admin_dpts_history
								(lotnumber,send_from, send_to, productItem_id, initial_quantity, initial_qnty_type,inputQty, ptype, final_product, send_to_quantity, send_to_qtny_type, waste, status, admindpt_parent_id,storageId,parent_id,author)
							VALUES('".$lotnumber."','2', '".$send_to."', '".$producItemId."', '".$initialQty."', '".$initialQtyType."', ".$waste_qty.",'".$ptype."', '".$finalProductId."', ".$waste_qty.", ".$send_to_qtny_type.", '4', 1,".$wasteAdminId.",'".$storageId."',".$last_id.",".$userId.");";
								
								$queryrun = mysqli_query($con, $query);
								
								if($queryrun >0){
									$totalqty = $totalqty-$waste_qty;
									$query2 = "update admin_dpts set send_to_quantity = ".$totalqty." where id=".$wasteAdminId ;
							
									$querysrun2 = mysqli_query($con, $query2);
								}
							}
						}

						if($tempBoxvar !=0){
							if(($per_box_quantity * $tempBoxvar) <= $totalqty){
								while($tempBoxvar !=0){
									$query = "INSERT INTO package_to_stock
									(lotnumber,final_product, send_to_quantity, send_to_qtny_type, status, totalBoxs, admindpt_parent_details, storageId, author)
									VALUES('".$lotnumber."','".$rows["final_product"]."', ".$per_box_quantity.", ".$rows["send_to_qtny_type"].", 1, ".$tempBoxvar.",'".$rows["id"]."-".$per_box_quantity."' , '".$rows["storageId"]."', ".$userId.");";

									$queryrun = mysqli_query($con, $query);
										
									if($queryrun >0){
										$last_id = mysqli_insert_id($con);
										$query = "INSERT INTO package_to_stock_history
										(lotnumber,final_product, send_to_quantity, send_to_qtny_type, status, totalBoxs, admindpt_parent_details, storageId, author,parent_id)
										VALUES('".$lotnumber."','".$rows["final_product"]."', ".$per_box_quantity.", ".$rows["send_to_qtny_type"].", 1, ".$tempBoxvar.",'".$rows["id"]."-".$per_box_quantity."', '".$rows["storageId"]."', ".$userId.",".$last_id.");";
										
										$queryrun = mysqli_query($con, $query);
										
										if($queryrun >0){
											$tquantity=$totalqty-($per_box_quantity * $tempBoxvar);

											$query2 = "update admin_dpts set send_to_quantity = ".$tquantity." where id=".$rows["id"] ;
											
											$querysrun2 = mysqli_query($con, $query2);
											if($querysrun2 >0)
											{	
												$totalqty = $tquantity;
												$internalinsert +=$tempBoxvar ;	
												$tempBoxvar = 0;
																	
											}
										}
									}
									
								}
							}else{

								if($balanceQty == 0 and $per_box_quantity <=$totalqty){
									$tquantity =0;
									$insertedboxes = 0;
									while($totalqty >= $per_box_quantity){
										
										$tquantity=$totalqty-$per_box_quantity;
										$totalqty = $tquantity;
										$internalinsert++;	
										$tempBoxvar--;
										
										$insertedboxes++;
										if($tempBoxvar == 0){
											break;
										}
										
									}
									
									$query = "INSERT INTO package_to_stock
									(lotnumber,final_product, send_to_quantity, send_to_qtny_type, status, totalBoxs, admindpt_parent_details, storageId, author)
									VALUES('".$lotnumber."','".$rows["final_product"]."', ".$per_box_quantity.", ".$rows["send_to_qtny_type"].", 1, ".$insertedboxes.",'".$rows["id"]."-".$per_box_quantity."' , '".$rows["storageId"]."', ".$userId.");";

									$queryrun = mysqli_query($con, $query);
										
									if($queryrun >0){
										$last_id = mysqli_insert_id($con);
										$query = "INSERT INTO package_to_stock_history
										(lotnumber,final_product, send_to_quantity, send_to_qtny_type, status, totalBoxs, admindpt_parent_details, storageId, author,parent_id)
										VALUES('".$lotnumber."','".$rows["final_product"]."', ".$per_box_quantity.", ".$rows["send_to_qtny_type"].", 1,".$insertedboxes.",'".$rows["id"]."-".$per_box_quantity."', '".$rows["storageId"]."', ".$userId.",".$last_id.");";
										
										$queryrun = mysqli_query($con, $query);
										
										if($queryrun >0){
										
											$query2 = "update admin_dpts set send_to_quantity = ".$tquantity." where id=".$rows["id"] ;
											
											$querysrun2 = mysqli_query($con, $query2);
											if($querysrun2 >0)
											{	
												$admindpt_parent_details = $rows["id"];	
											}
										}
									}	
									

									if($tempBoxvar !=0 and $totalqty !=0){
										$balanceQty = $totalqty;
									}
														
								}else if($balanceQty < $per_box_quantity){
									$additonalQty = $per_box_quantity - $balanceQty;
									$totalqty=$totalqty - $additonalQty;
									
									$query = "INSERT INTO package_to_stock
									(lotnumber,final_product, send_to_quantity, send_to_qtny_type, status, totalBoxs, admindpt_parent_details, storageId, author)
									VALUES('".$lotnumber."','".$rows["final_product"]."', ".$per_box_quantity.", ".$rows["send_to_qtny_type"].", 1, 1,'".$rows["id"]."-".$additonalQty.",".$admindpt_parent_details."-".$balanceQty."' , '".$rows["storageId"]."', ".$userId.");";

									$queryrun = mysqli_query($con, $query);
										
									if($queryrun >0){
										$last_id = mysqli_insert_id($con);
										$query = "INSERT INTO package_to_stock_history
										(lotnumber,final_product, send_to_quantity, send_to_qtny_type, status, totalBoxs, admindpt_parent_details, storageId, author,parent_id)
										VALUES('".$lotnumber."','".$rows["final_product"]."', ".$per_box_quantity.", ".$rows["send_to_qtny_type"].", 1, 1,'".$rows["id"]."-".$additonalQty.",".$admindpt_parent_details."-".$balanceQty."','".$rows["storageId"]."', ".$userId.",".$last_id.");";
										
										$querysrun2 = mysqli_query($con, $query);
										if($querysrun2 >0)
										{	
											$query2 = "update admin_dpts set send_to_quantity = ".$totalqty." where id=".$rows["id"];
										
											$querysrun2 = mysqli_query($con, $query2);
											if($querysrun2 >0)
											{
												$internalinsert++;	
												$tempBoxvar--;
											}
										}
										
									}

									$tquantity =0;
									$insertedboxes = 0;
									while($totalqty >= $per_box_quantity){
										
										$tquantity=$totalqty-$per_box_quantity;
										$totalqty = $tquantity;
										$internalinsert++;	
										$tempBoxvar--;
										
										$insertedboxes++;
										if($tempBoxvar == 0){
											break;
										}
										
									}
									
									$query = "INSERT INTO package_to_stock
									(lotnumber,final_product, send_to_quantity, send_to_qtny_type, status, totalBoxs, admindpt_parent_details, storageId, author)
									VALUES('".$lotnumber."','".$rows["final_product"]."', ".$per_box_quantity.", ".$rows["send_to_qtny_type"].", 1, ".$insertedboxes.",'".$rows["id"]."-".$per_box_quantity."' , '".$rows["storageId"]."', ".$userId.");";

									$queryrun = mysqli_query($con, $query);
										
									if($queryrun >0){
										$last_id = mysqli_insert_id($con);
										$query = "INSERT INTO package_to_stock_history
										(lotnumber,final_product, send_to_quantity, send_to_qtny_type, status, totalBoxs, admindpt_parent_details, storageId, author,parent_id)
										VALUES('".$lotnumber."','".$rows["final_product"]."', ".$per_box_quantity.", ".$rows["send_to_qtny_type"].", 1,".$insertedboxes.",'".$rows["id"]."-".$per_box_quantity."', '".$rows["storageId"]."', ".$userId.",".$last_id.");";
										
										$queryrun = mysqli_query($con, $query);
										
										if($queryrun >0){
										
											$query2 = "update admin_dpts set send_to_quantity = ".$tquantity." where id=".$rows["id"] ;
											
											$querysrun2 = mysqli_query($con, $query2);
											if($querysrun2 >0)
											{	
												$admindpt_parent_details = $rows["id"];	
											}
										}
									}
								}
							}
						}
						
					}

				}
				
				if($internalinsert == $totalBoxs){
					$insertedCount++;	
				}
			}else{
				$sql= "select adm.*, `productItem_id`, `initial_quantity`, `initial_qnty_type`, `inputQty`, `ptype`, `admindpt_parent_id`, `admindptml_parentId`, `storageId`, `water_wt` from 
				admin_dpts_mul_raw adm, admin_dpts_mul_raw_child admrc where adm.lotnumber = admrc.lotnumber and adm.id in (".$adminIdml.") order by send_to_quantity desc;";
				
				$res=mysqli_query($con,$sql);
				if (mysqli_num_rows($res) > 0) 
				{
					while($rows=mysqli_fetch_assoc($res)){
						$totalqty = $rows["send_to_quantity"];
						$lotnumber = $rows["lotnumber"];
						if($internalinsert == 0 and $waste_qty != '0'){
							$producItemId=$rows["productItem_id"];
							$initialQty = $rows["initial_quantity"];
							$initialQtyType=$rows["initial_qnty_type"];
							$send_to_qtny_type=$rows["send_to_qtny_type"];
							$ptype = $rows["ptype"];
							$finalProductId = $rows["final_product"];
							$storageId = $rows["storageId"];
							$wasteAdminId = $rows["id"];
							
							$query = "INSERT INTO admin_dpts_mul_raw
							(send_from, send_to, lotnumber,final_product, send_to_quantity, send_to_qtny_type, waste, status,author)
							VALUES('2', '".$send_to."', '".$lotnumber."','".$finalProductId."', ".$waste_qty.", ".$send_to_qtny_type.", '4', 1,".$userId.");";

							$queryrun = mysqli_query($con, $query);
							
							if($queryrun >0){
								$last_id = mysqli_insert_id($con);
								$query = "INSERT INTO admin_dpts_mul_raw_history
								(send_from, send_to, lotnumber,final_product, send_to_quantity, send_to_qtny_type, waste, status, parent_id,author)
								VALUES('2', '".$send_to."', '".$lotnumber."','".$finalProductId."', ".$waste_qty.", ".$send_to_qtny_type.", '4', 1,".$last_id.",".$userId.");";
								
								$queryrun = mysqli_query($con, $query);
								
								if($queryrun >0){
									$query = "INSERT INTO admin_dpts_mul_raw_child
									(productItem_id, initial_quantity, initial_qnty_type,inputQty, ptype, lotnumber ,admindptml_parentId,storageId,admr_parent_id)
									VALUES('".$producItemId."', '".$initialQty."', '".$initialQtyType."', '".$waste_qty."','".$ptype."','".$lotnumber."' ,".$wasteAdminId.",'".$storageId."',".$last_id.");";

									$queryrun = mysqli_query($con, $query);
									
									if($queryrun >0){
										$last_idh = mysqli_insert_id($con);
										$query = "INSERT INTO admin_dpts_mul_raw_child_history
										(productItem_id, initial_quantity, initial_qnty_type,inputQty, ptype, lotnumber ,admindptml_parentId,storageId,admin_dpts_mul_raw_child_parent,admr_parent_id)
										VALUES('".$producItemId."', '".$initialQty."', '".$initialQtyType."', '".$waste_qty."','".$ptype."','".$lotnumber."' ,".$wasteAdminId.",'".$storageId."',".$last_idh.",".$last_id.");";

										$queryrun = mysqli_query($con, $query);
										
										if($queryrun >0){
											$totalqty = $totalqty-$waste_qty;
											$query2 = "update admin_dpts_mul_raw set send_to_quantity = ".$totalqty." where id=".$wasteAdminId ;
											
											$querysrun2 = mysqli_query($con, $query2);	

										}
									}
															
								}
							}
						}

						if($tempBoxvar !=0){
							if(($per_box_quantity * $tempBoxvar) <= $totalqty){
								while($tempBoxvar !=0){
									$query = "INSERT INTO package_to_stock
									(lotnumber,final_product, send_to_quantity, send_to_qtny_type, status, totalBoxs, admindpt_parent_details, storageID_ml, author)
									VALUES('".$lotnumber."','".$rows["final_product"]."', ".$per_box_quantity.", ".$rows["send_to_qtny_type"].", 1, ".$tempBoxvar.",'".$rows["id"]."-".$per_box_quantity."' , '".$rows["storageId"]."', ".$userId.");";

									$queryrun = mysqli_query($con, $query);
										
									if($queryrun >0){
										$last_id = mysqli_insert_id($con);
										$query = "INSERT INTO package_to_stock_history
										(lotnumber,final_product, send_to_quantity, send_to_qtny_type, status, totalBoxs, admindpt_parent_details, storageID_ml, author,parent_id)
										VALUES('".$lotnumber."','".$rows["final_product"]."', ".$per_box_quantity.", ".$rows["send_to_qtny_type"].", 1, ".$tempBoxvar.",'".$rows["id"]."-".$per_box_quantity."', '".$rows["storageId"]."', ".$userId.",".$last_id.");";
										
										$queryrun = mysqli_query($con, $query);
										
										if($queryrun >0){
											$tquantity=$totalqty-($per_box_quantity * $tempBoxvar);

											$query2 = "update admin_dpts_mul_raw set send_to_quantity = ".$tquantity." where id=".$rows["id"] ;
											
											$querysrun2 = mysqli_query($con, $query2);
											if($querysrun2 >0)
											{	
												$totalqty = $tquantity;
												$internalinsert += $tempBoxvar;	
												$tempBoxvar = 0;
																	
											}
										}
									}
									
								}
							}else{

								if($balanceQty == 0 and $per_box_quantity <=$totalqty){
									$tquantity =0;
									$insertedboxes = 0;
									while($totalqty >= $per_box_quantity){
										
										$tquantity=$totalqty-$per_box_quantity;
										$totalqty = $tquantity;
										$internalinsert++;	
										$tempBoxvar--;
										
										$insertedboxes++;
										if($tempBoxvar == 0){
											break;
										}
										
									}
									
									$query = "INSERT INTO package_to_stock
									(lotnumber,final_product, send_to_quantity, send_to_qtny_type, status, totalBoxs, admindpt_parent_details, storageID_ml, author)
									VALUES('".$lotnumber."','".$rows["final_product"]."', ".$per_box_quantity.", ".$rows["send_to_qtny_type"].", 1, ".$insertedboxes.",'".$rows["id"]."-".$per_box_quantity."' , '".$rows["storageId"]."', ".$userId.");";

									$queryrun = mysqli_query($con, $query);
										
									if($queryrun >0){
										$last_id = mysqli_insert_id($con);
										$query = "INSERT INTO package_to_stock_history
										(lotnumber,final_product, send_to_quantity, send_to_qtny_type, status, totalBoxs, admindpt_parent_details, storageID_ml, author,parent_id)
										VALUES('".$lotnumber."','".$rows["final_product"]."', ".$per_box_quantity.", ".$rows["send_to_qtny_type"].", 1, ".$insertedboxes.",'".$rows["id"]."-".$per_box_quantity."', '".$rows["storageId"]."', ".$userId.",".$last_id.");";
										
										$queryrun = mysqli_query($con, $query);
										
										if($queryrun >0){
											
											$query2 = "update admin_dpts_mul_raw set send_to_quantity = ".$tquantity." where id=".$rows["id"] ;
											
											$querysrun2 = mysqli_query($con, $query2);
											if($querysrun2 >0)
											{	
												$admindpt_parent_details = $rows["id"];		

											}
										}
									}
									

									if($tempBoxvar !=0 and $totalqty !=0){
										$balanceQty = $totalqty;
									}
																
								}else if($balanceQty < $per_box_quantity){
									$additonalQty = $per_box_quantity - $balanceQty;
									$totalqty=$totalqty - $additonalQty;
									
									$query = "INSERT INTO package_to_stock
									(lotnumber,final_product, send_to_quantity, send_to_qtny_type, status, totalBoxs, admindpt_parent_details, storageID_ml, author)
									VALUES('".$lotnumber."','".$rows["final_product"]."', ".$per_box_quantity.", ".$rows["send_to_qtny_type"].", 1, 1,'".$rows["id"]."-".$additonalQty.",".$admindpt_parent_details."-".$balanceQty."' , '".$rows["storageId"]."', ".$userId.");";

									$queryrun = mysqli_query($con, $query);
										
									if($queryrun >0){
										$last_id = mysqli_insert_id($con);
										$query = "INSERT INTO package_to_stock_history
										(lotnumber,final_product, send_to_quantity, send_to_qtny_type, status, totalBoxs, admindpt_parent_details, storageID_ml, author,parent_id)
										VALUES('".$lotnumber."','".$rows["final_product"]."', ".$per_box_quantity.", ".$rows["send_to_qtny_type"].", 1, 1,'".$rows["id"]."-".$additonalQty.",".$admindpt_parent_details."-".$balanceQty."','".$rows["storageId"]."', ".$userId.",".$last_id.");";
										
										$querysrun2 = mysqli_query($con, $query);
										if($querysrun2 >0)
										{	
											$query2 = "update admin_dpts_mul_raw set send_to_quantity = ".$totalqty." where id=".$rows["id"];
										
											$querysrun2 = mysqli_query($con, $query2);
											if($querysrun2 >0)
											{
												$internalinsert++;	
												$tempBoxvar--;
											}
										}
										
									}

									$tquantity =0;
									$insertedboxes = 0;
									while($totalqty >= $per_box_quantity){
										
										$tquantity=$totalqty-$per_box_quantity;
										$totalqty = $tquantity;
										$internalinsert++;	
										$tempBoxvar--;
										
										$insertedboxes++;
										if($tempBoxvar == 0){
											break;
										}
										
									}
									
									$query = "INSERT INTO package_to_stock
									(lotnumber,final_product, send_to_quantity, send_to_qtny_type, status, totalBoxs, admindpt_parent_details, storageID_ml, author)
									VALUES('".$lotnumber."','".$rows["final_product"]."', ".$per_box_quantity.", ".$rows["send_to_qtny_type"].", 1, ".$insertedboxes.",'".$rows["id"]."-".$per_box_quantity."' , '".$rows["storageId"]."', ".$userId.");";

									$queryrun = mysqli_query($con, $query);
										
									if($queryrun >0){
										$last_id = mysqli_insert_id($con);
										$query = "INSERT INTO package_to_stock_history
										(lotnumber,final_product, send_to_quantity, send_to_qtny_type, status, totalBoxs, admindpt_parent_details, storageID_ml, author,parent_id)
										VALUES('".$lotnumber."','".$rows["final_product"]."', ".$per_box_quantity.", ".$rows["send_to_qtny_type"].", 1, ".$insertedboxes.",'".$rows["id"]."-".$per_box_quantity."', '".$rows["storageId"]."', ".$userId.",".$last_id.");";
										
										$queryrun = mysqli_query($con, $query);
										
										if($queryrun >0){
											
											$query2 = "update admin_dpts_mul_raw set send_to_quantity = ".$tquantity." where id=".$rows["id"] ;
											
											$querysrun2 = mysqli_query($con, $query2);
											if($querysrun2 >0)
											{	
												$admindpt_parent_details = $rows["id"];		

											}
										}
									}
								}
							}
						}
						
					}

				}
				

				if($internalinsert == $totalBoxs){
					$insertedCount++;	
				}
			}
			
			
	        		    
		}

		if($insertedCount == 0){
			$myObj = [ 'status' => false,'msg'=>'Failed to Send products'];
		}else{
			$myObj = [ 'status' => true,'msg'=>$insertedCount." products Sent out of ".$number];
		}
				
	}else{
		$myObj = [ 'status' => false,'msg'=>'No Rows Found'];
	}

	mysqli_close($con);
	header('Content-type: application/json');
	echo json_encode($myObj);
}
else if($_POST['type'] == 'adminEdit')
{
	$adminId=$_POST['editadminId'];
	$send_to_quantity=$_POST['editsend_to_quantity'];
	$send_to_qtny_type=$_POST['editsendqty_typ'];
	$extrawaterwt = isset($_POST['editextrawaterwt']) && !empty($_POST['editextrawaterwt']) ? $_POST['editextrawaterwt'] : '0';
	
	$userId=$_POST['userId'];
	
	$status = false;
	$msg = 'Unable to Edit Details';

	$sql="select * from admin_dpts where id =".$adminId;
	$res=mysqli_query($con,$sql);
	if (mysqli_num_rows($res) > 0) 
	{
		while($rows=mysqli_fetch_assoc($res)){

			if($send_to_quantity == 0){
				$send_to_quantity = $rows["send_to_quantity"];
				$send_to_qtny_type = $rows["send_to_qtny_type"];
			}

			if($extrawaterwt == 0){
				$extrawaterwt = $rows["water_wt"];
			}

			$query = "UPDATE admin_dpts SET send_to_quantity=".$send_to_quantity.", send_to_qtny_type=".$send_to_qtny_type.",water_wt=".$extrawaterwt.", updated_by=current_timestamp() WHERE id=".$adminId.";";

			$queryrun = mysqli_query($con, $query);

			if($queryrun >0){
				$wasteqty = 0;
				if($rows["wasteqty"] !=null){
					$wasteqty = $rows["wasteqty"];
				}

				$lotnumber = $rows["lotnumber"];

				$query = "INSERT INTO admin_dpts_history
				(lotnumber,send_from, send_to, productItem_id, initial_quantity, initial_qnty_type,inputQty, ptype, final_product, send_to_quantity, send_to_qtny_type, wtype,wasteqty, waste, status, water_wt, admindpt_parent_id,storageId,parent_id,updated_by,author)
			VALUES('".$lotnumber."','".$rows["send_from"]."', '".$rows["send_to"]."', '".$rows["productItem_id"]."', '".$rows["initial_quantity"]."', '".$rows["initial_qnty_type"]."', 
			".$rows["inputQty"]." ,'".$rows["ptype"]."', '".$rows["final_product"]."', ".$rows["send_to_quantity"].", ".$rows["send_to_qtny_type"].", '".$rows["wtype"]."',
			".$wasteqty.", '".$rows["waste"]."', 1, ".$rows["water_wt"].", ".$adminId.",'".$rows["storageId"]."',".$adminId.",current_timestamp(),".$userId.");";
				 
				$queryrun = mysqli_query($con, $query);
				if($queryrun >0){
						
					$status = true;	
					$msg = 'Success!';							
					
				}
			}	

		}
	    										
	}
	

	$myObj = [ 'status' => $status,'msg'=>$msg];
	mysqli_close($con);
	header('Content-type: application/json');
	
	echo json_encode($myObj);
}else if($_POST['type'] == 'adminEditFromStorage')
{
	$adminId=$_POST['storageEditAdminId'];
	$send_to_quantity=$_POST['editStorageQuantity'];
	$totalqty=$_POST['totalstrqty'];
	$userId=$_POST['userId'];
		
	$status = false;
	
	$sql="select * from admin_dpts where id =".$adminId;
	$res=mysqli_query($con,$sql);
	
	if (mysqli_num_rows($res) > 0) 
	{
		while($rows=mysqli_fetch_assoc($res)){
			
			$query = "UPDATE admin_dpts set send_to_quantity=".$send_to_quantity.", updated_by=current_timestamp() WHERE id=".$adminId.";";

			$queryrun = mysqli_query($con, $query);
			
			if($queryrun >0){
				
				$query = "INSERT INTO admin_dpts_history
			(send_from, send_to, productItem_id, initial_quantity, initial_qnty_type, ptype, send_to_quantity, send_to_qtny_type, admindpt_parent_id, send_to_dat, send_to_time,storageId,parent_id,updated_by,author)
			VALUES('11','".$rows["send_to"]."', '".$rows["productItem_id"]."', ".$rows["initial_quantity"].",".$rows["initial_qnty_type"].", '".$rows["ptype"]."', ".$rows["send_to_quantity"].",'".$rows["send_to_qtny_type"]."', ".$rows["admindpt_parent_id"].", '".$rows["send_to_dat"]."', '".$rows["send_to_time"]."',".$rows["storageId"].",".$adminId.",current_timestamp(),".$userId.");
			";
				 
				$queryrun = mysqli_query($con, $query);
				
				if($queryrun >0){
						
					$tquantity=$totalqty-$send_to_quantity;

					$query2 = "update total_purchase_qty set quantity = '".$tquantity."' where id=".$rows["storageId"] ;
					
					$querysrun2 = mysqli_query($con, $query2);
					if($querysrun2 >0)
					{	
						$status = true;								
					}
				}
			}	

		}
	    										
	}
	

	$myObj = [ 'status' => $status];
	mysqli_close($con);
	header('Content-type: application/json');
	
	echo json_encode($myObj);
}else if($_POST['type'] == 'adminDelete')
{
	$adminId=$_POST['adminId'];
	$userId=$_POST['userId'];
			
	$status = false;

	$revertDpt='';
	
	$sql="select * from admin_dpts where id in (".$adminId.")";
	$res=mysqli_query($con,$sql);
	
	if (mysqli_num_rows($res) > 0) 
	{
		while($rows=mysqli_fetch_assoc($res)){
			$dptnm = getDepartmentNameById($con,$rows["send_from"]);

			if(strpos($revertDpt, $rows["ptype"]) === false){
				$revertDpt .= $dptnm.",";
			}
			
			$adminDetails = explode(',',$rows["admindpt_parent_id"]);

			$updatedCount=0;

			for($i =0; $i < count($adminDetails); $i++){

				$adminQtyarray = explode('-',$adminDetails[$i]);

				$sql="select * from admin_dpts where id =".$adminQtyarray[0];
				$res2=mysqli_query($con,$sql);
				
				if (mysqli_num_rows($res2) > 0) 
				{
					while($rows2=mysqli_fetch_assoc($res2)){
						$tquantity=$rows["send_to_quantity"]+$rows2["send_to_quantity"];
						$query = "UPDATE admin_dpts set send_to_quantity=".$tquantity.", updated_by=current_timestamp() WHERE id=".$adminQtyarray[0].";";

						$queryrun = mysqli_query($con, $query);
						
						if($queryrun >0){
							$updatedCount++;
						}
					}
					
				}
			}

			if($updatedCount == count($adminDetails)){
				$query = "INSERT INTO admin_dpts_history
				(send_from, send_to, productItem_id, initial_quantity, initial_qnty_type, inputQty,ptype, send_to_quantity, send_to_qtny_type, admindpt_parent_id,storageId,parent_id,deleted_by,author)
				VALUES('".$rows["send_from"]."','".$rows["send_to"]."', '".$rows["productItem_id"]."', '".$rows["initial_quantity"]."','".$rows["initial_qnty_type"]."', 
				".$rows["inputQty"].",'".$rows["ptype"]."', ".$rows["send_to_quantity"].",'".$rows["send_to_qtny_type"]."', '".$rows["admindpt_parent_id"]."',
				'".$rows["storageId"]."',".$rows["id"].",current_timestamp(),".$userId.");";
				
				$queryrun = mysqli_query($con, $query);
				
				if($queryrun >0){
					
					$query2 = "DELETE from admin_dpts where id=".$rows["id"];
					
					$querysrun2 = mysqli_query($con, $query2);
					if($querysrun2 >0)
					{	
						$status = true;								
					}
				}
			}
			
		}
	    										
	}
	
	if(substr($revertDpt,-1) == ','){
		$revertDpt = substr($revertDpt,0,strlen($revertDpt)-1);
	}

	$myObj = [ 'status' => $status,'revertDpt'=>$revertDpt];
	mysqli_close($con);
	header('Content-type: application/json');
	
	echo json_encode($myObj);
}else if($_POST['type'] == 'adminDeleteFromStorage')
{
	$adminId=$_POST['adminId'];
	$userId=$_POST['userId'];
			
	$status = false;

	$sql="select * from admin_dpts where id in (".$adminId.");";
	$res=mysqli_query($con,$sql);
	
	if (mysqli_num_rows($res) > 0) 
	{
		while($rows=mysqli_fetch_assoc($res)){
			$sql="select * from total_purchase_qty where id =".$rows["storageId"];
			$res2=mysqli_query($con,$sql);
			
			if (mysqli_num_rows($res2) > 0) 
			{
				while($rows2=mysqli_fetch_assoc($res2)){
					$tquantity=$rows["send_to_quantity"]+$rows2["quantity"];
					$query = "UPDATE total_purchase_qty set quantity=".$tquantity." WHERE id=".$rows["storageId"].";";

					$queryrun = mysqli_query($con, $query);
					
					if($queryrun >0){
						
						$query = "INSERT INTO admin_dpts_history
					(send_from, send_to, productItem_id, initial_quantity, initial_qnty_type,ptype, send_to_quantity, send_to_qtny_type, admindpt_parent_id,storageId,parent_id,deleted_by,author)
					VALUES('4','".$rows["send_to"]."', '".$rows["productItem_id"]."', ".$rows["initial_quantity"].",".$rows["initial_qnty_type"].",'".$rows["ptype"]."', ".$rows["send_to_quantity"].",'".$rows["send_to_qtny_type"]."', ".$rows["admindpt_parent_id"].",".$rows["storageId"].",".$adminId.",current_timestamp(),".$userId.");
					";
					 
					$queryrun = mysqli_query($con, $query);
					
					if($queryrun >0){
						
						$query2 = "DELETE from admin_dpts where id=".$adminId;
						
						$querysrun2 = mysqli_query($con, $query2);
						if($querysrun2 >0)
						{	
							$status = true;								
						}
					}
				}
			}
				
			}	

		}
	    										
	}
	

	$myObj = [ 'status' => $status];
	mysqli_close($con);
	header('Content-type: application/json');
	
	echo json_encode($myObj);
}else if($_POST['type'] == 'getStorageQuantity')
{
	$storageId =$_POST["storageId"];

	$status = false;
	$storageQty = 0;
	
	$sql1="select * from total_purchase_qty tpq where id =".$storageId.";";
	$result = $con->query($sql1);

	if (mysqli_num_rows($result) > 0) 
	{
		while($row1 = mysqli_fetch_array($result))
		{
			$storageQty = $row1['quantity'];
			$status = true;
		}
	}
	
	$myObj = [ 'status' => $status,'storageQty'=>$storageQty];
	mysqli_close($con);
	header('Content-type: application/json');
	echo json_encode($myObj);
}else if($_POST['type'] == 'validateProductIsProcessed')
{
	$admindpt_ids =$_POST["adminId"];

	$adId = explode(",",$admindpt_ids);
	
	$recordFound =false;

	for($i =0; $i < count($adId); $i++){
		$sql2="select * from admin_dpts ad where admindpt_parent_id like '%".$adId[$i]."%';";
		$result2 = $con->query($sql2);
		if ($result2->num_rows > 0) {
			while($row2 = mysqli_fetch_array($result2))
			{
				$adIds = explode(",",$row2['admindpt_parent_id']);
				for($j =0; $j < count($adIds); $j++){
					$adminarry = explode("-",$adIds[$j]);
					if($adId[$i] == $adminarry[0]){
						$recordFound = true;
						break;
					}
				}
				if($recordFound){
					break;
				}
			}
		}
		if($recordFound){
			break;
		}
	}

	if($recordFound){
		$myObj = [ 'status' => true];
	}else{
		$myObj = [ 'status' => false];
	}

	mysqli_close($con);
	header('Content-type: application/json');
	echo json_encode($myObj);
}else if($_POST['type'] == 'validateProductIsSentToStock')
{
	$admindpt_ids =$_POST["adminId"];
	$is_single =$_POST["is_single"];

	$adId = explode(",",$admindpt_ids);
	
	$recordFound =false;

	for($i =0; $i < count($adId); $i++){
		$whereCon ='';

		if($is_single == '1'){
			$whereCon = " and storageId != '0';";
		}else{
			$whereCon = ' and storageID_ml is not null;';
		}

		$sql2="select * from package_to_stock ad where admindpt_parent_details like '%".$adId[$i]."%'".$whereCon;
		$result2 = $con->query($sql2);
		if ($result2->num_rows > 0) {
			while($row2 = mysqli_fetch_array($result2))
			{
				$adIds = explode(",",$row2['admindpt_parent_details']);
				for($j =0; $j < count($adIds); $j++){
					$adminarry = explode("-",$adIds[$j]);
					if($adId[$i] == $adminarry[0]){
						$recordFound = true;
						break;
					}
				}
				if($recordFound){
					break;
				}
			}
		}
		if($recordFound){
			break;
		}
	}

	if($recordFound){
		$myObj = [ 'status' => true];
	}else{
		$myObj = [ 'status' => false];
	}

	mysqli_close($con);
	header('Content-type: application/json');
	echo json_encode($myObj);
}else if($_POST['type'] == 'scrapSend')
{
	$adminId=$_POST['adminId'];
	$inputQty=$_POST['initialqty'];
	
	$send_to=$_POST['dpt'];
	$userId=$_POST['userId'];
	$itemr=$_POST['itemr'];
	$ptype=$_POST['ptype'];

	$status = false;
	
	$sql="select * from admin_dpts where id =".$adminId;
	$res=mysqli_query($con,$sql);
	if (mysqli_num_rows($res) > 0) 
	{
		while($rows=mysqli_fetch_assoc($res)){
			$totalqty = $rows["wasteqty"];

			$sql="select * from total_purchase_qty where item = '".$itemr."' and quantity_type = '".$rows["wtype"]."' and ptype=".$ptype;
			$res=mysqli_query($con,$sql);

			if (mysqli_num_rows($res) > 0) 
			{
				$row = mysqli_fetch_assoc($res);
				$qt=$row['quantity'];
				$tquantity=$qt+$qty;
				$query2 = "update total_purchase_qty set quantity = '".$tquantity."' where item = '".$itemr."' and quantity_type = '".$rows["wtype"]."' and ptype=".$ptype;
				$querysrun2 = mysqli_query($con, $query2);
				if($querysrun2 >0)
				{	
					$query = "INSERT INTO admin_dpts_history
					(send_from, send_to, productItem_id, initial_quantity, initial_qnty_type, ptype, send_to_quantity, send_to_qtny_type, admindpt_parent_id, send_to_dat, send_to_time,storageId,parent_id,author,waste,final_product)
					VALUES('5','".$send_to."', '".$itemr."', ".$rows["wasteqty"].",".$rows["wtype"].", '".$ptype."', ".$inputQty.",'".$rows["wtype"]."', ".$adminId.", '".$dat."', '".$time."',".$rows["storageId"].",0,".$userId.",'".$rows["waste"]."','".$rows["final_product"]."');
					";
						
					$queryrun = mysqli_query($con, $query);
					if($queryrun >0){
						$tquantity=$totalqty-$send_to_quantity;

						$query2 = "update admin_dpts set wasteqty = '".$tquantity."' where id=".$adminId ;
						
						$querysrun2 = mysqli_query($con, $query2);
						if($querysrun2 >0)
						{	
							$status = true;								
						}
					}								
				}
												
			}else
			{
				$query1 = "INSERT INTO total_purchase_qty(item, quantity_type, quantity,ptype) VALUES('".$itemr."', '".$rows["wtype"]."', ".$inputQty.",".$ptype.");";
											
				$queryrun1 = mysqli_query($con, $query1);
				if($queryrun1 > 0)
				{ 
					$query = "INSERT INTO admin_dpts_history
					(send_from, send_to, productItem_id, initial_quantity, initial_qnty_type, ptype, send_to_quantity, send_to_qtny_type, admindpt_parent_id, send_to_dat, send_to_time,storageId,parent_id,author)
					VALUES('5','".$send_to."', '".$itemr."', ".$rows["wasteqty"].",".$rows["wtype"].", '".$ptype."', ".$inputQty.",'".$rows["wtype"]."', ".$adminId.", '".$dat."', '".$time."',".$rows["storageId"].",0,".$userId.");
					";
						
					$queryrun = mysqli_query($con, $query);
					if($queryrun >0){
						$tquantity=$totalqty-$send_to_quantity;

						$query2 = "update admin_dpts set wasteqty = '".$tquantity."' where id=".$adminId ;
						
						$querysrun2 = mysqli_query($con, $query2);
						if($querysrun2 >0)
						{	
							$status = true;								
						}
					}
				}
			}
			
		}
	    										
	}
	
	$myObj = [ 'status' => $status,'dpt'=> getDepartmentNameById($con,$send_to)];
	mysqli_close($con);
	header('Content-type: application/json');
	
	echo json_encode($myObj);
}else if($_POST['type'] == 'scrapEdit')
{
	$adminId=$_POST['editadminId'];
	$wasteType=$_POST['editwtype'];
	$wasteqty=$_POST['wasteqty'];
	$wqtytype=$_POST['wqtytype'];
	$userId=$_POST['userId'];
	
	$status = false;

	$sql="select * from admin_dpts where id =".$adminId;
	$res=mysqli_query($con,$sql);
	if (mysqli_num_rows($res) > 0) 
	{
		while($rows=mysqli_fetch_assoc($res)){
			if($wasteqty == 0){
				$wasteqty = $rows["wasteqty"];
				$wqtytype = $rows["wtype"];
			}
			
			$query = "UPDATE admin_dpts SET wasteqty=".$wasteqty.", wtype=".$wqtytype.", waste='".$wasteType."', updated_by=current_timestamp() WHERE id=".$adminId.";";

			$queryrun = mysqli_query($con, $query);
			
			if($queryrun >0){
				$query = "INSERT INTO admin_dpts_history
				(send_from, send_to, productItem_id, initial_quantity, initial_qnty_type,inputQty, ptype, final_product, send_to_quantity, send_to_qtny_type,status,waste,wasteqty,wtype, admindpt_parent_id,storageId,parent_id,updated_by,author)
			VALUES('0', '".$rows["send_to"]."', '".$rows["productItem_id"]."', '".$rows["initial_quantity"]."', '".$rows["initial_qnty_type"]."', ".$rows["inputQty"].",'".$rows["ptype"]."', '".$rows["final_product"]."', ".$rows["send_to_quantity"].", ".$rows["send_to_qtny_type"].", 1,'".$rows["waste"]."',".$rows["wasteqty"].",'".$rows["wtype"]."','".$adminId."','".$rows["storageId"]."','".$adminId."',current_timestamp(),".$userId.");";
				 
				$queryrun = mysqli_query($con, $query);
				
				if($queryrun >0){
						
					$status = true;								
					
				}
			}	

		}
	    										
	}
	
	$myObj = [ 'status' => $status];
	mysqli_close($con);
	header('Content-type: application/json');
	
	echo json_encode($myObj);
}else if($_POST['type'] == 'scrapDelete')
{
	$adminId=$_POST['adminId'];
	$userId=$_POST['userId'];
		
	$status = false;

	$sql="select * from admin_dpts where id =".$adminId;
	$res=mysqli_query($con,$sql);
	if (mysqli_num_rows($res) > 0) 
	{
		while($rows=mysqli_fetch_assoc($res)){
			
			$query = "UPDATE admin_dpts SET wasteqty=0, wtype=NULL, updated_by=current_timestamp() WHERE id=".$adminId.";";

			$queryrun = mysqli_query($con, $query);
			
			if($queryrun >0){
				$query = "INSERT INTO admin_dpts_history
				(send_from, send_to, productItem_id, initial_quantity, initial_qnty_type,inputQty, ptype, final_product, send_to_quantity, send_to_qtny_type,status,waste,wasteqty,wtype, admindpt_parent_id,storageId,parent_id,deleted_by,author)
			VALUES('0', '".$rows["send_to"]."', '".$rows["productItem_id"]."', ".$rows["initial_quantity"].", '".$rows["initial_qnty_type"]."', ".$rows["inputQty"].",'".$rows["ptype"]."', '".$rows["final_product"]."', ".$rows["send_to_quantity"].", ".$rows["send_to_qtny_type"].", 1,'".$rows["waste"]."',".$rows["wasteqty"].",'".$rows["wtype"]."',".$adminId.",".$rows["storageId"].",".$adminId.",current_timestamp(),".$userId.");";
				 
				$queryrun = mysqli_query($con, $query);
				
				if($queryrun >0){
						
					$status = true;								
					
				}
			}	

		}
	    										
	}
	
	$myObj = [ 'status' => $status];
	mysqli_close($con);
	header('Content-type: application/json');
	
	echo json_encode($myObj);
}else if($_POST['type'] =='viewPackage'){
	$p_id = $_POST['id'];
 	
	/*$q = "select ad.id ,frmd.depart as frmdpt,p.item as finalProdname,p.id as finalprodID,ad.send_to_quantity,sendqt.q_name,sendqt.id as qttypeId,ad.created_at as senddttime,ad.water_wt 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 = 9 and ad.send_to_quantity !=0 and ad.id in (".$p_id.") order by ad.created_at desc";*/
					
					
	$q = "select ad.id ,frmd.depart as frmdpt,p.item as finalProdname,p.id as finalprodID,ad.send_to_quantity,sendqt.q_name,sendqt.id as qttypeId,ad.created_at as senddttime,ad.water_wt from admin_dpts_mul 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 = 9 and ad.send_to_quantity !=0 and ad.id in (".$p_id.") order by ad.created_at desc";				
 
   	$result=mysqli_query($con,$q);
		
	if(mysqli_num_rows($result) > 0)
    { 
		while($row = mysqli_fetch_assoc($result)) 
		{
			$date = new DateTime($row['senddttime'], new DateTimeZone('MST'));
			$date->setTimezone(new DateTimeZone('Asia/Kolkata'));
			$row['senddttime']= $date->format('Y-m-d H:i:s');
			$data[]=$row;
			
		}
		$myObj = [ 'status' => true,'data'=>$data];
	}
	else
	{
		$myObj = [ 'status' => false];
	}
	mysqli_close($con);
	header('Content-type: application/json');
	echo json_encode($myObj);
}else if($_POST['type'] =='viewAdmin'){
	$p_id = $_POST['id'];
 	$q = "select fp.id as finalproductId,ad.ptype as ptypeId,ad.id ,frmd.depart as frmdpt,ad.productItem_id,fp.item as finalprodct,ad.send_to_quantity,sendqt.q_name,
	 sendqt.id as qtytypeid,ad.created_at as senddttime ,ad.water_wt 
		  from admin_dpts ad ,department frmd,final_product fp ,quantity_type sendqt
		  where ad.send_from = frmd.id and ad.final_product = fp.id and ad.send_to_qtny_type = sendqt.id and ad.id in (".$p_id.") order by ad.created_at desc";
 
   	$result=mysqli_query($con,$q);
		
	if(mysqli_num_rows($result) > 0)
    { 
		while($row = mysqli_fetch_assoc($result)) 
		{
			$date = new DateTime($row['senddttime'], new DateTimeZone('MST'));
			$date->setTimezone(new DateTimeZone('Asia/Kolkata'));
			$row['senddttime']= $date->format('Y-m-d H:i:s');

			$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))
			{
				$row['items'] =  $row1['items'];
			} 

			$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))
			{
				$row['prodtypenm'] =  $row1['items'];
			} 

			$data[]=$row;
			
		}
		$myObj = [ 'status' => true,'data'=>$data];
	}
	else
	{
		$myObj = [ 'status' => false];
	}
	mysqli_close($con);
	header('Content-type: application/json');
	echo json_encode($myObj);
}else if($_POST['type'] =='viewStorage'){
	$p_id = $_POST['id'];
 	$q = "select ad.storageId,p2.item as ptypename,p2.id as ptypeId,ad.id ,p.description as prodname,ad.send_to_quantity,sendqt.q_name,
	 ad.created_at as senddttime ,sendqt.id as qtytypeid 
	 from admin_dpts ad ,productitem p ,quantity_type sendqt,productype p2 
	 where ad.productItem_id = p.id and ad.send_to_qtny_type = sendqt.id and ad.ptype = p2.id and 
	 (ad.admindpt_parent_id = 0 or ad.send_from =11) and ad.id in (".$p_id.") order by ad.created_at desc";
 
   	$result=mysqli_query($con,$q);
		
	if(mysqli_num_rows($result) > 0)
    { 
		while($row = mysqli_fetch_assoc($result)) 
		{
			$date = new DateTime($row['senddttime'], new DateTimeZone('MST'));
			$date->setTimezone(new DateTimeZone('Asia/Kolkata'));
			$row['senddttime']= $date->format('Y-m-d H:i:s');

			$data[]=$row;
			
		}
		$myObj = [ 'status' => true,'data'=>$data];
	}
	else
	{
		$myObj = [ 'status' => false];
	}
	mysqli_close($con);
	header('Content-type: application/json');
	echo json_encode($myObj);
}else if($_POST['type'] == 'checkLotNumber'){
	$lotnumber = $_POST['lotnumber'];
	$sql="select lotnumber from admin_dpts ad where lotnumber = ".$lotnumber." union select lotnumber from admin_dpts_mul_raw ad where lotnumber = ".$lotnumber.";";
	$result=mysqli_query($con,$sql);
		
	if(mysqli_num_rows($result) == 0){
		$myObj = [ 'status' => true];
	}else{
		$myObj = [ 'status' => false,'msg'=>'Lot Number already Exist!'];
	}

	mysqli_close($con);
	header('Content-type: application/json');
	echo json_encode($myObj);
}else if($_POST['type'] == 'deletePackageByLotNumber')
{
	$lotnumber=$_POST['lotnumber'];
	
	$userId=$_POST['userId'];
	
	$status = false;

	$revertDpt='';
	
	$sql="select * from admin_dpts where lotnumber = '".$lotnumber."' and send_to=2";
	$res=mysqli_query($con,$sql);
	
	if (mysqli_num_rows($res) > 0) 
	{
		
		while($rows=mysqli_fetch_assoc($res)){
			
			$adminDetails = explode(',',$rows["admindpt_parent_id"]);

			for($i =0; $i < count($adminDetails); $i++){

				$adminQtyarray = explode('-',$adminDetails[$i]);

				$sql="select * from admin_dpts where id =".$adminQtyarray[0];
				$res2=mysqli_query($con,$sql);
				
				if (mysqli_num_rows($res2) > 0) 
				{
					while($rows2=mysqli_fetch_assoc($res2)){
						$tquantity=$adminQtyarray[1]+$rows2["send_to_quantity"];
						$query = "UPDATE admin_dpts set send_to_quantity=".$tquantity.", updated_by=current_timestamp() WHERE id=".$adminQtyarray[0].";";

						$queryrun = mysqli_query($con, $query);

						if($queryrun > 0){
							$query = "INSERT INTO admin_dpts_history
							(send_from, send_to, productItem_id, initial_quantity, initial_qnty_type, inputQty,ptype, send_to_quantity, send_to_qtny_type, admindpt_parent_id,storageId,parent_id,deleted_by,author)
							VALUES('".$rows["send_from"]."','".$rows["send_to"]."', '".$rows["productItem_id"]."', '".$rows["initial_quantity"]."','".$rows["initial_qnty_type"]."', 
							".$rows["inputQty"].",'".$rows["ptype"]."', ".$rows["send_to_quantity"].",'".$rows["send_to_qtny_type"]."', '".$rows["admindpt_parent_id"]."',
							'".$rows["storageId"]."',".$rows["id"].",current_timestamp(),".$userId.");";
							
							$queryrun = mysqli_query($con, $query);
							
							if($queryrun >0){
								
								$query2 = "DELETE from admin_dpts where id=".$rows["id"];
								
								$querysrun2 = mysqli_query($con, $query2);
								if($querysrun2 >0)
								{	
									$status = true;								
								}
							}
						}
						
					}
					
				}
			}

		}
	    										
	}

	$myObj = [ 'status' => $status];
	mysqli_close($con);
	header('Content-type: application/json');
	
	echo json_encode($myObj);
}

function getDepartmentNameById($con,$id) {
    $sql1="select depart from department where id =".$id;
	$res=mysqli_query($con,$sql1);
	while($row1 = mysqli_fetch_array($res))
	{
		$dept = $row1['depart'];
	}

	return $dept;
}
?>