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

if($_POST['type'] == 'storePurchase')
{
		
	$inv_no=$_POST['inv_no'];
    $dat=$_POST['dat'];
	$time=$_POST['time'];
	$cha_no=$_POST['cha_no'];
	$vno=$_POST['vno'];
	$item_category=$_POST['item_category'];
	$item=$_POST['item'];
	$s_name=$_POST['sname'];
	
	$ptype=$_POST['ptype'];
	$l_no=$_POST['l_no'];
	$qty_typ=$_POST['qty_typ'];
	$qty=$_POST['qty'];
	$moisture=$_POST['moisture'];
	$lab_report=$_POST['lab_report'];
	$userId=$_POST['userId'];
		
		
    $uploaddir = 'upload/';
	$uploadfile = $uploaddir . basename($_FILES['labfile']['name']);
    move_uploaded_file($_FILES['labfile']['tmp_name'], $uploadfile);
	$query = "INSERT INTO purchase(inv_no,dat,time,cha_no,vno,item_category,item,supplier_name,ptype,l_no,quantity_type,quantity,moisture,lab_report,lap_report_file,author) VALUES ('".$inv_no."','".$dat."','".$time."','".$cha_no."','".$vno."','".$item_category."','".$item."','".$s_name."','".$ptype."','".$l_no."','".$qty_typ."','".$qty."','".$moisture."','".$lab_report."','".$uploadfile."',".$userId.")";

	$status = false;			 
	$queryrun = mysqli_query($con, $query);
    if($queryrun > 0)
    { 
    	$last_id = mysqli_insert_id($con);
        $sql="select * from total_purchase_qty where item = '".$item."' and quantity_type = '".$qty_typ."' 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 = '".$item."' and quantity_type = '".$qty_typ."' and ptype=".$ptype;
			$querysrun2 = mysqli_query($con, $query2);
			if($querysrun2 >0)
			{	
				$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,parent_id,author) VALUES ('".$inv_no."','".$dat."','".$time."','".$cha_no."','".$vno."','".$item_category."','".$item."','".$s_name."','".$ptype."','".$l_no."','".$qty_typ."','".$qty."','".$moisture."','".$lab_report."','".$uploadfile."',".$last_id.",".$userId.")";
			 
				$queryrun = mysqli_query($con, $query);
				if($queryrun >0){
					$status = true;
				}									
			}
											
		}else
		{
			$query1 = "INSERT INTO total_purchase_qty(item, quantity_type, quantity,ptype) VALUES('".$item."', '".$qty_typ."', ".$qty.",".$ptype.");";
										 
			$queryrun1 = mysqli_query($con, $query1);
			if($queryrun1 > 0)
			{ 
				$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,parent_id,author) VALUES ('".$inv_no."','".$dat."','".$time."','".$cha_no."','".$vno."','".$item_category."','".$item."','".$s_name."','".$ptype."','".$l_no."','".$qty_typ."','".$qty."','".$moisture."','".$lab_report."','".$uploadfile."',".$last_id.",".$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'] == 'add_product')
{
	$p_name=mysqli_real_escape_string($con,$_POST['pname']);
	
	if(empty($p_name)){
		$myObj = [ 'status' => false,'msg'=>"Product Cannot be Empty"];
	}else{
	    $sql1="SELECT item FROM product where item = '".$p_name."';";
		$result = $con->query($sql1);

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

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

}
else if($_POST['type'] == 'addInventory')
{
	$items =$_POST["items"];
	$number= count($_POST["name"]);
	if($number > 0)
	{
		for($i=0; $i < $number; $i++)
		{
			if(trim($_POST["name"][$i]) != '')
			{
				$sql= "INSERT INTO productitem(item,description) VALUES('".$items."','".mysqli_real_escape_string($con,$_POST["name"][$i])."')";
				mysqli_query($con,$sql);
			}
		}
		echo 'Item Description Added';
	}else
	{
		echo "Unable to Add Item Description";
	}
	mysqli_close($con);
}else if($_POST['type'] == 'validateInventory')
{
	$items =$_POST["items"];
	$number= count($_POST["name"]);
	if($number > 0)
	{
		$existingItemDes = "";	
		for($i=0; $i < $number; $i++)
		{	
			if(trim($_POST["name"][$i]) != '')
			{
				$descp = mysqli_real_escape_string($con,$_POST["name"][$i]);
				$sql1="SELECT item FROM productitem where item = '".$items."' and description='".$descp."';";
				$result = $con->query($sql1);

				if ($result->num_rows > 0) {
					$existingItemDes .= $descp.",";
				}
			}
		}

		if($existingItemDes !=''){
			$msg = $existingItemDes." these Item Descriptions already Exist";
			$myObj = [ 'status' => false,'msg'=>$msg];
		}else{
			$myObj = [ 'status' => true];
		}
	}else{
		$myObj = [ 'status' => false,'msg'=>'No Items were Submitted'];
	}

	mysqli_close($con);
	header('Content-type: application/json');
	echo json_encode($myObj);
}else if($_POST['type'] =='productype')
{
	$pt_name=mysqli_real_escape_string($con,$_POST['ptname']);
	
	if(empty($pt_name)){
		$myObj = [ 'status' => false,'msg'=>"Product Type Cannot be Empty"];
	}else{
		$sql1="SELECT item FROM productype where item = '".$pt_name."';";
		$result = $con->query($sql1);

		if ($result->num_rows == 0) {

			$query = "INSERT INTO productype(item) VALUES ('".$pt_name."')";
				 
			$queryrun = mysqli_query($con, $query);
	        if($queryrun)
	        { 
	           $last_id = mysqli_insert_id($con);
	           $myObj = [ 'status' => true,'msg'=>"Product Type Added successfully",'rowId'=>$last_id];
			} else {
			   $myObj = [ 'status' => false,'msg'=>"Error: " . $query . "<br>" . mysqli_error($con)];
			}
		}else{
			$myObj = [ 'status' => false,'msg'=>"Product Type Already Exist"];
		}
	}
	
	mysqli_close($con);
	header('Content-type: application/json');
	echo json_encode($myObj);

}else if($_POST['type'] =='addSup')
{
	$s_name=$_POST['sname'];
	$phone=$_POST['phone'];
	$email=$_POST['email'];
	$address=$_POST['address'];
	
	if(empty($s_name)){
		$myObj = [ 'status' => false,'msg'=>"Supplier Name Cannot be Empty"];
	}else{
		$sql1="SELECT name FROM supplier where name = '".$s_name."';";
		$result = $con->query($sql1);

		if ($result->num_rows == 0) {

			$query = "INSERT INTO supplier(name,phone,email,address) VALUES ('".$s_name."','".$phone."','".$email."','".$address."')";
				 
			$queryrun = mysqli_query($con, $query);
	        if($queryrun > 0)
	        { 
	           $last_id = mysqli_insert_id($con);
	           $myObj = [ 'status' => true,'msg'=>"Supplier Added successfully",'rowId'=>$last_id];
			} else {
				$myObj = [ 'status' => false,'msg'=>"Error: " . $query . "<br>" . mysqli_error($con)];
			}
		}else{
			$myObj = [ 'status' => false,'msg'=>"Supplier Already Exist"];
		}
	}
	
	mysqli_close($con);
	header('Content-type: application/json');
	echo json_encode($myObj);

}else if($_POST['type'] =='editSup')
{
	$sid=$_POST['sid'];
	$phone=$_POST['edphone'];
	$email=$_POST['edemail'];
	$address=$_POST['edaddress'];
	
	$sql1="SELECT name FROM supplier where id = ".$sid.";";
	$result = $con->query($sql1);

	if ($result->num_rows > 0) {

		$query = "UPDATE supplier SET phone='".$phone."', email='".$email."', address='".$address."', updated_on=CURRENT_TIMESTAMP WHERE id=".$sid.";";
			 
		$queryrun = mysqli_query($con, $query);
        if($queryrun > 0)
        { 
           $last_id = mysqli_insert_id($con);
           $myObj = [ 'status' => true,'msg'=>"Supplier Updated successfully"];
		} else {
			$myObj = [ 'status' => false,'msg'=>"Error: " . $query . "<br>" . mysqli_error($con)];
		}
	}else{
		$myObj = [ 'status' => false,'msg'=>"Supplier Not Found"];
	}

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

}else if($_POST['type'] =='deleteSup')
{
	$sid=$_POST['sid'];
	
	$sql1="SELECT supplier_name FROM purchase where supplier_name = '".$sid."';";
	$result = $con->query($sql1);

	if ($result->num_rows == 0) {

		$query = "DELETE from supplier where id = '".$sid."';";
			 
		$queryrun = mysqli_query($con, $query);
        if($queryrun > 0)
        { 
           $last_id = mysqli_insert_id($con);
           $myObj = [ 'status' => true,'msg'=>"Supplier Deleted successfully"];
		} else {
			$myObj = [ 'status' => false,'msg'=>"Error: " . $query . "<br>" . mysqli_error($con)];
		}
	}else{
		$myObj = [ 'status' => false,'msg'=>"Supplier is in Use, therefore cannot be deleted"];
	}

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

}else if($_POST['type'] =='addPurchaser')
{
	$s_name=$_POST['sname'];
	$phone=$_POST['phone'];
	$email=$_POST['email'];
	$address=$_POST['address'];
	
	$sql1="SELECT name FROM purchaser_master where name = '".$s_name."';";
	$result = $con->query($sql1);

	if ($result->num_rows == 0) {

		$query = "INSERT INTO purchaser_master(name,phone,email,address) VALUES ('".$s_name."','".$phone."','".$email."','".$address."')";
			 
		$queryrun = mysqli_query($con, $query);
        if($queryrun > 0)
        { 
           $last_id = mysqli_insert_id($con);
           $myObj = [ 'status' => true,'msg'=>"Purchaser Added successfully",'rowId'=>$last_id];
		} else {
			$myObj = [ 'status' => false,'msg'=>"Error: " . $query . "<br>" . mysqli_error($con)];
		}
	}else{
		$myObj = [ 'status' => false,'msg'=>"Purchaser Already Exist"];
	}

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

}else if($_POST['type'] =='editPurchaser')
{
	$sid=$_POST['sid'];
	$phone=$_POST['edphone'];
	$email=$_POST['edemail'];
	$address=$_POST['edaddress'];
	
	$sql1="SELECT name FROM purchaser_master where id = ".$sid.";";
	$result = $con->query($sql1);

	if ($result->num_rows > 0) {

		$query = "UPDATE purchaser_master SET phone='".$phone."', email='".$email."', address='".$address."', updated_on=CURRENT_TIMESTAMP WHERE id=".$sid.";";
			 
		$queryrun = mysqli_query($con, $query);
        if($queryrun > 0)
        { 
           $last_id = mysqli_insert_id($con);
           $myObj = [ 'status' => true,'msg'=>"Purchaser Updated successfully"];
		} else {
			$myObj = [ 'status' => false,'msg'=>"Error: " . $query . "<br>" . mysqli_error($con)];
		}
	}else{
		$myObj = [ 'status' => false,'msg'=>"Purchaser Not Found"];
	}

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

}else if($_POST['type'] =='deletePurchaser')
{
	$sid=$_POST['sid'];
	
	$sql1="SELECT purchaser_name FROM stock_to_export where purchaser_name = '".$sid."';";
	$result = $con->query($sql1);

	if ($result->num_rows == 0) {

		$query = "DELETE from purchaser_master where id = '".$sid."';";
			 
		$queryrun = mysqli_query($con, $query);
        if($queryrun > 0)
        { 
           $last_id = mysqli_insert_id($con);
           $myObj = [ 'status' => true,'msg'=>"Purchaser Deleted successfully"];
		} else {
			$myObj = [ 'status' => false,'msg'=>"Error: " . $query . "<br>" . mysqli_error($con)];
		}
	}else{
		$myObj = [ 'status' => false,'msg'=>"Purchaser is in Use, therefore cannot be deleted"];
	}

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

}else if($_POST['type'] =='getItemDesp')
{
	$val=$_POST["value"];
	$val_m=mysqli_real_escape_string($con,$val);
	$sql="SELECT id,description FROM productitem where item='$val_m'";
	$result=mysqli_query($con,$sql);
	
	if(mysqli_num_rows($result) > 0){
		$htmlData= "";
		while($rows=mysqli_fetch_assoc($result)){
			$htmlData.= "<option value=".$rows["id"].">".$rows["description"]."</option>";
			
		}

		if($htmlData !=''){
			$myObj = [ 'status' => true,'data'=>$htmlData];
		}else{
			$myObj = [ 'status' => false];
		}
		
	}else{
		$myObj = [ 'status' => false];
	}

	mysqli_close($con);
	header('Content-type: application/json');
	echo json_encode($myObj);
}else if($_POST['type'] =='viewPurchase'){
	$p_id = $_POST['id'];
 	$q = "select p3.item as ptype,pur.dat ,pur.l_no ,pur.`time`,pur.inv_no, pur.cha_no, pur.vno, p.item as item_category, p2.description as item,s.name as supplier_name, qt.id as qtytypeid,qt.q_name as quantity_type, pur.quantity, pur.lab_report,pur.lap_report_file from 
purchase pur,product p,productitem p2,supplier s,quantity_type qt,productype p3 where 
pur.item_category = p.id and pur.item = p2.id and pur.supplier_name = s.id and pur.ptype = p3.id and pur.quantity_type = qt.id and pur.p_id = ".$p_id;
 
   	$result=mysqli_query($con,$q);
		
	if(mysqli_num_rows($result) > 0)
    { 
		while($row = mysqli_fetch_assoc($result)) 
		{
			$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'] =='update_pur')
{
	$inv_no=$_POST['inv_no'];
	$p_id = $_POST['p_id'];
	$dat=$_POST['dat'];
	$time=$_POST['time'];
	$cha_no=$_POST['cha_no'];
	$vno=$_POST['vno'];
	$s_name=$_POST['sname'];
	
	$l_no=$_POST['l_no'];
	$qty=$_POST['qty'];
	$moisture=$_POST['moisture'];
	$lab_report=$_POST['lab_report'];
	$lap_report_file=isset($_POST['lap_report_file']) ? $_POST['lap_report_file'] : "";
	$isfileUploaded=$_POST['isfileUploaded'];
	$userId=$_POST['userId'];

	$uploaddir = 'upload/';

	$status = false;

	if($isfileUploaded == 1){
		$uploadfile = $uploaddir . basename($_FILES['labfile']['name']);
	    move_uploaded_file($_FILES['labfile']['tmp_name'], $uploadfile);
	    $lap_report_file = $uploadfile;
	}

	$sql11="select * from purchase where p_id = '".$p_id."'";
	$res11=mysqli_query($con,$sql11);
	if (mysqli_num_rows($res11) > 0) {
		$row11 = mysqli_fetch_assoc($res11);
		$re_quantity=$row11['quantity'];
		$querys = "update purchase set dat='".$dat."',time='".$time."',inv_no='".$inv_no."',cha_no='".$cha_no."',vno='".$vno."',supplier_name = '".$s_name."',l_no='".$l_no."',quantity='".$qty."',moisture='".$moisture."',lab_report='".$lab_report."',lap_report_file='".$lap_report_file."',updated_by = CURRENT_TIMESTAMP() where p_id = ".$p_id;
			
        $querysrun = mysqli_query($con, $querys);
        if($querysrun>0)
        {
        	$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,parent_id,updated_by,author) VALUES ('".$inv_no."','".$dat."','".$time."','".$cha_no."','".$vno."','".$row11['item_category']."','".$row11['item']."','".$s_name."','".$row11['ptype']."','".$l_no."','".$row11['quantity_type']."','".$qty."','".$moisture."','".$lab_report."','".$lap_report_file."',".$p_id.",CURRENT_TIMESTAMP(),".$userId.")";

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

			if($queryrun > 0){
	         	$sql="select * from total_purchase_qty where item = '".$row11['item']."' and quantity_type = '".$row11['quantity_type']."' and ptype =".$row11['ptype'];
	         	$res=mysqli_query($con,$sql);
				if (mysqli_num_rows($res) > 0) 
				{
				   $row = mysqli_fetch_assoc($res);
					$qt=$row['quantity'];
					if($re_quantity > $qt)
					{
						$minus=$re_quantity-$qt;
						$tquantity=$qty+$minus;
						$query2 = "update total_purchase_qty set quantity = '".$tquantity."' where item = '".$row11['item']."' and quantity_type ='".$row11['quantity_type']."' and ptype=".$row11['ptype'];
						$querysrun2 = mysqli_query($con, $query2);
						if($querysrun2 >0)
						{
							$status = true;
						}
					}else if($re_quantity < $qt)
					{
						$plus=$qt-$re_quantity;
						$tquantity=$qty+$plus;
						$query2 = "update total_purchase_qty set quantity = '".$tquantity."' where item = '".$row11['item']."' and quantity_type = '".$row11['quantity_type']."' and ptype=".$row11['ptype'];
						$querysrun2 = mysqli_query($con, $query2);
						if($querysrun2 >0)
						{
							$status = true;
						}
					}else{
						
						$tquantity = $qty;
						
						$query2 = "update total_purchase_qty set quantity = '".$tquantity."' where item = '".$row11['item']."' and quantity_type = '".$row11['quantity_type']."' and ptype=".$row11['ptype'];
						$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'] == 'multiple_purchase')
{
		
	$inv_no=$_POST['inv_no'];
    $dat=$_POST['dat'];
	$time=$_POST['time'];
	$cha_no=$_POST['cha_no'];
	$vno=$_POST['vno'];
	$item_category=$_POST['item_category'];
	$item=$_POST['item'];
	$s_name=$_POST['sname'];
	
	$ptype=$_POST['ptype'];
	$l_no=$_POST['l_no'];
	$qty_typ=$_POST['qty_typ'];
	$qty=$_POST['qty'];
	$moisture=$_POST['moisture'];
	$lab_report=$_POST['lab_report'];
	$userId=$_POST['userId'];
		
	$uploaddir = 'upload/';
	$uploadfile = $uploaddir . basename($_FILES['labfile']['name']);
         move_uploaded_file($_FILES['labfile']['tmp_name'], $uploadfile);
	
	$number= count($_POST["item"]);


	$insertedCount =0;
	if($number > 0)
	{
	for($i=0; $i < $number; $i++)
	{
	if(trim($_POST["item"][$i]) != '')
		{
		
			$item1=mysqli_real_escape_string($con,$_POST["item"][$i]);
			$qty_typs=mysqli_real_escape_string($con,$_POST["qty_typ"][$i]);
			$qtys=mysqli_real_escape_string($con,$_POST["qty"][$i]);

			$itemcategorys=mysqli_real_escape_string($con,$_POST["item_category"][$i]);
			$ptypes=mysqli_real_escape_string($con,$_POST["ptype"][$i]);
			$moistures=mysqli_real_escape_string($con,$_POST["moisture"][$i]);
			
			
			$query = "INSERT INTO purchase(inv_no,dat,time,cha_no,vno,item_category,item,supplier_name,ptype,l_no,quantity_type,quantity,moisture,lab_report,lap_report_file,author) VALUES ('".$inv_no."','".$dat."','".$time."','".$cha_no."','".$vno."','".$itemcategorys."','".$item1."','".$s_name."','".$ptypes."','".$l_no."','".$qty_typs."','".$qtys."','".$moistures."','".$lab_report."','".$uploadfile."',".$userId.")";
				 
			$queryrun = mysqli_query($con, $query);
	        if($queryrun > 0)
	        { 
	           $last_id = mysqli_insert_id($con);
	           $sql="select * from total_purchase_qty where item = '".$item1."' and quantity_type = '".$qty_typs."' and ptype=".$ptypes;
	           $res=mysqli_query($con,$sql);

			    if (mysqli_num_rows($res) > 0) {
				    $row = mysqli_fetch_assoc($res);
				
					$qt=$row['quantity'];
						
					$tquantity=$qt+$qtys;
					$query2 = "update total_purchase_qty set quantity = '".$tquantity."' where item = '".$item1."' and quantity_type = '".$qty_typs."' and ptype=".$ptypes;
					$querysrun2 = mysqli_query($con, $query2);
					if($querysrun2 >0)
					{
						$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,parent_id,author) VALUES ('".$inv_no."','".$dat."','".$time."','".$cha_no."','".$vno."','".$itemcategorys."','".$item1."','".$s_name."','".$ptypes."','".$l_no."','".$qty_typs."','".$qtys."','".$moistures."','".$lab_report."','".$uploadfile."',".$last_id.",".$userId.")";

						$queryrun = mysqli_query($con, $query);
						if($queryrun >0){
							$insertedCount++;
						}
					}
				}else{
					$query1 = "INSERT INTO total_purchase_qty(item, quantity_type, quantity,ptype) VALUES('".$item1."', '".$qty_typs."', ".$qtys.",".$ptypes.");";
											 
					$queryrun1 = mysqli_query($con, $query1);
					if($queryrun1 > 0){ 

						$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,parent_id,author) VALUES ('".$inv_no."','".$dat."','".$time."','".$cha_no."','".$vno."','".$itemcategorys."','".$item1."','".$s_name."','".$ptypes."','".$l_no."','".$qty_typs."','".$qtys."','".$moistures."','".$lab_report."','".$uploadfile."',".$last_id.",".$userId.")";

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

					}
				}
			   
			}
					
		}
	}
		if($insertedCount == 0){
			$myObj = [ 'status' => false,'msg'=>'Failed to add products'];
		}else{
			$myObj = [ 'status' => true,'msg'=>$insertedCount." Purchase Added 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'] == 'add_final_product')
{
	$p_name=mysqli_real_escape_string($con,$_POST['pname']);
	
    $sql1="SELECT item FROM final_product where item ='".$p_name."';";
	$result = $con->query($sql1);

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

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

}else if($_POST['type'] == 'deleteFromPurchase')
{
	$puchaseId=$_POST['puchaseId'];
	$userId=$_POST['userId'];

	$status = false;
	$msg ="Failed to Delete purchase";
	
	$sql="select * from purchase p where p_id =".$puchaseId;
	$res=mysqli_query($con,$sql);

	if (mysqli_num_rows($res) > 0) 
	{
		while($rows=mysqli_fetch_assoc($res)){
			$sql2="select * from total_purchase_qty where item = '".$rows["item"]."' and quantity_type = '".$rows["quantity_type"]."' and ptype=".$rows["ptype"];

			$res2=mysqli_query($con,$sql2);

			if (mysqli_num_rows($res2) > 0) 
			{
				while($rows2=mysqli_fetch_assoc($res2)){
					$sql1="select * from admin_dpts ad where storageId in (".$rows2["id"].");";
					$result = $con->query($sql1);

					if ($result->num_rows > 0) {
						$msg = "The Purchase is processed,therefore cannot be deleted,please delete from processed Departments first!";
					}else{
						$totalqty = $rows2["quantity"]-$rows["quantity"];

						$query2 = "update total_purchase_qty set quantity = '".$totalqty."' where id=".$rows2["id"] ;

						$queryrun2 = mysqli_query($con, $query2);
						if($queryrun2 >0){
							$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() , '".$userId."' 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 purchase where p_id =".$puchaseId;
								 
								$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);
}

?>