<?php
	header('Content-Type: application/json');
	include("includes/dbconfig.php");
	
	session_write_close();
	
	$err = "";
	
	$server_response = array();
	
	$stockitem = $_POST['stockitem'];
	$costprice = (str_replace(",", "", trim($_POST['costprice'])) == "" ) ? 0 : str_replace(",", "", trim($_POST['costprice']));
	$sellprice = (str_replace(",", "", trim($_POST['sellprice'])) == "" ) ? 0 : str_replace(",", "", trim($_POST['sellprice']));
	$recversion = $_POST['recversion'];
	
	$isvalidshopitem = FALSE;
	
	if(isset($_SESSION['connecteduserid']))
	{
		if($_SESSION["connectedusergroup"] == 1)
		{
			if($stockitem == "")
			{
				$err = $err."Item Identification Required!<br>";
			}
			else
			{
				$itemstockdata = DB::queryFirstRow("SELECT stock_item.item_name, stock_item.item_code, stock_item.bar_code, item_price.cost_price, item_price.sell_price FROM item_price INNER JOIN stock_item ON item_price.item = stock_item.id WHERE item_price.id=%i", $stockitem);
				
				if(DB::count() == 1)
				{
					if($costprice != "")
					{
						if(!is_numeric($costprice))
							$err = $err."Numeric Cost Price Required!<br>";
					}
					
					if($sellprice == "")
					{
						$err = $err."Sell Price Required!<br>";
					}
					else
					{
						if(!is_numeric($sellprice))
						{
							$err = $err."Numeric Sell Price Required!<br>";
						}
						else
						{
							if($sellprice <= 0)
								$err = $err."Sell Price Greater Than Zero Required!<br>";
							
						}
					}
				}
				else
				{
					$err = $err."Item Not Identified!<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;
		
		try
		{
			$trxnConnextn = new MeekroDB();
			$nonTrxnConnextn = new MeekroDB();
			
			$trxnConnextn->startTransaction();
			$trxnConnextn->query("SET SESSION TRANSACTION ISOLATION LEVEL SERIALIZABLE");
			$trxnConnextn->query("SELECT * FROM item_price WHERE id=%i FOR UPDATE", $stockitem);
			
			$trxnConnextn->update
			('item_price', 
				array
				(
					'updated_date' => date('Y-m-d H:i:s'),
					'updated_by' => $_SESSION["connecteduserid"],
					'cost_price' => $costprice,
					'sell_price' => $sellprice,
					'version' => ($recversion + 1)
				), 
				"id=%i", $stockitem
			);
		
			$row = $nonTrxnConnextn->queryFirstRow("SELECT version FROM item_price WHERE id=%i LIMIT 1", $stockitem);
			
			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>Price 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>Price 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);
	}
?>