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

if($_POST['type'] == 'sendFromStorage')
{
	$dat=$_POST['dat'];
	$time=$_POST['time'];
	$storageId=$_POST['storageId'];
	$send_to_quantity=$_POST['send_to_quantity'];
	$fromPurchase=$_POST['fromPurchase'];
	$userId=$_POST['userId'];
	
	$send_to=$_POST['dpt'];

	$is_single =  $_POST['is_single'];

	$status = false;
	
	if($fromPurchase == 1){
		$sql="select * from total_purchase_qty where id =".$storageId;
		$res=mysqli_query($con,$sql);

		if (mysqli_num_rows($res) > 0) 
		{
			while($rows=mysqli_fetch_assoc($res)){
				$totalqty = $rows["quantity"];

				$query = "INSERT INTO admin_dpts
				(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,author)
				VALUES('4','".$send_to."', '".$rows["item"]."', ".$rows["quantity"].",".$rows["quantity_type"].", '".$rows["ptype"]."', ".$send_to_quantity.",'".$rows["quantity_type"]."', 0, '".$dat."', '".$time."',".$storageId.",".$userId.");
				";
				 
				$queryrun = mysqli_query($con, $query);
				if($queryrun >0){
					$last_id = mysqli_insert_id($con);
					$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('4','".$send_to."', '".$rows["item"]."', ".$rows["quantity"].",".$rows["quantity_type"].", '".$rows["ptype"]."', ".$send_to_quantity.",'".$rows["quantity_type"]."', 0, '".$dat."', '".$time."',".$storageId.",".$last_id.",".$userId.");
					";
					 
					$queryrun = mysqli_query($con, $query);
					if($queryrun >0){
						$tquantity=$totalqty-$send_to_quantity;

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

			}
		    										
		}
	}else{

		$tableNm = "admin_dpts";
		$adminparentColumnNm = "admindpt_parent_id";
		if($is_single == 0){
			$tableNm = "admin_dpts_mul";
			$adminparentColumnNm = "admindptml_parentId";
		}

		$sql="select * from ".$tableNm." where id in (".$storageId.") order by send_to_quantity desc;";

		$res=mysqli_query($con,$sql);
		if (mysqli_num_rows($res) > 0) 
		{
			$additionalQty = 0;
			$admindpt_parent_id ='';
			$producItemId = '';
			$finalprodId = '';
			$send_qty_type = '';
			$initialQty='';
			$initialQtyType='';
			$ptype='';
			$storageId='';
			$insertedQty = $send_to_quantity;
			$updateAdminArry = array();

			while($insertedQty > 0){
				while($rows=mysqli_fetch_assoc($res)){
					$totalqty = $rows["send_to_quantity"];

					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"].",";

					$finalprodId = $rows["final_product"];
					$send_qty_type = $rows["send_to_qtny_type"];

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

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

							$admindpt_parent_id .=$rows["id"]."-".$send_to_quantity;
							$insertedQty = 0;
							break;
							
						}else{
							$additionalQty = $send_to_quantity - $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);
			}

			$query = "INSERT INTO ".$tableNm."
			(send_from, send_to, productItem_id, initial_quantity, initial_qnty_type, ptype, final_product, send_to_quantity, send_to_qtny_type,status, ".$adminparentColumnNm.",storageId,author)
			VALUES('4', '".$send_to."', '".$producItemId."', '".$initialQty."', '".$initialQtyType."','".$ptype."', '".$finalprodId."', 
			".$send_to_quantity.", ".$send_qty_type.", 1,'".$admindpt_parent_id."','".$storageId."',".$userId.");";

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

			if($queryrun >0){
				$last_id = mysqli_insert_id($con);
				$query = "INSERT INTO ".$tableNm."_history
				(send_from, send_to, productItem_id, initial_quantity, initial_qnty_type, ptype, final_product, send_to_quantity, send_to_qtny_type,status, ".$adminparentColumnNm.",storageId,parent_id,author)
			VALUES('4', '".$send_to."', '".$producItemId."', '".$initialQty."', '".$initialQtyType."','".$ptype."', '".$finalprodId."',
			 ".$send_to_quantity.", ".$send_qty_type.", 1,'".$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'] == '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 where admindpt_parent_id =".$adminId;
	$resv=mysqli_query($con,$sql);

	if (mysqli_num_rows($resv) == 0) {
		$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"];
				}
				
				$query = "UPDATE admin_dpts 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_history
					(send_from, send_to, productItem_id, initial_quantity, initial_qnty_type,ptype, final_product, send_to_quantity, send_to_qtny_type, status,admindpt_parent_id,storageId,parent_id,updated_by,author)
				VALUES('".$rows["send_from"]."', '".$rows["send_to"]."', '".$rows["productItem_id"]."', '".$rows["initial_quantity"]."', '".$rows["initial_qnty_type"]."', 
				'".$rows["ptype"]."', '".$rows["final_product"]."', ".$rows["send_to_quantity"].", ".$rows["send_to_qtny_type"].", 1, ".$adminId.",'".$rows["storageId"]."',".$adminId.",current_timestamp(),".$userId.");";
					 
					$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'] == 'add_other_department')
{
	$p_name=mysqli_real_escape_string($con,$_POST['dname']);
	
    $sql1="SELECT depart FROM department where depart like '%".$p_name."%';";
	$result = $con->query($sql1);

	if ($result->num_rows == 0) {
		 $query = "INSERT INTO department(depart,dpt_id) VALUES ('".$p_name."',12)";
		 
		 $queryrun = mysqli_query($con, $query);
        if($queryrun)
        { 	
           $last_id = mysqli_insert_id($con);	
           $myObj = [ 'status' => true,'msg'=>"Department Added successfully",'rowId'=>$last_id];
		} else {
		   $myObj = [ 'status' => false,'msg'=>"Error: " . $query . "<br>" . mysqli_error($con)];
		}
	}else{
		$myObj = [ 'status' => false,'msg'=>"Department Already Exist"];
	}

	mysqli_close($con);
	header('Content-type: application/json');
	echo json_encode($myObj);

}else if($_POST['type'] == 'deleteFromStorage')
{
	$storageId=$_POST['storageId'];
	$deletedBy=$_POST['deletedBy'];
	$userId=$_POST['userId'];
	
	$status = false;
	
	$sql="select * from total_purchase_qty where id =".$storageId;
	$res=mysqli_query($con,$sql);

	if (mysqli_num_rows($res) > 0) 
	{
		while($rows=mysqli_fetch_assoc($res)){
			

			$query = "INSERT INTO purchase_history (inv_no, dat, `time`, cha_no, vno, item_category, item, supplier_name, ptype, l_no, quantity_type, quantity, moisture, lab_report, lap_report_file, status,parent_id, deleted_on, deleted_by,author)
			SELECT inv_no, dat, `time`, cha_no, vno, item_category, item, supplier_name, ptype, l_no, quantity_type, quantity, moisture, lab_report, lap_report_file, status,p_id,current_timestamp() , '".$deletedBy."' as deleted_by, ".$userId." as author
			from purchase where item = '".$rows["item"]."' and quantity_type = '".$rows["quantity_type"]."' and ptype = '".$rows["ptype"]."';";
			 
			$queryrun = mysqli_query($con, $query);
			if($queryrun >0){
				$query = "DELETE from total_purchase_qty where id =".$storageId;
				 
				$queryrun = mysqli_query($con, $query);
				if($queryrun >0){
					$query2 = "INSERT INTO total_purchase_qty_delete_history
					(item, quantity_type, quantity, ptype, deleted_on, delete_by,parent_id,author) VALUES('".$rows["item"]."','".$rows["quantity_type"]."',".$rows["quantity"].",'".$rows["ptype"]."',current_timestamp(),'".$deletedBy."',".$storageId.",".$userId.")";

					$queryrun2 = mysqli_query($con, $query2);
					if($queryrun2 >0){
						$status = true;
					}
				}	
			}	

		}
	    										
	}
	
	$myObj = [ 'status' => $status];
	mysqli_close($con);
	header('Content-type: application/json');
	
	echo json_encode($myObj);
}else if($_POST['type'] == 'validateStorageIsProcessed')
{
	$storageId =$_POST["storageId"];
	
	$sql1="select * from admin_dpts ad where storageId =".$storageId.";";
	$result = $con->query($sql1);

	if ($result->num_rows > 0) {
		$myObj = [ 'status' => true,'msg'=>'The Product is processed,therefore cannot be deleted'];
	}else{
		$myObj = [ 'status' => false];
	}
	
	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;
}

?>