<?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']);
	$shop = $_POST['shop'];
	$quantity = (str_replace(",", "", trim($_POST['quantity'])) == "" ) ? 0 : str_replace(",", "", trim($_POST['quantity']));
	$the_item_code = $memo = trim($_POST['memo']);
	$recversion = $_POST['recversion'];
	$the_item_code =  $_POST['transfernumber'];
	//$the_item_code = $_POST['the_item_code'  ];
	
	
	
	$isvaliditemstatus = FALSE;
	
	$i_items = DB::query("SELECT id, item_code FROM stock_item where item_code = '{$the_item_code}'");
	
	//echo "<br />".$the_item_code;
														
	foreach ($i_items as $i_item)
	{
		$i_id = $i_item['id'];
		//echo "<br />".$i_id;
	}
	
	
	$s_items = DB::query("SELECT id, shop, item, quantity FROM item_stock_level where shop = '{$shop}' and  item = '{$i_id}' LIMIT 1");
														
	foreach ($s_items as $s_item)
	{
		$s_id = $s_item['id'];
		$s_qty = $s_item['quantity'];
	}
	
	if(isset($_SESSION['connecteduserid']))
	{
		if($_SESSION["connectedusergroup"] == 2 || $_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.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 IS NULL AND item_stock_level.id=%i", $stockitem);
				
				if(DB::count() == 1)
				{
					 
						if($itemstockdata['status'] != 1)
						{
							$err = $err."Item Status Does Not Support Item Transfer!<br>";
						}
						else
						{
							$isvaliditemstatus = TRUE;
						}
					 
					
					if($isvaliditemstatus)
					{
						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($shop == "")
						{
							$err = $err."Destination Shop Required!<br>";
						}
						else
						{
							 
								if(DB::queryFirstField("SELECT COUNT(id) FROM item_stock_level WHERE shop=%i AND item=%i   AND is_active = 1", $shop, $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);
			
			$trxnConnextn->update
			('item_stock_level', 
				array
				(
					'updated_date' => $trxnConnextn->sqleval("current_timestamp()"),
					'updated_by' => $_SESSION["connecteduserid"],
					'quantity' => ($itemstockdata['quantity'] - $quantity) 
				), 
				"id=%i", $stockitem
			);
			
			$trxnConnextn->update
			('item_stock_level', 
				array
				(
					'updated_date' => $trxnConnextn->sqleval("current_timestamp()"),
					'updated_by' => $_SESSION["connecteduserid"],
					'quantity' => ($s_qty + $quantity) 
				), 
				"id=%i", $s_id
			);
		
			$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'],
					 
					'destination' => $shop,
					'quantity' => $quantity,
					'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 To Shop!</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 To Shop 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);
	}
?>