<?php
	header('Content-Type: application/json');
	include("includes/dbconfig.php");
	
	session_write_close();
	
	$err = "";//
	
	$server_response = array();
	
	$stockitem = $_POST['stockitem'];
	$valuedate = trim($_POST['valuedate']);
	$referencenumber = trim($_POST['referencenumber']);
	$adjustmenttype = $_POST['adjustmenttype'];
	$quantity = (str_replace(",", "", trim($_POST['quantity'])) == "" ) ? 0 : str_replace(",", "", trim($_POST['quantity']));
	$memo = trim($_POST['memo']);
	$recversion = $_POST['recversion'];
	
	$isvalidshopitem = FALSE;
	
	if(isset($_SESSION['connecteduserid']))
	{
		if($_SESSION["connectedusergroup"] == 2 || $_SESSION["connectedusergroup"] == 3 || $_SESSION["connectedusergroup"] == 1)
		{
			if($stockitem == "")
			{
				$err = $err."Item Identification Required!<br>";
			}
			else
			{
			$itemstockdata = DB::queryFirstRow("SELECT stock_item.item_name, stock_item.status, CURRENT_DATE() AS date_now, item_stock_level.shop, item_stock_level.item, item_stock_level.quantity FROM item_stock_level INNER JOIN stock_item ON item_stock_level.item = stock_item.id  WHERE item_stock_level.id=%i", $stockitem);
				
				
				if(DB::count() == 1)
				{
					/*if($_SESSION["connectedusergroup"] == 2 && $itemstockdata['shop'] != "")
					{
						$err = $err."You Are Not Authorised To Adjust Shop Stock!<br>";
					}*/
					
				/*	if($_SESSION["connectedusergroup"] == 3 && $itemstockdata['shop'] != $_SESSION["connecteduserbranch"])
					{
						$err = $err."You Are Not Authorised To Adjust Stock Item Quantities Other Than Those Allocated To Your Shop!<br>";
					}*/
					
					if($valuedate == "")
					{
						$err = $err."Adjustment Date Required!<br>";
					}
					else
					{
						$month = substr($valuedate, 0, 2);
						$day = substr($valuedate, 3, 2);
						$year = substr($valuedate, 6, 4);
						
						if(!checkdate($month, $day, $year))
						{
							$err = $err."Valid Adjustment Date Required!<br>";
						}
						else
						{
							if(strtotime($valuedate) > strtotime($itemstockdata['date_now']))
							{
							    $valuedate = date('Y-m-d');
								
								//$err = $err."Adjustment Date Not Exceeding Current Date Required!<br>";
							}
						}
					}
					
					if($adjustmenttype == "")
						$err = $err."Adjustment Type Required!<br>";
					
					if($quantity == "")
					{
						$err = $err."Adjustment Quantity Required!<br>";
					}
					else
					{
						if(!is_numeric($quantity))
						{
							$err = $err."Numeric Adjustment Quantity Required!<br>";
						}
						else
						{
							if($quantity <= 0)
							{
								$err = $err."Adjustment Quantity Greater Than Zero Required!<br>";
							}
							else
							{
								if($adjustmenttype == 0)
								{
									if($quantity > $itemstockdata['quantity'])
										$err = $err."Reduction Quantity Not Exceeding Stock Quantity (".$itemstockdata['quantity'].") 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_stock_level WHERE id=%i FOR UPDATE", $stockitem);
			
			$trxnConnextn->update
			('item_stock_level', 
				array
				(
					'updated_date' => $trxnConnextn->sqleval("current_timestamp()"),
					'updated_by' => $_SESSION["connecteduserid"],
					'quantity' => ($adjustmenttype == 1) ? ($itemstockdata['quantity'] + $quantity) : ($itemstockdata['quantity'] - $quantity),
					'version' => ($recversion + 1)
				), 
				"id=%i", $stockitem
			);
		
			$trxnConnextn->insert
			('stock_item_adjustment', 
				array
				(
					'created_by' => $_SESSION["connecteduserid"],
					'value_date' => date("Y-m-d", strtotime($valuedate)),
					'reference_number' => $referencenumber,
					'item' => $itemstockdata['item'],
					 
					'shop' => $itemstockdata['shop'],
					'quantity' => ($adjustmenttype == 1) ? $quantity :  ($quantity * -1),
					'memo' => $memo
				)
			);
			 
			$row = $nonTrxnConnextn->queryFirstRow("SELECT version FROM item_stock_level 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>Item Quantity Successfully Adjusted To Store!</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 Quantity Could Not Be Adjusted To Store 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);
	}
?>