<?php
	header('Content-Type: application/json');
	include("includes/dbconfig.php");
	
	session_write_close();
	
	$err = "";
	
	$server_response = array();
	
	$tag = $_POST['tag'];
	
	$recversion = $_POST['recversion'];
	
	if(isset($_SESSION['connecteduserid']))
	{
		if($_SESSION["connectedusergroup"] == 1)
		{
			if($tag == "")
			{
				$err = $err."Tag Identification Required!<br>";
			}
			else
			{
				$tagdata = DB::queryFirstRow("SELECT tag_name FROM gl_tag WHERE id=%i", $tag);
			
				if(DB::count() != 1)
				{
					$err = $err."Tag Not Identified!<br>";
				}
				else
				{
					$tagusecount = DB::queryFirstField("SELECT COUNT(id) AS tagusecount FROM gl_gltrxn WHERE tag=%i", $tag);
					
					if($tagusecount > 0)
						$err = $err."Tag Already Used On GL Transactions Can Not Be Deleted!<br>";
				}
				
			}
		}
		else
		{
			$err = $err."Limited Access!<br>";
		}
	}
	else
	{
		$err = $err."Un Authenticated User Access Detected!<br>";
	}
	
	if($err == "")
	{
		try
		{
			$trxnConnextn = new MeekroDB();
			$nonTrxnConnextn = new MeekroDB();
			
			$trxnConnextn->startTransaction();
			$trxnConnextn->query("SET SESSION TRANSACTION ISOLATION LEVEL SERIALIZABLE");
			$trxnConnextn->query("SELECT * FROM gl_tag WHERE id=%i FOR UPDATE", $tag);
			
			$row = $nonTrxnConnextn->queryFirstRow("SELECT version FROM gl_tag WHERE id=%i LIMIT 1", $tag);
			
			if($row['version'] == $recversion)
			{
				$trxnConnextn->delete('gl_tag', "id=%i", $tag);
				$trxnConnextn->commit();
				
				$server_response[] = array('issaved' => 1, 'message' => "Tag Successfully Deleted.");
				echo json_encode($server_response);
			}
			else
			{
				$trxnConnextn->rollback();
				$server_response[] = array('issaved' => 0, 'message' => "Tag Was Not Deleted Due To Changes Done By Another User. Refresh The Tag List View And Try Again");
				echo json_encode($server_response);
			}
		}
		catch(Exception $e)
		{
			$server_response[] = array('issaved' => 0, 'message' => "Tag Delete Error Occured. Try Again");
			echo json_encode($server_response);
			exit();
		}
		
	}
	else
	{
		$server_response[] = array('issaved' => 0, 'message' => $err);
		echo json_encode($server_response);
	}
?>