<?php
	header('Content-Type: application/json');
	include("includes/dbconfig.php");
	
	session_write_close();
	
	$err = "";
	
	$server_response = array();
	
	$stockitem = $_POST['stockitem'];
	$valuedate = trim($_POST['valuedate']);
	$transfernumber = trim($_POST['transfernumber']);
	$quantity = (str_replace(",", "", trim($_POST['quantity'])) == "" ) ? 0 : str_replace(",", "", trim($_POST['quantity']));
	$memo = trim($_POST['memo']);
	$recversion = $_POST['recversion'];
	
	if(isset($_SESSION['connecteduserid']))
	{
		if($_SESSION["connectedusergroup"] == 2)
		{
			if($stockitem == "")
			{
				$err = $err."Item Identification Required!<br>";
			}
			else
			{
				$itemstockdata = DB::queryFirstRow("SELECT stock_item_movement.item, stock_item_movement.batch, stock_item.item_name, stock_item.item_code, stock_item.bar_code, item_batch.batch_code,  CURRENT_DATE() AS date_now, stock_item_movement.origin, stock_item_movement.destination, stock_item_movement.quantity, stock_item_movement.received_quantity, stock_item_movement.is_complete, stock_item_movement.version FROM stock_item_movement LEFT JOIN stock_item ON stock_item_movement.item = stock_item.id LEFT JOIN item_batch ON stock_item_movement.batch = item_batch.id AND stock_item_movement.item = item_batch.item WHERE stock_item_movement.id=%i AND stock_item_movement.destination IS NULL", $stockitem);
				
				if(DB::count() == 1)
				{
					if($valuedate == "")
					{
						$err = $err."Return 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 Return Date Required!<br>";
						}
						else
						{
							if(strtotime($valuedate) > strtotime($itemstockdata['date_now']))
							{
								$err = $err."Return Date Not Exceeding Current Date Required!<br>";
							}
						}
					}
					
					if($itemstockdata['batch'] != "")
					{
						if(DB::queryFirstField("SELECT COUNT(id) FROM item_stock_level WHERE shop IS NULL AND item=%i AND batch=%i", $itemstockdata['item'], $itemstockdata['batch']) != 1)
						{
							$err = $err.$itemstockdata['item_name']." Does Not Exist In Store!<br>";
						}
						else
						{
							$shopstockdata = DB::queryFirstRow("SELECT id, quantity, version FROM item_stock_level WHERE shop IS NULL AND item=%i AND batch=%i", $itemstockdata['item'], $itemstockdata['batch']);
						}
					}
					else
					{
						if(DB::queryFirstField("SELECT COUNT(id) FROM item_stock_level WHERE shop IS NULL AND item=%i AND batch IS NULL", $itemstockdata['item']) != 1)
						{
							$err = $err.$itemstockdata['item_name']." Does Not Exist In Store!<br>";
						}
						else
						{
							$shopstockdata = DB::queryFirstRow("SELECT id, quantity, version FROM item_stock_level WHERE shop IS NULL AND item=%i AND batch IS NULL", $itemstockdata['item']);
						}
					}
					
					if($quantity == "")
					{
						$err = $err."Return Quantity Required!<br>";
					}
					else
					{
						if(!is_numeric($quantity))
						{
							$err = $err."Numeric Return Quantity Required!<br>";
						}
						else
						{
							if($quantity <= 0)
							{
								$err = $err."Return Quantity Greater Than Zero Required!<br>";
							}
							else
							{
								if($quantity > ($itemstockdata['quantity'] - $itemstockdata['received_quantity']))
									$err = $err."Received Quantity Not Exceeding Sent Quantity Balance (".number_format(($itemstockdata['quantity'] - $itemstockdata['received_quantity']), 2).") 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 stock_item_movement WHERE id=%i FOR UPDATE", $stockitem);
			$trxnConnextn->query("SELECT * FROM item_stock_level WHERE id=%i FOR UPDATE", $shopstockdata['id']);
			
			$trxnConnextn->update
			('item_stock_level', 
				array
				(
					'updated_date' => $trxnConnextn->sqleval("current_timestamp()"),
					'updated_by' => $_SESSION["connecteduserid"],
					'quantity' => ($itemstockdata['quantity'] + $quantity),
					'version' => ($shopstockdata['version'] + 1)
				), 
				"id=%i", $shopstockdata['id']
			);
		
			$trxnConnextn->update
			('stock_item_movement', 
				array
				(
					'updated_date' => $trxnConnextn->sqleval("current_timestamp()"),
					'updated_by' => $_SESSION["connecteduserid"],
					'received_quantity' => ($itemstockdata['received_quantity'] + $quantity),
					'is_complete' => ($quantity == ($itemstockdata['quantity'] - $itemstockdata['received_quantity'])) ? 1 : 0,
					'version' => ($recversion + 1)
				), 
				"id=%i", $stockitem
			);
			
			$trxnConnextn->insert
			('item_movement_receipt', 
				array
				(
					'created_by' => $_SESSION["connecteduserid"],
					'value_date' => date("Y-m-d", strtotime($valuedate)),
					'reference_number' => $transfernumber,
					'transfer_id' => $stockitem,
					'item' => $itemstockdata['item'],
					'batch' => ($itemstockdata['batch'] != "") ? $itemstockdata['batch'] : NULL,
					'shop' => NULL,
					'quantity' => $quantity,
					'memo' => $memo
				)
			);
		
			$row = $nonTrxnConnextn->queryFirstRow("SELECT version FROM stock_item_movement WHERE id=%i LIMIT 1", $stockitem);
			$storerow = $nonTrxnConnextn->queryFirstRow("SELECT version FROM item_stock_level WHERE id=%i LIMIT 1", $shopstockdata['id']);
			
			if($row['version'] == $recversion && $storerow['version'] == $shopstockdata['version'])
			{
				$trxnConnextn->commit();
				$savestatusmessage = "<div class=\"alert alert-success\"><button type=\"button\" class=\"close\" data-dismiss=\"alert\"aria-hidden=\"true\">&times;</button>Item Quantity Successfully Returned 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 Returned 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);
	}
?>