<?php
ini_set('max_execution_time', '300'); //300 seconds = 5 minutes

error_reporting(E_ALL);
ini_set('display_errors', '1');
require_once('../Db/dbconfig.php');


if($_POST['type'] == 'multipleRawMaterialSend'){
	
	$sendFrom=$_POST['sendFrom'];
	$lotnumber=$_POST['lotnumber'];
	
	$send_to_quantity_t=$_POST['sqty'];
	
	$send_to_qtny_type_t=$_POST['sendqty_typ'];

	//$waste_type_t =$_POST['wtype'];

	$waste_qty_type_t = $_POST['waste_qty_typ'];

	$waste_qty_t = $_POST['wqty'];
	
	$extrawaterwt = $_POST['extrawaterwt'];
	
	$fin_product=$_POST['fin_product'];
	
	$send_to=$_POST['dpt'];
	$userId=$_POST['userId'];

	$number= count($_POST["adminId"]);
	$final_pro_number= count($fin_product);
	
	$status = false;

	$insertedCount =0;

	if($number > 0)
	{

		

    	for($i=0; $i < $number; $i++)
		{
			$adminIdml=mysqli_real_escape_string($con,$_POST["adminId"][$i]);
			$inputQty=mysqli_real_escape_string($con,$_POST["qty"][$i]);
			$extrawaterwtml = mysqli_real_escape_string($con,$_POST["extrawaterwt"][$i]);
			$insertedQty = $inputQty;
			$additionalQty = 0;
			$totalAdmin = '';

			$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($insertedQty > 0){
					while($rows=mysqli_fetch_assoc($res)){
						$totalqty = $rows["send_to_quantity"];

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

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

								$query = "INSERT INTO admin_dpts_mul_raw_child
								(lotnumber, productItem_id, initial_quantity,initial_qnty_type, inputQty, ptype, admindpt_parent_id, storageId,water_wt)
								VALUES('".$lotnumber."', '".$rows["productItem_id"]."', '".$rows["initial_quantity"]."', '".$rows["initial_qnty_type"]."', '".$inputQty."','".$rows["ptype"]."', 
								'".$totalAdmin."','".$rows["storageId"]."',".$extrawaterwtml.");";
							
								$queryrun = mysqli_query($con, $query);
								
								if($queryrun >0){
									$last_id = mysqli_insert_id($con);
									$query = "INSERT INTO admin_dpts_mul_raw_child_history
									(lotnumber, productItem_id, initial_quantity,initial_qnty_type, inputQty, ptype, admindpt_parent_id, storageId,admin_dpts_mul_raw_child_parent,water_wt)
								VALUES('".$lotnumber."', '".$rows["productItem_id"]."', '".$rows["initial_quantity"]."', '".$rows["initial_qnty_type"]."', '".$inputQty."','".$rows["ptype"]."', 
								'".$totalAdmin."','".$rows["storageId"]."',".$last_id.",".$extrawaterwtml.");";
									
									$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)
										{	
											$insertedCount++;	
											break;	
										}
									}
								}

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

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

								$query2 = "update admin_dpts set send_to_quantity = 0 where id=".$rows["id"] ;
						
								$querysrun2 = mysqli_query($con, $query2);
								
							}
						}else{
							$tquantity=$totalqty-$additionalQty;

							$insertedQty = 0;
							$totalAdmin .=$rows["id"]."-".$additionalQty;

							$query = "INSERT INTO admin_dpts_mul_raw_child
								(lotnumber, productItem_id, initial_quantity,initial_qnty_type, inputQty, ptype, admindpt_parent_id, storageId,water_wt)
								VALUES('".$lotnumber."', '".$rows["productItem_id"]."', '".$rows["initial_quantity"]."', '".$rows["initial_qnty_type"]."', '".$inputQty."','".$rows["ptype"]."', 
								'".$totalAdmin."','".$rows["storageId"]."',".$extrawaterwtml.");";
							
							$queryrun = mysqli_query($con, $query);
							
							if($queryrun >0){
								$last_id = mysqli_insert_id($con);
								$query = "INSERT INTO admin_dpts_mul_raw_child_history
								(lotnumber, productItem_id, initial_quantity,initial_qnty_type, inputQty, ptype, admindpt_parent_id, storageId,admin_dpts_mul_raw_child_parent,water_wt)
							VALUES('".$lotnumber."', '".$rows["productItem_id"]."', '".$rows["initial_quantity"]."', '".$rows["initial_qnty_type"]."', '".$inputQty."','".$rows["ptype"]."', 
							'".$totalAdmin."','".$rows["storageId"]."',".$last_id.",".$extrawaterwtml.");";
								
								$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)
									{	
										$insertedCount++;
										break;
									}
								}
							}

						}

					}
				}										
			}
		}
 
		if($insertedCount == $number){
			$insertedCount = 0;
			for($i=0; $i < $final_pro_number; $i++)
			{
				$finProduct=mysqli_real_escape_string($con,$_POST["fin_product"][$i]);
				
				$send_to_quantity=mysqli_real_escape_string($con,$_POST["sqty"][$i]);
	
				$send_to_qtny_type=mysqli_real_escape_string($con,$_POST["sendqty_typ"][$i]);
			
				if(isset($_POST['wtype'][$i]) && !empty($_POST['wtype'][$i])){
					$waste_type =mysqli_real_escape_string($con,$_POST["wtype"][$i]);
				}else{
					$waste_type ='';
				}
			
				$waste_qty_type = mysqli_real_escape_string($con,$_POST["waste_qty_typ"][$i]);
			
				$waste_qty = mysqli_real_escape_string($con,$_POST["wqty"][$i]);

				if($waste_qty == ''){
					$waste_qty ='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."', '".$finProduct."', '".$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)
				VALUES('".$lotnumber."','".$sendFrom."', '".$send_to."', '".$finProduct."', '".$send_to_quantity."',
				'".$send_to_qtny_type."', '".$waste_qty_type."',".$waste_qty.", '".$waste_type."', 1,".$userId.");";
					
					$queryrun = mysqli_query($con, $query);
						
					if($queryrun >0){
						$insertedCount++;
					}
				}
			}			
		}

		if($insertedCount == $final_pro_number){
			$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'] == 'adminSendml')
{
	$adminId=$_POST['adminIdr'];
	$sendFrom=$_POST['sendFrom'];
	$inputQty=$_POST['rinitialqty'];
	$send_to_quantity=$_POST['rsend_to_quantity'];
	$send_to_qtny_type=$_POST['rsendqty_typ'];
	$waste_type =$_POST['rwtype'];
	$waste_qty_type = $_POST['rwaste_qty_typ'];
	$waste_qty = isset($_POST['rwaste_qty']) && !empty($_POST['rwaste_qty']) ? $_POST['rwaste_qty'] : '0';
		
	$fin_product=$_POST['rfin_product'];
	$send_to=$_POST['rdpt'];
	$userId=$_POST['userId'];

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

			$query = "INSERT INTO admin_dpts_mul
			(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,admindptml_parentId,storageId,author)
			VALUES('".$sendFrom."', '".$send_to."', '".$rows["productItem_id"]."', '".$rows["initial_quantity"]."', '".$rows["initial_qnty_type"]."', '".$inputQty."','".$rows["ptype"]."', '".$fin_product."', ".$send_to_quantity.", ".$send_to_qtny_type.", '".$waste_qty_type."',".$waste_qty.", '".$waste_type."', 1, ".$adminId.",'".$rows["storageId"]."',".$userId.");";

			$queryrun = mysqli_query($con, $query);
			
			if($queryrun >0){
				$last_id = mysqli_insert_id($con);
				$query = "INSERT INTO admin_dpts_mul_history
				(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, admindptml_parentId,storageId,parent_id,author)
			VALUES('".$sendFrom."', '".$send_to."', '".$rows["productItem_id"]."', '".$rows["initial_quantity"]."', '".$rows["initial_qnty_type"]."','".$inputQty."' ,'".$rows["ptype"]."', '".$fin_product."', ".$send_to_quantity.", ".$send_to_qtny_type.", '".$waste_qty_type."',".$waste_qty.", '".$waste_type."', 1, ".$adminId.",'".$rows["storageId"]."',".$last_id.",".$userId.");";
				 
				$queryrun = mysqli_query($con, $query);
				
				if($queryrun >0){
					$tquantity=$totalqty-$inputQty;

					$query2 = "update admin_dpts_mul set send_to_quantity = '".$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'] == '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 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 (".$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_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;
									$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_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.");";
							 
							$queryrun = mysqli_query($con, $query);
							
							$querysrun2 = mysqli_query($con, $query2);
							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)
								{
									$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_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($insertcount == $totalBoxs){
		$status = true;		
	}
	
	$myObj = [ 'status' => $status,'query'=>$query];
	mysqli_close($con);
	header('Content-type: application/json');
	
	echo json_encode($myObj);
}else if($_POST['type'] == 'stockSend')
{
	$adminIds=$_POST['boxescat'];
	$buyrname=$_POST['buyrname'];
	$isinternational=$_POST['isinternational'];
	
	$inv_no=$_POST['inv_no'];
	$invdat=$_POST['invdat'];
	$noofbox=$_POST['noofbox'];
	$userId=$_POST['userId'];

	$insertedCount=0;
	$dubplicateInv=array();
	
	$sqls="SELECT * FROM stock_to_export where invoice_no='".$inv_no."';";
    $ress=mysqli_query($con,$sqls);

    if (mysqli_num_rows($ress) > 0) {
    	$dubplicateInv[] = $inv_no;
	}else{
		$adId = explode(",",$adminIds);

		for($a=0; $a < count($adId); $a++)
		{	
			if($noofbox !=0){
				$adminId = $adId[$a];
				$sql="SELECT * FROM package_to_stock where id=".$adminId.";";
		        $res=mysqli_query($con,$sql);

			    if (mysqli_num_rows($res) > 0) {
				    $row = mysqli_fetch_assoc($res);
					$totalBoxs = $row["totalBoxs"];
					$lotnumber = $row["lotnumber"];

					if($totalBoxs > $noofbox){
						$tqbox=$totalBoxs-$noofbox;
						/*if($tqbox < $noofbox){
							$noofbox = $noofbox - $tqbox;
						}*/
						$query = "INSERT INTO stock_to_export
						(lotnumber,purchaser_name, quantity_type, quantity, invoice_no, invoice_dt, storageIdml, adminId, final_productId, is_international, no_of_boxes, created_at,author)
						VALUES('".$lotnumber."','".$buyrname."', '".$row['send_to_qtny_type']."', ".$row['send_to_quantity'].", '".$inv_no."', '".$invdat."', '".$row['storageID_ml']."',".$adminId.", ".$row['final_product'].", ".$isinternational.", ".$noofbox.", CURRENT_TIMESTAMP,".$userId.");";
						
						$queryrun = mysqli_query($con, $query);
						if($queryrun > 0)
						{ 
							$last_id = mysqli_insert_id($con);
				
							$query3 = "INSERT INTO stock_to_export_history
							(lotnumber,purchaser_name, quantity_type, quantity, invoice_no, invoice_dt, storage_id, adminId, final_productId, is_international, no_of_boxes, created_at,parent_id,author)
							VALUES('".$lotnumber."','".$buyrname."', '".$row['send_to_qtny_type']."', ".$row['send_to_quantity'].", '".$inv_no."', '".$invdat."', '".$row['storageId']."',".$adminId.", ".$row['final_product'].", ".$isinternational.",".$noofbox.", CURRENT_TIMESTAMP,".$last_id.",".$userId.");";
							
							$queryrun3 = mysqli_query($con, $query3);
							if($queryrun3 > 0)
							{
								if($tqbox == 0){
									$query2 = "update package_to_stock set totalBoxs = 0,send_to_quantity=0 where id=".$adminId;
								}else{
									$query2 = "update package_to_stock set totalBoxs = ".$tqbox." where id=".$adminId;
								}
								
								$querysrun2 = mysqli_query($con, $query2);
								if($querysrun2 >0)
								{
									$insertedCount++;
									$noofbox = 0;
								}
							}
						}

						
					}else{
						$noofbox=$noofbox-$totalBoxs;

						$query = "INSERT INTO stock_to_export
						(lotnumber,purchaser_name, quantity_type, quantity, invoice_no, invoice_dt, storageIdml, adminId, final_productId, is_international, no_of_boxes, created_at,author)
						VALUES('".$lotnumber."','".$buyrname."', '".$row['send_to_qtny_type']."', ".$row['send_to_quantity'].", '".$inv_no."', '".$invdat."', '".$row['storageID_ml']."',".$adminId.", ".$row['final_product'].", ".$isinternational.", ".$totalBoxs.", CURRENT_TIMESTAMP,".$userId.");";
						
						$queryrun = mysqli_query($con, $query);
						if($queryrun > 0)
						{ 
							$last_id = mysqli_insert_id($con);
				
							$query3 = "INSERT INTO stock_to_export_history
							(lotnumber,purchaser_name, quantity_type, quantity, invoice_no, invoice_dt, storage_id, adminId, final_productId, is_international, no_of_boxes, created_at,parent_id,author)
							VALUES('".$lotnumber."','".$buyrname."', '".$row['send_to_qtny_type']."', ".$row['send_to_quantity'].", '".$inv_no."', '".$invdat."', '".$row['storageId']."',".$adminId.", ".$row['final_product'].", ".$isinternational.",".$totalBoxs.", CURRENT_TIMESTAMP,".$last_id.",".$userId.");";
							
							$queryrun3 = mysqli_query($con, $query3);
							if($queryrun3 > 0)
							{
								
								$query2 = "update package_to_stock set totalBoxs = 0,send_to_quantity=0 where id=".$adminId;
								
								$querysrun2 = mysqli_query($con, $query2);
								if($querysrun2 >0)
								{
									$insertedCount++;
								}
							}
						}

					}
					
				}
			}
			

		}
	}
	
	if($insertedCount == 0){
		$myObj = [ 'status' => false,'msg'=>'Failed to Export products','duplicateInv'=>$dubplicateInv];
	}else{
		$myObj = [ 'status' => true];
	}

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

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

			if($noofboxes !=0){
				$adDet = explode(",",$rows['admindpt_parent_details']);
				$totalBoxs = $rows['totalBoxs'];
				$updatedCount=0;
				for($a=0; $a < count($adDet); $a++){
					
					$adminSplit = explode("-",$adDet[$a]);
					$insertedBoxes = 0;
					if($totalBoxs < $noofboxes){
						$updateQty = $adminSplit[1] * $totalBoxs;
						$noofboxes = $noofboxes - $totalBoxs;
						$totalBoxsup = 0;
						$insertedBoxes = $totalBoxs;
					}else{
						$updateQty = $adminSplit[1] * $noofboxes;
						$totalBoxsup = $totalBoxs -  $noofboxes;
						$insertedBoxes = $noofboxes;
						$noofboxes = 0;
					}
					$query = "UPDATE admin_dpts_mul set send_to_quantity=send_to_quantity+".$updateQty." WHERE id=".$adminSplit[0].";";

					$queryrun = mysqli_query($con, $query);
					
					if($queryrun >0){
						
						$query = "INSERT INTO package_to_stock_history
						(final_product, send_to_quantity, send_to_qtny_type, status, totalBoxs, admindpt_parent_details,deleted_by, storageId, author, parent_id)
						VALUES('".$rows['final_product']."', ".$rows['send_to_quantity'].",  ".$rows['send_to_qtny_type'].", 1, ".$insertedBoxes.", '".$rows['admindpt_parent_details']."', CURRENT_TIMESTAMP, 0,'".$userId."',".$rows['id']." );";

						$queryrun = mysqli_query($con, $query);
						
						if($queryrun >0){
							
							if($totalBoxsup == 0){
								$query = "DELETE from package_to_stock WHERE id=".$rows['id'].";";
								$queryrun = mysqli_query($con, $query);
								
							}else{
								$query = "UPDATE package_to_stock set totalBoxs = ".$totalBoxsup." WHERE id=".$rows['id'].";";
								$queryrun = mysqli_query($con, $query);
								
							}
						}
					}
				}
				
					
					
				
			}
				    										
		}
	}

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

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

			$adDet = explode(",",$rows['admindpt_parent_details']);
			$totalBoxs = $rows['totalBoxs'];
			$updatedCount=0;
			for($a=0; $a < count($adDet); $a++){
				
				$adminSplit = explode("-",$adDet[$a]);
				$updateQty = $adminSplit[1] * $totalBoxs;
				$query = "UPDATE admin_dpts_mul_raw set send_to_quantity=send_to_quantity+".$updateQty." WHERE id=".$adminSplit[0].";";

				$queryrun = mysqli_query($con, $query);
				
				if($queryrun >0){
					$updatedCount++;
				}
			}
			if($updatedCount == count($adDet)){
				$query = "INSERT INTO package_to_stock_history
				(final_product, send_to_quantity, send_to_qtny_type, status, totalBoxs, admindpt_parent_details,deleted_by, storageID_ml, author, parent_id)
				VALUES('".$rows['final_product']."', ".$rows['send_to_quantity'].",  ".$rows['send_to_qtny_type'].", 1,".$rows['totalBoxs'].", '".$rows['admindpt_parent_details']."', CURRENT_TIMESTAMP, '".$rows['storageID_ml']."','".$userId."',".$rows['id']." );";

				$queryrun = mysqli_query($con, $query);
				
				if($queryrun >0){
					$query = "DELETE from package_to_stock WHERE id=".$rows['id'].";";
					$queryrun = mysqli_query($con, $query);
					
					if($queryrun >0){
						$numofRows--;
					}
				}
			}
			
				    										
		}
	}

	if($numofRows == 0){
		$status = true;
	}else{
		$status = false;
	}
	
	$myObj = [ 'status' => $status];
	mysqli_close($con);
	header('Content-type: application/json');
	
	echo json_encode($myObj);
}else if($_POST['type'] == 'sendFromStorage')
{
	$dat=$_POST['dat'];
	$time=$_POST['time'];
	$storageId=$_POST['storageId'];
	$send_to_quantity=$_POST['send_to_quantity'];
	$userId=$_POST['userId'];
	
	$send_to=$_POST['dpt'];

	$status = false;
		
	$sql="select * from admin_dpts_mul where id =".$storageId;

	$res=mysqli_query($con,$sql);
	if (mysqli_num_rows($res) > 0) 
	{
		while($rows=mysqli_fetch_assoc($res)){
			$totalqty = $rows["send_to_quantity"];

			$query = "INSERT INTO admin_dpts_mul
			(send_from, send_to, productItem_id, initial_quantity, initial_qnty_type, ptype, final_product, send_to_quantity, send_to_qtny_type,status, admindptml_parentId,storageId,author)
			VALUES('11', '".$send_to."', '".$rows["productItem_id"]."', '".$rows["initial_quantity"]."', '".$rows["initial_qnty_type"]."','".$rows["ptype"]."', '".$rows["final_product"]."', ".$send_to_quantity.", ".$rows["send_to_qtny_type"].", 1,".$storageId.",'".$rows["storageId"]."',".$userId.");";

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

			if($queryrun >0){
				$last_id = mysqli_insert_id($con);
				$query = "INSERT INTO admin_dpts_mul_history
				(send_from, send_to, productItem_id, initial_quantity, initial_qnty_type, ptype, final_product, send_to_quantity, send_to_qtny_type,status, admindptml_parentId,storageId,parent_id,author)
			VALUES('11', '".$send_to."', '".$rows["productItem_id"]."', '".$rows["initial_quantity"]."', '".$rows["initial_qnty_type"]."','".$rows["ptype"]."', '".$rows["final_product"]."', ".$send_to_quantity.", ".$rows["send_to_qtny_type"].", 1,".$storageId.",'".$rows["storageId"]."',".$last_id.",".$userId.");";
				 
				$queryrun = mysqli_query($con, $query);
				
				if($queryrun >0){
					$tquantity=$totalqty-$send_to_quantity;

					$query2 = "update admin_dpts_mul set send_to_quantity = '".$tquantity."' where id=".$storageId ;
					
					$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'] =='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_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'] == '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 adp.*,admrc.id as admrcId, `productItem_id`, `initial_quantity`, `initial_qnty_type`, `inputQty`, `ptype`, `admindpt_parent_id`, `admindptml_parentId`, `storageId`, `water_wt` 
	from admin_dpts_mul_raw adp, admin_dpts_mul_raw_child admrc where adp.id = admrc.admr_parent_id and adp.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_mul_raw adm,admin_dpts_mul_raw_child admr 
			SET send_to_quantity=".$send_to_quantity.", send_to_qtny_type=".$send_to_qtny_type.", water_wt=".$extrawaterwt.", updated_by=current_timestamp() 
			where adm.id = admr.admr_parent_id and adm.id =".$adminId.";";

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

			$columnnm='admindptml_parentId';
			if($rows["admindptml_parentId"] ==null){
				$columnnm='admindpt_parent_id';
			}

			if($queryrun >0){

				if($rows['send_from'] == '4'){
					$query = "INSERT INTO admin_dpts_mul_raw_history
					(send_from, send_to, lotnumber,final_product, send_to_quantity, send_to_qtny_type, wtype,wasteqty,waste, status,updated_by,author,parent_id)
					VALUES('".$rows["send_from"]."', '".$rows["send_to"]."','".$rows["lotnumber"]."','".$rows["final_product"]."', ".$rows["send_to_quantity"].", 
					".$rows["send_to_qtny_type"].",'".$rows["wtype"]."',".$rows["wasteqty"].",".$rows["waste"].",1 ,current_timestamp(),".$userId.",".$adminId.");";
				}else{
					$wasteqty = 0;
					if($rows["wasteqty"] !=null){
						$wasteqty = $rows["wasteqty"];
					}

					$query = "INSERT INTO admin_dpts_mul_raw_history
					(send_from, send_to, lotnumber,final_product, send_to_quantity, send_to_qtny_type, wtype,wasteqty,waste, status,updated_by,author,parent_id)
					VALUES('".$rows["send_from"]."', '".$rows["send_to"]."','".$rows["lotnumber"]."','".$rows["final_product"]."', ".$rows["send_to_quantity"].", 
					".$rows["send_to_qtny_type"].",'".$rows["wtype"]."',".$wasteqty.",".$rows["waste"].",1 ,current_timestamp(),".$userId.",".$adminId.");";

				}
				$queryrun = mysqli_query($con, $query);
				if($queryrun >0){
					
					$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)
					VALUES('".$rows["productItem_id"]."', '".$rows["initial_quantity"]."', '".$rows["initial_qnty_type"]."', '".$rows["inputQty"]."','".$rows["ptype"]."',
					'".$rows["lotnumber"]."' ,".$adminId.",'".$rows["storageId"]."',".$rows["admrcId"].");";
					$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'] == 'validateProductIsProcessed')
{
	$admindpt_parent_id =$_POST["adminId"];
	
	$adId = explode(",",$admindpt_parent_id);
	
	$recordFound =false;

	for($i =0; $i < count($adId); $i++){
		$sql2="select * from admin_dpts_mul_raw_child ad where admindptml_parentId like '%".$adId[$i]."%';";
		$result2 = $con->query($sql2);
		if ($result2->num_rows > 0) {
			while($row2 = mysqli_fetch_array($result2))
			{
				$adIds = explode(",",$row2['admindptml_parentId']);
				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'] == 'adminDelete')
{
	$adminId=$_POST['adminId'];
	$userId=$_POST['userId'];
			
	$status = false;

	$revertDpt='';
	
		$sql="select adp.*,admrc.id as admrcId, `productItem_id`, `initial_quantity`, `initial_qnty_type`, `inputQty`, `ptype`, `admindpt_parent_id`, `admindptml_parentId`, `storageId`, `water_wt` 
		from admin_dpts_mul_raw adp, admin_dpts_mul_raw_child admrc where adp.id = admrc.admr_parent_id and adp.id =".$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["admindptml_parentId"]);

			$updatedCount=0;

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

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

				$sql="select * from admin_dpts_mul_raw 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_mul_raw 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)){

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

				$query = "INSERT INTO admin_dpts_mul_raw_history
					(send_from, send_to, lotnumber,final_product, send_to_quantity, send_to_qtny_type, wtype,wasteqty,waste, status,updated_by,author,parent_id)
					VALUES('".$rows["send_from"]."', '".$rows["send_to"]."','".$rows["lotnumber"]."','".$rows["final_product"]."', ".$rows["send_to_quantity"].", 
					".$rows["send_to_qtny_type"].",'".$rows["wtype"]."',".$wasteqty.",".$rows["waste"].",1 ,current_timestamp(),".$userId.",".$adminId.");";
				
				$queryrun = mysqli_query($con, $query);
				
				if($queryrun >0){
					
					$query2 = "DELETE from admin_dpts_mul_raw 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'] == 'scrapSend')
{
	$adminId=$_POST['adminId'];
	
	$send_to=$_POST['dpt'];
	$userId=$_POST['userId'];
	$itemr=$_POST['itemr'];
	$ptype=$_POST['ptype'];

	$status = false;
	
	$separateIds= explode(',',$adminId);

	for($i =0; $i < count($separateIds); $i++){
		$chkSingles = explode('-',$separateIds[$i]);

		if($chkSingles[1] == '1'){
			$sql="select * from admin_dpts where id =".$chkSingles[0];
			$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+$totalqty;
						$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,storageId,parent_id,author,waste,final_product)
							VALUES('5','".$send_to."', '".$itemr."', ".$rows["wasteqty"].",".$rows["wtype"].", '".$ptype."', ".$totalqty.",'".$rows["wtype"]."', ".$chkSingles[0].",".$rows["storageId"].",0,".$userId.",'".$rows["waste"]."','".$rows["final_product"]."');
							";
								
							$queryrun = mysqli_query($con, $query);
							if($queryrun >0){
								$tquantity=0;

								$query2 = "update admin_dpts set wasteqty = '".$tquantity."' where id=".$chkSingles[0] ;
								
								$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"]."', ".$totalqty.",".$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,storageId,parent_id,author,waste,final_product)
							VALUES('5','".$send_to."', '".$itemr."', ".$rows["wasteqty"].",".$rows["wtype"].", '".$ptype."', ".$totalqty.",'".$rows["wtype"]."', ".$chkSingles[0].",".$rows["storageId"].",0,".$userId.",'".$rows["waste"]."','".$rows["final_product"]."');
							";
								
							$queryrun = mysqli_query($con, $query);
							if($queryrun >0){
								$tquantity=0;

								$query2 = "update admin_dpts set wasteqty = '".$tquantity."' where id=".$chkSingles[0] ;
								
								$querysrun2 = mysqli_query($con, $query2);
								if($querysrun2 >0)
								{	
									$status = true;								
								}
							}
						}
					}
					
				}
														
			}
		}else{
			$sql="select * from admin_dpts_mul_raw adp where adp.id =".$chkSingles[0].";";
			$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+$totalqty;
						$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_mul_raw_history
								(send_from, send_to, send_to_quantity, send_to_qtny_type,author,parent_id,waste,final_product)
								VALUES('5', '".$send_to."', '".$totalqty."', 
								'".$rows["wtype"]."',".$userId.",0,'".$rows["waste"]."','".$rows["final_product"]."');";
						
							$queryrun = mysqli_query($con, $query);
							
							if($queryrun >0){
								$last_id = mysqli_insert_id($con);
								$query = "INSERT INTO admin_dpts_mul_raw_child_history
								(productItem_id, initial_quantity, initial_qnty_type, ptype, admindptml_parentId,admr_parent_id,admin_dpts_mul_raw_child_parent)
								VALUES('".$itemr."', '".$rows["wasteqty"]."', '".$rows["wtype"]."', '".$ptype."',
								".$chkSingles[0].",".$last_id.",0);";
								$queryrun = mysqli_query($con, $query);
								if($queryrun >0){
									$tquantity=0;

									$query2 = "update admin_dpts_mul_raw set wasteqty = '".$tquantity."' where id=".$chkSingles[0] ;
									
									$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"]."', ".$totalqty.",".$ptype.");";
													
						$queryrun1 = mysqli_query($con, $query1);
						if($queryrun1 > 0)
						{ 
							$query = "INSERT INTO admin_dpts_mul_raw_history
								(send_from, send_to, send_to_quantity, send_to_qtny_type,author,parent_id,waste,final_product)
								VALUES('5', '".$send_to."', '".$totalqty."', 
								'".$rows["wtype"]."',".$userId.",0,'".$rows["waste"]."','".$rows["final_product"]."');";
						
							$queryrun = mysqli_query($con, $query);
							
							if($queryrun >0){
								$last_id = mysqli_insert_id($con);
								$query = "INSERT INTO admin_dpts_mul_raw_child_history
								(productItem_id, initial_quantity, initial_qnty_type, ptype, admindptml_parentId,admr_parent_id,admin_dpts_mul_raw_child_parent)
								VALUES('".$itemr."', '".$rows["wasteqty"]."', '".$rows["wtype"]."', '".$ptype."',
								".$chkSingles[0].",".$last_id.",0);";
								$queryrun = mysqli_query($con, $query);
								if($queryrun >0){
									$tquantity=0;

									$query2 = "update admin_dpts_mul_raw set wasteqty = '".$tquantity."' where id=".$chkSingles[0] ;
									
									$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'] == 'scrapDelete')
{
	$adminId=$_POST['adminId'];
	$userId=$_POST['userId'];
		
	$status = false;

	$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 = ".$adminId;
	$res=mysqli_query($con,$sql);
	if (mysqli_num_rows($res) > 0) 
	{
		while($rows=mysqli_fetch_assoc($res)){
			$columnnm='admindptml_parentId';
			if($rows["admindptml_parentId"] ==null){
				$columnnm='admindpt_parent_id';
			}
			$query = "UPDATE admin_dpts_mul_raw 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_mul_raw_history
						(send_from, send_to, send_to_quantity, send_to_qtny_type,author,parent_id,waste,final_product,deleted_by,lotnumber,wtype,wasteqty)
						VALUES('".$rows["send_from"]."', '".$rows["send_to"]."', '".$rows["send_to_quantity"]."', 
						'".$rows["send_to_qtny_type"]."',".$userId.",".$adminId.",'".$rows["waste"]."','".$rows["final_product"]."',current_timestamp(),'".$rows["lotnumber"]."',
						'".$rows["wtype"]."',".$rows["wasteqty"].");";
				 
				$queryrun = mysqli_query($con, $query);
				
				if($queryrun >0){
						
					$last_id = mysqli_insert_id($con);
					$query = "INSERT INTO admin_dpts_mul_raw_child_history
					(productItem_id, initial_quantity, initial_qnty_type, ptype, $columnnm,admr_parent_id,admin_dpts_mul_raw_child_parent,lotnumber)
					VALUES('".$rows["productItem_id"]."', '".$rows["initial_quantity"]."', '".$rows["initial_qnty_type"]."', '".$rows["ptype"]."',
					'".$rows[$columnnm]."',".$last_id.",".$adminId.",'".$rows["lotnumber"]."');";
					$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'] == 'scrapEdit')
{
	$adminId=$_POST['editadminId'];
	$wasteType=$_POST['editwtype'];
	$wasteqty=$_POST['wasteqty'];
	$wqtytype=$_POST['wqtytype'];
	$userId=$_POST['userId'];
	
	$status = false;

	$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 = ".$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"];
			}

			$columnnm='admindptml_parentId';
			if($rows["admindptml_parentId"] ==null){
				$columnnm='admindpt_parent_id';
			}
			
			$query = "UPDATE admin_dpts_mul_raw 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_mul_raw_history
						(send_from, send_to, send_to_quantity, send_to_qtny_type,author,parent_id,waste,final_product,updated_by,lotnumber,wtype,wasteqty)
						VALUES('".$rows["send_from"]."', '".$rows["send_to"]."', '".$rows["send_to_quantity"]."', 
						'".$rows["send_to_qtny_type"]."',".$userId.",".$adminId.",'".$rows["waste"]."','".$rows["final_product"]."',current_timestamp(),'".$rows["lotnumber"]."',
						'".$rows["wtype"]."',".$rows["wasteqty"].");";
				 
					$queryrun = mysqli_query($con, $query);
					
					if($queryrun >0){
						$last_id = mysqli_insert_id($con);
						$query = "INSERT INTO admin_dpts_mul_raw_child_history
						(productItem_id, initial_quantity, initial_qnty_type, ptype, $columnnm,admr_parent_id,admin_dpts_mul_raw_child_parent,lotnumber)
						VALUES('".$rows["productItem_id"]."', '".$rows["initial_quantity"]."', '".$rows["initial_qnty_type"]."', '".$rows["ptype"]."',
						'".$rows[$columnnm]."',".$last_id.",".$adminId.",'".$rows["lotnumber"]."');";
						$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'] =='viewAdmin'){
	$p_id = $_POST['id'];
 	$q = "select fp.id as finalproductId,admrc.ptype as ptypeId,ad.id ,frmd.depart as frmdpt,admrc.productItem_id,fp.item as finalprodct,ad.send_to_quantity,sendqt.q_name,
	 sendqt.id as qtytypeid,ad.created_at as senddttime ,admrc.water_wt 
		  from admin_dpts_mul_raw ad ,department frmd,final_product fp ,quantity_type sendqt,admin_dpts_mul_raw_child admrc  
		  where ad.send_from = frmd.id and ad.final_product = fp.id and ad.send_to_qtny_type = sendqt.id and ad.id = admrc.admr_parent_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'] == 'storageEditFromDpts')
{
	$adminId=$_POST['editadminId'];
	$send_to_quantity=$_POST['editsend_to_quantity'];
	$send_to_qtny_type=$_POST['editsendqty_typ'];
	
	$userId=$_POST['userId'];
	
	$status = false;
	$msg = 'Unable to Edit Details';

	$sql="select * from admin_dpts_mul_raw where admindpt_parent_id =".$adminId;
	$resv=mysqli_query($con,$sql);

	if (mysqli_num_rows($resv) == 0) {
		$sql="select * from admin_dpts_mul_raw 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"];
				}
				
				$query = "UPDATE admin_dpts_mul_raw SET send_to_quantity=".$send_to_quantity.", send_to_qtny_type=".$send_to_qtny_type.",updated_by=current_timestamp() WHERE id=".$adminId.";";

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

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

			}
		    										
		}
		
	}else{
		$msg = 'This Product has been processed furthur, first please delete from processed departments to edit this!.';
	}

	$myObj = [ 'status' => $status,'msg'=>$msg];
	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_mul_raw_child admrc where lotnumber = '".$lotnumber."' and admr_parent_id =0";
	$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_mul_raw_child_history
							(productItem_id, initial_quantity, initial_qnty_type,inputQty, ptype, lotnumber ,admindpt_parent_id,storageId,admin_dpts_mul_raw_child_parent)
							VALUES('".$rows["productItem_id"]."', '".$rows["initial_quantity"]."', '".$rows["initial_qnty_type"]."', '".$rows["inputQty"]."','".$rows["ptype"]."',
							'".$rows["lotnumber"]."' ,".$rows["admindpt_parent_id"].",'".$rows["storageId"]."',".$rows["id"].");";
							$queryrun = mysqli_query($con, $query);
							
						}
					}
					
				}
			}

		}
	    										
	}

	$sql="select * from admin_dpts_mul_raw where lotnumber = '".$lotnumber."' and send_to =2";
	$res=mysqli_query($con,$sql);
	
	if (mysqli_num_rows($res) > 0) 
	{
		while($rows=mysqli_fetch_assoc($res)){

			$query = "INSERT INTO admin_dpts_mul_raw_history
				(send_from, send_to, lotnumber,final_product, send_to_quantity, send_to_qtny_type, wtype,wasteqty,waste, status,deleted_by,author,parent_id)
				VALUES('".$rows["send_from"]."', '".$rows["send_to"]."','".$rows["lotnumber"]."','".$rows["final_product"]."', ".$rows["send_to_quantity"].", 
				".$rows["send_to_qtny_type"].",'".$rows["wtype"]."',".$rows["wasteqty"].",'".$rows["waste"]."',1 ,current_timestamp(),".$userId.",".$rows["id"].");";
			
			$queryrun = mysqli_query($con, $query);
			
			if($queryrun >0){
				
				$query2 = "DELETE from admin_dpts_mul_raw 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);
}else if($_POST['type'] =='viewF39'){
	$finalproductId = $_POST['finalproductId'];
	$wasteId = $_POST['wasteId'];
	$qtytypeId = $_POST['qtytypeId'];

 	$q = "select * from (
		select '1' as is_single ,s.finalproductId,s.finalprodct,s.wasteqty,s.qtytypeId,s.wasteqt_type_name,s.wasteId,s.id,s.frmdpt,s.productItem_id,s.senddttime from (select fp.id as finalproductId,fp.item as finalprodct,ad.wasteqty ,
		ad.wtype as qtytypeId,wasteqttype.q_name as wasteqt_type_name ,
		ad.waste as wasteId,ad.id ,frmd.depart as frmdpt,ad.productItem_id,
		ad.created_at as senddttime from admin_dpts ad ,department frmd ,quantity_type wasteqttype,final_product fp 
		where ad.send_from = frmd.id and ad.final_product = fp.id and wasteqttype.id = ad.wtype and ad.wasteqty !=0) as s
		union 
		select '0' as is_single,m.finalproductId,m.finalprodct,m.wasteqty,m.qtytypeId,m.wasteqt_type_name,m.wasteId,m.id,m.frmdpt,m.productItem_id,m.senddttime from (select adm.wasteqty,admrc.storageId,frmd.depart as frmdpt,
		adm.final_product as finalproductId,admrc.water_wt ,adm.waste as wasteId, adm.id,admrc.productItem_id, adm.send_from ,
		adm.send_to, adm.created_at as senddttime ,adm.wtype as qtytypeId,
		fp.item as finalprodct,qt.q_name as wasteqt_type_name  from admin_dpts_mul_raw adm,final_product fp ,quantity_type qt, department frmd, admin_dpts_mul_raw_child admrc 
		where adm.final_product = fp.id and adm.wtype = qt.id and adm.send_from = frmd.id and adm.lotnumber = admrc.lotnumber  and adm.wasteqty !=0 group by adm.id) as m
		) t where finalproductId = ".$finalproductId." and wasteId =".$wasteId." and qtytypeId = ".$qtytypeId." ;";
 
   	$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'];
			} 

			$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'] == 'packageEdit')
{
	$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 adp.*,admrc.id as admrcId, `productItem_id`, `initial_quantity`, `initial_qnty_type`, `inputQty`, `ptype`, `admindpt_parent_id`, `admindptml_parentId`, `storageId`, `water_wt` 
	from admin_dpts_mul_raw adp, admin_dpts_mul_raw_child admrc where adp.lotnumber = admrc.lotnumber and adp.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_mul_raw adm,admin_dpts_mul_raw_child admr 
			SET send_to_quantity=".$send_to_quantity.", send_to_qtny_type=".$send_to_qtny_type.", water_wt=".$extrawaterwt.", updated_by=current_timestamp() 
			where adm.lotnumber = admr.lotnumber and adm.id =".$adminId.";";

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

			$columnnm='admindptml_parentId';
			if($rows["admindptml_parentId"] ==null){
				$columnnm='admindpt_parent_id';
			}

			if($queryrun >0){

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

				$query = "INSERT INTO admin_dpts_mul_raw_history
				(send_from, send_to, lotnumber,final_product, send_to_quantity, send_to_qtny_type, wtype,wasteqty,waste, status,updated_by,author,parent_id)
				VALUES('".$rows["send_from"]."', '".$rows["send_to"]."','".$rows["lotnumber"]."','".$rows["final_product"]."', ".$rows["send_to_quantity"].", 
				".$rows["send_to_qtny_type"].",'".$rows["wtype"]."',".$wasteqty.",".$rows["waste"].",1 ,current_timestamp(),".$userId.",".$adminId.");";

				
				$queryrun = mysqli_query($con, $query);
				if($queryrun >0){
					
					$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)
					VALUES('".$rows["productItem_id"]."', '".$rows["initial_quantity"]."', '".$rows["initial_qnty_type"]."', '".$rows["inputQty"]."','".$rows["ptype"]."',
					'".$rows["lotnumber"]."' ,".$adminId.",'".$rows["storageId"]."',".$rows["admrcId"].");";
					$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);
}

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;
}
?>