<?php
	header('Content-Type: application/json');
	include("includes/dbconfig.php");
	
	session_write_close();
	
	$err = "";
	
	$server_response = array();
	
	$category = $_POST['category'];
	$catname = trim($_POST['catname']);
	$catdescription = trim($_POST['catdescription']);
	$recversion = $_POST['recversion'];
	
	if(isset($_SESSION['connecteduserid']))
	{
		if($_SESSION["connectedusergroup"] == 1)
		{
			if($catname == "")
			{
				$err = $err."Category Name Required!<br>";
			}
			else
			{
				if($category > 0)
				{
					$catdata = DB::queryFirstRow("SELECT category_name FROM item_category WHERE id=%i ", $category);
					
					if(DB::count() == 1) 
					{
						DB::queryFirstRow("SELECT id FROM item_category WHERE category_name=%s AND id!=%i", $catname, $category);
					
						if(DB::count() > 0)
							$err = $err."Category Name Already Exists!<br>";
					}
					else
					{
						$err = $err."Category Can Not Be Identified!<br>";
					}
				}
				else
				{
					DB::queryFirstRow("SELECT id FROM item_category WHERE category_name=%s", $catname);
					
					if(DB::count() > 0)
						$err = $err."Category Name Already Exists!<br>";
				}

			}
		}
		else
		{
			$err = $err."Limited Access!<br>";
		}
	}
	else
	{
		$err = $err."Un Authenticated User Access Detected!<br>";
	}
	
	if($err == "")
	{
		DB::$error_handler = false;
		DB::$throw_exception_on_error = true;
		
		if($category == 0)
		{
			try
			{
				DB::startTransaction();
				DB::query("SET SESSION TRANSACTION ISOLATION LEVEL SERIALIZABLE");
				DB::insert
				('item_category', 
					array
					(
						'created_by' => $_SESSION["connecteduserid"],
						'category_name' => $catname,
						'category_description' => $catdescription
					)
				);
				
				DB::commit();
				$savestatusmessage = "<div class=\"alert alert-success\"><button type=\"button\" class=\"close\" data-dismiss=\"alert\"aria-hidden=\"true\">&times;</button>Item Category Successfully Saved!</div>";
				$server_response[] = array('issaved' => 1, 'message' => $savestatusmessage);
				echo json_encode($server_response);
			}
			catch(MeekroDBException $e)
			{
				$err = $err.$e->getMessage()."<br>";
				$err = $err.$e->getQuery()."<br>";
				DB::rollback();
				$errormessage = "<div class=\"alert alert-danger\"><button type=\"button\" class=\"close\" data-dismiss=\"alert\"aria-hidden=\"true\">&times;</button>" . $err . "</div>";
				$server_response[] = array('issaved' => 0, 'message' => $errormessage);
				DB::$error_handler = 'meekrodb_error_handler';
				DB::$throw_exception_on_error = false;
				echo json_encode($server_response);
				exit();
			}
		}
		else
		{
			try
			{
				$trxnConnextn = new MeekroDB();
				$nonTrxnConnextn = new MeekroDB();
				
				$trxnConnextn->startTransaction();
				$trxnConnextn->query("SET SESSION TRANSACTION ISOLATION LEVEL SERIALIZABLE");
				$trxnConnextn->query("SELECT * FROM item_category WHERE id=%i FOR UPDATE", $category);
				
				$trxnConnextn->update
				('item_category', 
					array
					(
						'updated_date' => $trxnConnextn->sqleval("current_timestamp()"),
						'updated_by' => $_SESSION["connecteduserid"],
						'category_name' => $catname,
						'category_description' => $catdescription,
						'version' => ($recversion + 1)
					), 
					"id=%i", $category
				);
				
				$row = $nonTrxnConnextn->queryFirstRow("SELECT version FROM item_category WHERE id=%i LIMIT 1", $category);
				
				if($row['version'] == $recversion)
				{
					$trxnConnextn->commit();
					$savestatusmessage = "<div class=\"alert alert-success\"><button type=\"button\" class=\"close\" data-dismiss=\"alert\"aria-hidden=\"true\">&times;</button>Item Category Successfully Updated!</div>";
					$server_response[] = array('issaved' => 1, 'message' => $savestatusmessage);
					DB::$error_handler = 'meekrodb_error_handler';
					DB::$throw_exception_on_error = false;
					echo json_encode($server_response);
				}
				else
				{
					$trxnConnextn->rollback();
					$errormessage = "<div class=\"alert alert-danger\"><button type=\"button\" class=\"close\" data-dismiss=\"alert\"aria-hidden=\"true\">&times;</button>Item Category Details Could Not Be Updated Due To Updates Just Done By Another System User</div>";
					$server_response[] = array('issaved' => 0, 'message' => $errormessage);
					DB::$error_handler = 'meekrodb_error_handler';
					DB::$throw_exception_on_error = false;
					echo json_encode($server_response);
				}
			}
			catch(MeekroDBException $e)
			{
				$err = $err.$e->getMessage()."<br>";
				$err = $err.$e->getQuery()."<br>";
				$trxnConnextn->rollback();
				$errormessage = "<div class=\"alert alert-danger\"><button type=\"button\" class=\"close\" data-dismiss=\"alert\"aria-hidden=\"true\">&times;</button>" . $err . "</div>";
				$server_response[] = array('issaved' => 0, 'message' => $errormessage);
				DB::$error_handler = 'meekrodb_error_handler';
				DB::$throw_exception_on_error = false;
				echo json_encode($server_response);
				exit();
			}
		}
	}
	else
	{
		$errormessage = "<div class=\"alert alert-danger\"><button type=\"button\" class=\"close\" data-dismiss=\"alert\"aria-hidden=\"true\">&times;</button>" . $err . "</div>";
		$server_response[] = array('issaved' => 0, 'message' => $errormessage);
		echo json_encode($server_response);
	}
?>