<?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']);
	$destination = $_POST['destination'];
	$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"]  <4)
		{
			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.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.shop=%i AND item_stock_level.id=%i", $_SESSION["connecteduserbranch"], $stockitem);
				
				if(DB::count() == 1)
				{
					if($valuedate == "")
					{
						$err = $err."Transfer 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 Transfer Date Required!<br>";
						}
						else
						{
							if(strtotime($valuedate) > strtotime($itemstockdata['date_now']))
							{
								$err = $err."Transfer Date Not Exceeding Current Date Required!<br>";
							}
						}
					}
					
					if($destination == "")
					{
						$err = $err."Destination Required!<br>";
					}
					else
					{
						if($destination == "x")
						{
							if($itemstockdata['batch'] != "")
							{
								if(DB::queryFirstField("SELECT COUNT(id) FROM item_stock_level WHERE shop IS NULL AND item=%i  ", $itemstockdata['item'] ) != 1)
								{
									$err = $err.$itemstockdata['item_name']." Does Not Exist In Store!<br>";
								}
							}
							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
						{
							if($itemstockdata['batch'] != "")
							{
								if(DB::queryFirstField("SELECT COUNT(id) FROM item_stock_level WHERE shop=%i AND item=%i   AND is_active = 1", $destination, $itemstockdata['item'] ) != 1)
								{
									$err = $err.$itemstockdata['item_name']." Does Not Exist In Selected Shop!<br>";
								}
							}
							else
							{
								if(DB::queryFirstField("SELECT COUNT(id) FROM item_stock_level WHERE shop=%i AND item=%i AND batch IS NULL AND is_active = 1", $destination, $itemstockdata['item']) != 1)
								{
									$err = $err.$itemstockdata['item_name']." Does Not Exist In Selected Shop!<br>";
								}
							}
						}
					}
					
					if($quantity == "")
					{
						$err = $err."Transfer Quantity Required!<br>";
					}
					else
					{
						if(!is_numeric($quantity))
						{
							$err = $err."Numeric Transfer Quantity Required!<br>";
						}
						else
						{
							if($quantity <= 0)
							{
								$err = $err."Transfer Quantity Greater Than Zero Required!<br>";
							}
							else
							{
								if($quantity > $itemstockdata['quantity'])
									$err = $err."Transfer Quantity Not Exceeding Stock 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);
			
			$balance = $itemstockdata['quantity'] - $quantity;
			if($balance < 0){
				$balance = 0;
			}
			
			$trxnConnextn->update
			('item_stock_level', 
				array
				(
					'updated_date' => $trxnConnextn->sqleval("current_timestamp()"),
					'updated_by' => $_SESSION["connecteduserid"],
					'quantity' =>$balance,
					'version' => ($recversion + 1)
				), 
				"id=%i", $stockitem
			);
	
			$trxnConnextn->insert
			('stock_item_movement', 
				array
				(
					'created_by' => $_SESSION["connecteduserid"],
					'value_date' => date("Y-m-d", strtotime($valuedate)),
					'goods_transfer_note' => $transfernumber,
					'item' => $itemstockdata['item'], 
					'origin' => $_SESSION["connecteduserbranch"],
					'destination' => ($destination == "x") ? NULL : $destination,
					'quantity' => $quantity,
					'received_quantity' => $quantity,
					'is_complete' => 1,
					'memo' => $memo
				)
			);
			 
			$storerow = $nonTrxnConnextn->queryFirstRow("SELECT version FROM item_stock_level WHERE id=%i LIMIT 1", $stockitem);
			
			if($storerow['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 Transfered!</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 Transfered 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);
	}
?>