<?php
	header('Content-Type: application/json');
	include("includes/dbconfig.php");
	
	session_write_close();
	
	$err = "";
	
	$server_response = array();
	
	$shop = trim($_POST['shop']);
	$cartitems = json_decode(stripslashes($_POST['cartitems']), TRUE);
	$memo = trim($_POST['memo']);
	
	if(isset($_SESSION['connecteduserid']))
	{
		if($_SESSION["connectedusergroup"] == 2)
		{
			if($shop == "")
			{
				$err = $err."Destination Shop Required!<br>";
			}
			else
			{
				if(empty($cartitems))
				{
					$err = $err."Cart Items Required!<br>";
				}
				else
				{
					foreach($cartitems as $cartitem)
					{
						if($cartitem['quantity'] == 0)
						{
							$err = $err.$cartitem['itemname']." With Zero Quantity Is Not Supported!<br>";
						}
						
						if($shop == "x")
						{
							if(DB::queryFirstField("SELECT COUNT(item_stock_level.id) FROM item_stock_level INNER JOIN item_stock_level shop ON shop.item = item_stock_level.item AND shop.shop=%i AND shop.id=%i WHERE item_stock_level.shop IS NULL", $shop, $cartitem['stockid']) != 1)
							{
								$err = $err.$cartitem['itemname']." Does Not Exist In Store!<br>";
							}
						}
						else
						{
							if(DB::queryFirstField("SELECT COUNT(item_stock_level.id) FROM item_stock_level INNER JOIN item_stock_level shop ON shop.item = item_stock_level.item AND shop.shop=%i AND shop.id=%i WHERE item_stock_level.shop=%i", $shop, $cartitem['stockid'], $shop) != 1)
							{
								$err = $err.$cartitem['itemname']." Does Not Exist In Selected Shop!<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");
			
			foreach($cartitems as $cartitem)
			{
				$originstockdata = $trxnConnextn->queryFirstRow("SELECT shop, quantity, version FROM item_stock_level WHERE id=%i", $cartitem['stockid']);
				
				if($shop =='xx' )
				{
					$destinationstockdata = $trxnConnextn->queryFirstRow("SELECT item_stock_level.id, item_stock_level.item, item_stock_level.quantity, item_stock_level.version FROM item_stock_level INNER JOIN item_stock_level originshop ON originshop.item = item_stock_level.item AND originshop.shop=%i AND originshop.id=%i WHERE item_stock_level.shop IS NULL", $_SESSION["connecteduserbranch"], $cartitem['stockid']);
					
					$trxnConnextn->update
					('item_stock_level', 
						array
						(
							'updated_date' => date('Y-m-d H:i:s'),
							'updated_by' => $_SESSION["connecteduserid"],
							'quantity' => ($originstockdata['quantity'] - $cartitem['quantity']),
							'version' => ($originstockdata['version'] + 1)
						), 
						"id=%i", $cartitem['stockid']
					);
					
					$trxnConnextn->update
					('item_stock_level', 
						array
						(
							'updated_date' => date('Y-m-d H:i:s'),
							'updated_by' => $_SESSION["connecteduserid"],
							'quantity' => ($destinationstockdata['quantity'] + $cartitem['quantity']),
							'version' => ($destinationstockdata['version'] + 1)
						), 
						"id=%i", $destinationstockdata['id']
					);
					
					$trxnConnextn->insert
					('stock_item_movement', 
						array
						(
							'created_date' => date('Y-m-d H:i:s'),
							'created_by' => $_SESSION["connecteduserid"],
							'value_date' => date("Y-m-d"),
							'goods_transfer_note' => NULL,
							'item' => $destinationstockdata['item'],
							 
							'origin' => $shop,
							'destination' => NULL,
							'quantity' => $cartitem['quantity'],
							'memo' => $memo
						)
					);
				}
				else
				{
					$destinationstockdata = $trxnConnextn->queryFirstRow("SELECT item_stock_level.id, item_stock_level.item, item_stock_level.quantity, item_stock_level.version FROM item_stock_level INNER JOIN item_stock_level originshop ON originshop.item = item_stock_level.item AND originshop.shop=%i AND originshop.id=%i WHERE item_stock_level.shop=%i", $shop, $cartitem['stockid'], $shop);
					
					$balance = $originstockdata['quantity'] - $cartitem['quantity'];
					if($balance <1){
						$balance = 0;
					}
					$trxnConnextn->update
					('item_stock_level', 
						array
						(
							'updated_date' => date('Y-m-d H:i:s'),
							'updated_by' => $_SESSION["connecteduserid"],
							'quantity' => $balance,
							'version' => ($originstockdata['version'] + 1)
						), 
						"id=%i", $cartitem['stockid']
					);
					
					$trxnConnextn->update
					('item_stock_level', 
						array
						(
							'updated_date' => date('Y-m-d H:i:s'),
							'updated_by' => $_SESSION["connecteduserid"],
							'quantity' => ($destinationstockdata['quantity'] + $cartitem['quantity']),
							'version' => ($destinationstockdata['version'] + 1)
						), 
						"id=%i", $destinationstockdata['id']
					);
					
					$trxnConnextn->insert
					('stock_item_movement', 
						array
						(
							'created_date' => date('Y-m-d H:i:s'),
							'created_by' => $_SESSION["connecteduserid"],
							'value_date' => date("Y-m-d"),
							'goods_transfer_note' => NULL,
							'item' => $destinationstockdata['item'],
							'origin' => $shop,
							'destination' => NULL,
							'quantity' => $cartitem['quantity'],
							'memo' => $memo
						)
					);
				}
				
			}		
			
			$trxnConnextn->commit();
			$savestatusmessage = "<div class=\"alert alert-success\"><button type=\"button\" class=\"close\" data-dismiss=\"alert\"aria-hidden=\"true\">&times;</button>Item(s) 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);
		}
		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);
	}
?>