<?php

include('includes/DefineStockAdjustment.php');
include('includes/DefineSerialItems.php');
include('includes/session.php');
$Title = _('Reverse Work Order');

/* EMP manual links before header.php */
$ViewTopic= 'Inventory';
$BookMark = 'WorkOrderReverse';

include('includes/header.php');
include('includes/SQL_CommonFunctions.inc');

if (empty($_GET['identifier']))
{
	/*unique session identifier to ensure that there is no conflict with other adjustment sessions on the same machine  */
	$identifier=date('U');
} else {
	$identifier=$_GET['identifier'];
}

if (isset($_GET['NewAdjustment']))
{
	unset($_SESSION['Adjustment' . $identifier]);
	unset($_SESSION['Component' . $identifier]);
	$_SESSION['Adjustment' . $identifier] = new StockAdjustment();
	$_SESSION['Component' . $identifier] = array();
}
if (!isset($_SESSION['Adjustment' . $identifier]))
{
	$_SESSION['Adjustment' . $identifier] = new StockAdjustment();
}
if (!isset($_SESSION['Component' . $identifier]))
{
	$_SESSION['Component' . $identifier] = array();
}

$NewAdjustment = false;

if (isset($_POST['StockID']))
{
	if($_POST['StockID'] != $_SESSION['Adjustment' . $identifier]->StockID)
	{
		$NewAdjustment = true;
		$StockID = trim(mb_strtoupper($_POST['StockID']));
	}
}

if ($NewAdjustment==true)
{
	$_SESSION['Adjustment' . $identifier]->StockID = trim(mb_strtoupper($StockID));
	$result = DB_query("SELECT description,
							controlled,
							serialised,
							decimalplaces,
							perishable,
							materialcost+labourcost+overheadcost AS totalcost,
							units
						FROM stockmaster
						WHERE stockid='" . $_SESSION['Adjustment' . $identifier]->StockID . "'");
	$myrow = DB_fetch_array($result);
	$_SESSION['Adjustment' . $identifier]->ItemDescription = $myrow['description'];
	$_SESSION['Adjustment' . $identifier]->Controlled = $myrow['controlled'];
	$_SESSION['Adjustment' . $identifier]->Serialised = $myrow['serialised'];
	$_SESSION['Adjustment' . $identifier]->DecimalPlaces = $myrow['decimalplaces'];
	$_SESSION['Adjustment' . $identifier]->SerialItems = array();
	if (!isset($_SESSION['Adjustment' . $identifier]->Quantity) OR !is_numeric($_SESSION['Adjustment' . $identifier]->Quantity)){
		$_SESSION['Adjustment' . $identifier]->Quantity=0;
	}

	$_SESSION['Adjustment' . $identifier]->PartUnit = $myrow['units'];
	$_SESSION['Adjustment' . $identifier]->StandardCost = $myrow['totalcost'];
	$DecimalPlaces = $myrow['decimalplaces'];
	DB_free_result($result);
} //end if it's a new adjustment

if (isset($_POST['tag']))
{
	$_SESSION['Adjustment' . $identifier]->tag = $_POST['tag'];
}

$sql = "SELECT workcentres.location as loccode, description as locationname FROM workcentres INNER JOIN locationusers ON locationusers.loccode=workcentres.location AND locationusers.userid='" .  $_SESSION['UserID'] . "' AND locationusers.canupd=1";
$resultStkLocs = DB_query($sql);
$LocationList=array();
while ($myrow=DB_fetch_array($resultStkLocs))
{
	$LocationList[$myrow['loccode']]=$myrow['locationname'];
}

if (isset($_POST['StockLocation']))
{
	$_SESSION['Adjustment' . $identifier]->StockLocation = $_POST['StockLocation'];
}
else
{
	if(empty($_SESSION['Adjustment' . $identifier]->StockLocation))
	{
		if(empty($_SESSION['UserStockLocation']))
		{
			$_SESSION['Adjustment' . $identifier]->StockLocation=key(reset($LocationList));
		}
		else
		{
			$_SESSION['Adjustment' . $identifier]->StockLocation=$_SESSION['UserStockLocation'];
		}
	}
}
if (isset($_POST['Quantity']))
{
	if ($_POST['Quantity']=='' OR !is_numeric(filter_number_format($_POST['Quantity'])))
	{
		$_POST['Quantity']=0;
	}
}
else
{
	$_POST['Quantity']=0;
}

if($_POST['Quantity'] != 0)
{
	$_SESSION['Adjustment' . $identifier]->Quantity = filter_number_format($_POST['Quantity']);
}

echo '<p class="page_title_text"><img src="'.$RootPath.'/css/'.$Theme.'/images/supplier.png" title="' . _('Reverse Work Order') . '" alt="" />' . ' ' . _('Reverse Work Order') . '</p>';

$recipe_list = "";
if (isset($_POST['CheckCode']))
{
	unset($_SESSION['Component' . $identifier]);

	$sql="SELECT bom.component, bom.quantity
			FROM bom
			LEFT JOIN stockmaster
			ON stockmaster.stockid = bom.parent AND effectiveafter <= '".date('Y-m-d')."' AND effectiveto > '".date('Y-m-d')."'
			WHERE stockid = '" . $_POST['StockID'] ."' AND mbflag = 'M' AND controlled = '0' AND serialised = '0' AND discontinued = '0'";
	$ErrMsg=_('The stock information cannot be retrieved because');
	$DbgMsg=_('The SQL to get the stock description was');
	$result = DB_query($sql,$ErrMsg,$DbgMsg);
	
	while ($myrow = DB_fetch_row($result))
	{
		$Component = new StockAdjustment();
		$Component->StockID = $myrow[0];
		$Component->Quantity = $myrow[1];
		$Component->StandardCost = 0;
		
		$sql = "SELECT materialcost+labourcost+overheadcost AS totalcost FROM stockmaster WHERE stockid = '".$myrow[0]."'";
		$result_total_cost = DB_query($sql,$ErrMsg,$DbgMsg);
		while ($row_total_cost = DB_fetch_row($result_total_cost))
		{
			$Component->StandardCost = $row_total_cost[0];
		}

		$_SESSION['Component' . $identifier][] = $Component;
	}
}

if(isset($_SESSION['Component' . $identifier]) && count($_SESSION['Component' . $identifier]) > 0 && !isset($_POST['EnterAdjustment']))
{
	$recipe_list = '<tr>
				<th colspan="2">BOM for '.$_SESSION['Adjustment' . $identifier]->StockID . '</th>
				<th>' . _('Quantity') . '</th>
			</tr>';

	foreach($_SESSION['Component' . $identifier] as $Component)
	{
		$recipe_list .= '<tr class="striped_row">
							<td colspan="2">' . $Component->StockID . '</td>
							<td>' . $Component->Quantity . '<input type="hidden" name="ComponentID['.$Component->StockID.']" value="'.$Component->Quantity.'" /></td>
						</tr>';
	}
	$recipe_list .= '<tr><td><br></td></tr>';
}

if (isset($_POST['EnterAdjustment']) AND $_POST['EnterAdjustment']!= '')
{
	$InputError = false; /*Start by hoping for the best */
	$result = DB_query("SELECT * FROM stockmaster WHERE stockid='" . $_SESSION['Adjustment' . $identifier]->StockID . "'");
	$myrow = DB_fetch_row($result);
	if($_SESSION['Adjustment' . $identifier]->StockID == "") {
		prnMsg( _('Please select a stock code') . '. ' . _('There would be no adjustment to make'),'error');
		$InputError = true;
	}
	else if (DB_num_rows($result)==0) {
		prnMsg( _('The entered item code does not exist'),'error');
		$InputError = true;
	} elseif (!is_numeric($_SESSION['Adjustment' . $identifier]->Quantity)){
		prnMsg( _('The quantity entered must be numeric'),'error');
		$InputError = true;
	} elseif(strlen(substr(strrchr($_SESSION['Adjustment'.$identifier]->Quantity, "."), 1))>$_SESSION['Adjustment' . $identifier]->DecimalPlaces){
		prnMsg(_('The decimal places input is more than the decimals of this item defined,the defined decimal places is ').' '.$_SESSION['Adjustment' . $identifier]->DecimalPlaces.' '._('and the input decimal places is ').' '.strlen(substr(strrchr($_SESSION['Adjustment'.$identifier]->Quantity, "."), 1)),'error');
		$InputError = true;
	} elseif ($_SESSION['Adjustment' . $identifier]->Quantity==0){
		prnMsg( _('The quantity entered cannot be zero') . '. ' . _('There would be no adjustment to make'),'error');
		$InputError = true;
	} elseif ($_SESSION['Adjustment' . $identifier]->Quantity<0){
		prnMsg( _('The quantity entered cannot be negative'),'error');
		$InputError = true;
	} elseif ($_SESSION['Adjustment' . $identifier]->Controlled==1 AND count($_SESSION['Adjustment' . $identifier]->SerialItems)==0) {
		prnMsg( _('The item entered is a controlled item that requires the detail of the serial numbers or batch references to be adjusted to be entered'),'error');
		$InputError = true;
	} elseif (!isset($_SESSION['Component' . $identifier]) || count($_SESSION['Component' . $identifier]) == 0){
		prnMsg( _('Please select a stock code') . '. ' . _('There would be no adjustment to make'),'error');
		$InputError = true;
	}
	

	// if ($_SESSION['ProhibitNegativeStock']==1) {
		$SQL = "SELECT quantity FROM locstock
				WHERE stockid='" . $_SESSION['Adjustment' . $identifier]->StockID . "'
				AND loccode='" . $_SESSION['Adjustment' . $identifier]->StockLocation . "'";
		$CheckNegResult=DB_query($SQL);
		$CheckNegRow = DB_fetch_array($CheckNegResult);
		if ($CheckNegRow['quantity']-$_SESSION['Adjustment' . $identifier]->Quantity <0){
			$InputError=true;
			prnMsg(_('The system parameters are set to prohibit negative stocks. Processing this stock adjustment would result in negative stock at this location. This adjustment will not be processed.'),'error');
		}
	// }

	if (!$InputError) {

/*All inputs must be sensible so make the stock movement records and update the locations stocks */

		$WorkOrderReverseNumber = GetNextTransNo(98);
		$PeriodNo = GetPeriod (Date($_SESSION['DefaultDateFormat']));
		$SQLAdjustmentDate = FormatDateForSQL(Date($_SESSION['DefaultDateFormat']));

		$Result = DB_Txn_Begin();

		$_SESSION['Adjustment' . $identifier]->Narrative = 'Reverse Work Order for ' . $_SESSION['Adjustment' . $identifier]->StockID . ' x ' . $_SESSION['Adjustment' . $identifier]->Quantity;

		foreach($_SESSION['Component' . $identifier] as $Component)
		{
			// Need to get the current location quantity will need it later for the stock movement
			$SQL="SELECT locstock.quantity
				FROM locstock
				WHERE locstock.stockid='" . $Component->StockID . "'
				AND loccode= '" . $_SESSION['Adjustment' . $identifier]->StockLocation . "'";
			$Result = DB_query($SQL);
			if (DB_num_rows($Result)==1){
				$LocQtyRow = DB_fetch_row($Result);
				$QtyOnHandPrior = $LocQtyRow[0];
			} else {
				// There must actually be some error this should never happen
				$QtyOnHandPrior = 0;
			}

			$SQL = "INSERT INTO stockmoves (stockid,
											type,
											transno,
											loccode,
											trandate,
											userid,
											prd,
											reference,
											qty,
											newqoh,
											standardcost,
											narrative)
										VALUES ('" . $Component->StockID . "',
											98,
											'" . $WorkOrderReverseNumber . "',
											'" . $_SESSION['Adjustment' . $identifier]->StockLocation . "',
											'" . $SQLAdjustmentDate . "',
											'" . $_SESSION['UserID'] . "',
											'" . $PeriodNo . "',
											'" . $_SESSION['Adjustment' . $identifier]->Narrative ."',
											'" . ($Component->Quantity * $_SESSION['Adjustment' . $identifier]->Quantity) . "',
											'" . ($QtyOnHandPrior + ($Component->Quantity * $_SESSION['Adjustment' . $identifier]->Quantity)) . "',
											'" . $Component->StandardCost . "',
											'')";

			$ErrMsg =  _('CRITICAL ERROR') . '! ' . _('NOTE DOWN THIS ERROR AND SEEK ASSISTANCE') . ': ' . _('The stock movement record cannot be inserted because');
			$DbgMsg =  _('The following SQL to insert the stock movement record was used');
			$Result = DB_query($SQL, $ErrMsg, $DbgMsg, true);

			/*Get the ID of the StockMove... */
			$StkMoveNo = DB_Last_Insert_ID('stockmoves','stkmoveno');

			$SQL = "UPDATE locstock SET quantity = quantity + " . floatval($Component->Quantity * $_SESSION['Adjustment' . $identifier]->Quantity) . "
					WHERE stockid='" . $Component->StockID . "'
					AND loccode='" . $_SESSION['Adjustment' . $identifier]->StockLocation . "'";

			$ErrMsg = _('CRITICAL ERROR') . '! ' . _('NOTE DOWN THIS ERROR AND SEEK ASSISTANCE') . ': ' ._('The location stock record could not be updated because');
			$DbgMsg = _('The following SQL to update the stock record was used');
			$Result = DB_query($SQL, $ErrMsg, $DbgMsg, true);

			if ($_SESSION['CompanyRecord']['gllink_stock']==1 AND $Component->StandardCost > 0){

				$StockGLCodes = GetStockGLCode($Component->StockID);
	
				$SQL = "INSERT INTO gltrans (type,
											typeno,
											trandate,
											periodno,
											account,
											amount,
											narrative,
											tag)
									VALUES (98,
										'" . $WorkOrderReverseNumber . "',
										'" . $SQLAdjustmentDate . "',
										'" . $PeriodNo . "',
										'" .  $StockGLCodes['adjglact'] . "',
										'" . round($Component->StandardCost * -($Component->Quantity * $_SESSION['Adjustment' . $identifier]->Quantity), $_SESSION['CompanyRecord']['decimalplaces']) . "',
										'" . $Component->StockID . " x " . ($Component->Quantity * $_SESSION['Adjustment' . $identifier]->Quantity) . " @ " .
											$Component->StandardCost . " " . $_SESSION['Adjustment' . $identifier]->Narrative . "',
										'" . $_SESSION['Adjustment' . $identifier]->tag . "')";
	
				$ErrMsg = _('CRITICAL ERROR') . '! ' . _('NOTE DOWN THIS ERROR AND SEEK ASSISTANCE') . ': ' . _('The general ledger transaction entries could not be added because');
				$DbgMsg = _('The following SQL to insert the GL entries was used');
				$Result = DB_query($SQL, $ErrMsg, $DbgMsg, true);
	
				$SQL = "INSERT INTO gltrans (type,
											typeno,
											trandate,
											periodno,
											account,
											amount,
											narrative,
											tag)
									VALUES (98,
										'" . $WorkOrderReverseNumber . "',
										'" . $SQLAdjustmentDate . "',
										'" . $PeriodNo . "',
										'" .  $StockGLCodes['stockact'] . "',
										'" . round($Component->StandardCost * ($Component->Quantity * $_SESSION['Adjustment' . $identifier]->Quantity),$_SESSION['CompanyRecord']['decimalplaces']) . "',
										'" . $Component->StockID . ' x ' . ($Component->Quantity * $_SESSION['Adjustment' . $identifier]->Quantity) . ' @ ' . $Component->StandardCost . ' ' . $_SESSION['Adjustment' . $identifier]->Narrative . "',
										'" . $_SESSION['Adjustment' . $identifier]->tag . "'
										)";
	
				$Errmsg = _('CRITICAL ERROR') . '! ' . _('NOTE DOWN THIS ERROR AND SEEK ASSISTANCE') . ': ' . _('The general ledger transaction entries could not be added because');
				$DbgMsg = _('The following SQL to insert the GL entries was used');
				$Result = DB_query($SQL, $ErrMsg, $DbgMsg,true);
			}
		}


		// Need to get the current location quantity will need it later for the stock movement
		$SQL="SELECT locstock.quantity
			FROM locstock
			WHERE locstock.stockid='" . $_SESSION['Adjustment' . $identifier]->StockID . "'
			AND loccode= '" . $_SESSION['Adjustment' . $identifier]->StockLocation . "'";
		$Result = DB_query($SQL);
		if (DB_num_rows($Result)==1){
			$LocQtyRow = DB_fetch_row($Result);
			$QtyOnHandPrior = $LocQtyRow[0];
		} else {
			// There must actually be some error this should never happen
			$QtyOnHandPrior = 0;
		}
		$SQL = "INSERT INTO stockmoves (stockid,
										type,
										transno,
										loccode,
										trandate,
										userid,
										prd,
										reference,
										qty,
										newqoh,
										standardcost,
										narrative)
									VALUES ('" . $_SESSION['Adjustment' . $identifier]->StockID . "',
										98,
										'" . $WorkOrderReverseNumber . "',
										'" . $_SESSION['Adjustment' . $identifier]->StockLocation . "',
										'" . $SQLAdjustmentDate . "',
										'" . $_SESSION['UserID'] . "',
										'" . $PeriodNo . "',
										'" . $_SESSION['Adjustment' . $identifier]->Narrative ."',
										'" . -$_SESSION['Adjustment' . $identifier]->Quantity . "',
										'" . ($QtyOnHandPrior - $_SESSION['Adjustment' . $identifier]->Quantity) . "',
										'" . $_SESSION['Adjustment' . $identifier]->StandardCost . "',
										'')";

		$ErrMsg =  _('CRITICAL ERROR') . '! ' . _('NOTE DOWN THIS ERROR AND SEEK ASSISTANCE') . ': ' . _('The stock movement record cannot be inserted because');
		$DbgMsg =  _('The following SQL to insert the stock movement record was used');
		$Result = DB_query($SQL, $ErrMsg, $DbgMsg, true);

/*Get the ID of the StockMove... */
		$StkMoveNo = DB_Last_Insert_ID('stockmoves','stkmoveno');

		$SQL = "UPDATE locstock SET quantity = quantity - " . floatval($_SESSION['Adjustment' . $identifier]->Quantity) . "
				WHERE stockid='" . $_SESSION['Adjustment' . $identifier]->StockID . "'
				AND loccode='" . $_SESSION['Adjustment' . $identifier]->StockLocation . "'";

		$ErrMsg = _('CRITICAL ERROR') . '! ' . _('NOTE DOWN THIS ERROR AND SEEK ASSISTANCE') . ': ' ._('The location stock record could not be updated because');
		$DbgMsg = _('The following SQL to update the stock record was used');
		$Result = DB_query($SQL, $ErrMsg, $DbgMsg, true);

		if ($_SESSION['CompanyRecord']['gllink_stock']==1 AND $_SESSION['Adjustment' . $identifier]->StandardCost > 0){

			$StockGLCodes = GetStockGLCode($_SESSION['Adjustment' . $identifier]->StockID);

			$SQL = "INSERT INTO gltrans (type,
										typeno,
										trandate,
										periodno,
										account,
										amount,
										narrative,
										tag)
								VALUES (98,
									'" . $WorkOrderReverseNumber . "',
									'" . $SQLAdjustmentDate . "',
									'" . $PeriodNo . "',
									'" .  $StockGLCodes['adjglact'] . "',
									'" . round($_SESSION['Adjustment' . $identifier]->StandardCost * $_SESSION['Adjustment' . $identifier]->Quantity, $_SESSION['CompanyRecord']['decimalplaces']) . "',
									'" . $_SESSION['Adjustment' . $identifier]->StockID . " x " . $_SESSION['Adjustment' . $identifier]->Quantity . " @ " .
										$_SESSION['Adjustment' . $identifier]->StandardCost . " " . $_SESSION['Adjustment' . $identifier]->Narrative . "',
									'" . $_SESSION['Adjustment' . $identifier]->tag . "')";

			$ErrMsg = _('CRITICAL ERROR') . '! ' . _('NOTE DOWN THIS ERROR AND SEEK ASSISTANCE') . ': ' . _('The general ledger transaction entries could not be added because');
			$DbgMsg = _('The following SQL to insert the GL entries was used');
			$Result = DB_query($SQL, $ErrMsg, $DbgMsg, true);

			$SQL = "INSERT INTO gltrans (type,
										typeno,
										trandate,
										periodno,
										account,
										amount,
										narrative,
										tag)
								VALUES (98,
									'" . $WorkOrderReverseNumber . "',
									'" . $SQLAdjustmentDate . "',
									'" . $PeriodNo . "',
									'" .  $StockGLCodes['stockact'] . "',
									'" . round($_SESSION['Adjustment' . $identifier]->StandardCost * -($_SESSION['Adjustment' . $identifier]->Quantity),$_SESSION['CompanyRecord']['decimalplaces']) . "',
									'" . $_SESSION['Adjustment' . $identifier]->StockID . ' x ' . $_SESSION['Adjustment' . $identifier]->Quantity . ' @ ' . $_SESSION['Adjustment' . $identifier]->StandardCost . ' ' . $_SESSION['Adjustment' . $identifier]->Narrative . "',
									'" . $_SESSION['Adjustment' . $identifier]->tag . "'
									)";

			$Errmsg = _('CRITICAL ERROR') . '! ' . _('NOTE DOWN THIS ERROR AND SEEK ASSISTANCE') . ': ' . _('The general ledger transaction entries could not be added because');
			$DbgMsg = _('The following SQL to insert the GL entries was used');
			$Result = DB_query($SQL, $ErrMsg, $DbgMsg,true);
		}

		EnsureGLEntriesBalance(98, $WorkOrderReverseNumber);

		// check whether stock locator integration is enabled
		if($_SESSION['StockLocatorIntegrated'] == '1')
		{
			$StockLocators = array();
			$i = 0;

			// try to find the nearest rack, row, bin which has sufficient qty to fulfill the order and deduct from it
			$FoundQtyOnBin = false;
			$SQL = "SELECT quantity, rack, row, bin
					FROM stock_locators
					WHERE stockid = '".$_SESSION['Adjustment' . $identifier]->StockID."' AND loccode = '".$_SESSION['Adjustment' . $identifier]->StockLocation."' AND quantity >= '" . $_SESSION['Adjustment' . $identifier]->Quantity . "'
					ORDER BY rack, row, bin
					LIMIT 1";

			$ErrMsg =  _('Could not retrieve the quantity at the bin location because');
			$DbgMsg =  _('The SQL that failed was');
			$Result = DB_query($SQL, $ErrMsg, $DbgMsg,true);
			if(DB_num_rows($Result)==1)
			{
				$BinQtyRow = DB_fetch_row($Result);
				$QtyOnBinPrior = $BinQtyRow[0];
				$Rack = $BinQtyRow[1];
				$Row = $BinQtyRow[2];
				$Bin = $BinQtyRow[3];

				$StockLocators[$i] = array("QtyOnBinPrior" => $QtyOnBinPrior,
											"Rack" => $Rack,
											"Row" => $Row,
											"Bin" => $Bin);

				$FoundQtyOnBin = true;
			}
			else
			{
				// should there be no available single bin to fulfill the order, we have to fetch from mutltple bins
				$SQL = "SELECT quantity, rack, row, bin
						FROM stock_locators
						WHERE stockid = '".$_SESSION['Adjustment' . $identifier]->StockID."' AND loccode = '".$_SESSION['Adjustment' . $identifier]->StockLocation."' AND quantity > 0
						ORDER BY rack, row, bin";

				$ErrMsg =  _('Could not retrieve the quantity at the bin location because');
				$DbgMsg =  _('The SQL that failed was');
				$Result = DB_query($SQL, $ErrMsg, $DbgMsg,true);
				if(DB_num_rows($Result)>0)
				{
					while($myrow = DB_fetch_array($Result))
					{
						$StockLocators[$i] = array("QtyOnBinPrior" => $myrow['quantity'],
													"Rack" => $myrow['rack'],
													"Row" => $myrow['row'],
													"Bin" => $myrow['bin']);
						$i++;
					}
					$FoundQtyOnBin = true;
				}
				else
				{
					// There must actually be some error this should never happen or the location does not have warehousing data setup
					$QtyOnBinPrior = 0;
					$FoundQtyOnBin = false;
					prnMsg( _('Unable to fetch the bin quantity for item ' . $_SESSION['Adjustment' . $identifier]->StockID . ' at ' . $_SESSION['Adjustment' . $identifier]->StockLocation), 'warn');
				}
			}
			
			// proceed to update stock locators only when the bin qty is found
			if($FoundQtyOnBin)
			{
				$RemainingQtyToDispatch = $_SESSION['Adjustment' . $identifier]->Quantity;

				// loop through all the available bins and deduct the quantity untill we are able to fulfill the order
				foreach($StockLocators as $StockLocator)
				{
					if($RemainingQtyToDispatch >= $StockLocator['QtyOnBinPrior'])
					{
						$QtyDispatched = $StockLocator['QtyOnBinPrior'];
					}
					else
					{
						$QtyDispatched = $RemainingQtyToDispatch;
					}

					$RemainingQtyToDispatch -= $QtyDispatched;
					
					if($QtyDispatched > 0)
					{
						// Insert the stock movement for the stock going out of the location
						$SQL = "INSERT INTO stock_locator_moves(stockid,
																type,
																transno,
																loccode,
																rack,
																row,
																bin,
																trandate,
																userid,
																prd,
																reference,
																qty,
																newqoh)
														VALUES (
															'" . $_SESSION['Adjustment' . $identifier]->StockID . "',
															98,
															'" . $WorkOrderReverseNumber . "',
															'" . $_SESSION['Adjustment' . $identifier]->StockLocation . "',
															'" . $StockLocator['Rack'] . "',
															'" . $StockLocator['Row'] . "',
															'" . $StockLocator['Bin'] . "',
															'" . $SQLAdjustmentDate . "',
															'" . $_SESSION['UserID'] . "',
															'" . $PeriodNo . "',
															'" . $_SESSION['Adjustment' . $identifier]->Narrative ."',
															'" . -$QtyDispatched . "',
														'" . ($StockLocator['QtyOnBinPrior'] - $QtyDispatched) . "'
														)";

						$ErrMsg = _('CRITICAL ERROR') . '! ' . _('NOTE DOWN THIS ERROR AND SEEK ASSISTANCE') . ': ' . _('The stock movement record cannot be inserted because');
						$DbgMsg =  _('The following SQL to insert the stock movement record was used');
						$Result = DB_query($SQL,$ErrMsg,$DbgMsg,true);

						$SQL = "UPDATE stock_locators 
								SET quantity = (quantity - " . $QtyDispatched . ")  
								WHERE loccode = '" . $_SESSION['Adjustment' . $identifier]->StockLocation . "' AND stockid = '" . $_SESSION['Adjustment' . $identifier]->StockID . "' AND rack = '".$StockLocator['Rack']."' AND row = '".$StockLocator['Row']."' AND bin = '".$StockLocator['Bin']."'";
						$Result = DB_query($SQL,$ErrMsg,$DbgMsg,true);
					}
				}
			}
		}

		$Result = DB_Txn_Commit();
		$AdjustReason = $_SESSION['Adjustment' . $identifier]->Narrative?  _('Narrative') . ' ' . $_SESSION['Adjustment' . $identifier]->Narrative:'';
		$ConfirmationText = _('A stock adjustment for'). ' ' . $_SESSION['Adjustment' . $identifier]->StockID . ' -  ' . $_SESSION['Adjustment' . $identifier]->ItemDescription . ' '._('has been created from location').' ' . $_SESSION['Adjustment' . $identifier]->StockLocation .' '. _('for a quantity of') . ' ' . locale_number_format($_SESSION['Adjustment' . $identifier]->Quantity,$_SESSION['Adjustment' . $identifier]->DecimalPlaces) . ' ' . $AdjustReason;
		prnMsg( $ConfirmationText,'success');

		if ($_SESSION['InventoryManagerEmail']!=''){
			$ConfirmationText = $ConfirmationText . ' ' . _('by user') . ' ' . $_SESSION['UserID'] . ' ' . _('at') . ' ' . Date('Y-m-d H:i:s');
			$EmailSubject = _('Stock adjustment for'). ' ' . $_SESSION['Adjustment' . $identifier]->StockID;
			if($_SESSION['SmtpSetting']==0){
			      mail($_SESSION['InventoryManagerEmail'],$EmailSubject,$ConfirmationText);
			}else{
				include('includes/htmlMimeMail.php');
				$mail = new htmlMimeMail();
				$mail->setSubject($EmailSubject);
				$mail->setText($ConfirmationText);
				$result = SendmailBySmtp($mail,array($_SESSION['InventoryManagerEmail']));
			}

		}
		$StockID = $_SESSION['Adjustment' . $identifier]->StockID;
		unset ($_SESSION['Adjustment' . $identifier]);
		unset ($_SESSION['Component' . $identifier]);
	} /* end if there was no input error */

}/* end if the user hit enter the adjustment */


echo '<form action="'. htmlspecialchars($_SERVER['PHP_SELF'],ENT_QUOTES,'UTF-8') . '?identifier='.$identifier.'" method="post">';
echo '<div>';
echo '<input type="hidden" name="FormID" value="' . $_SESSION['FormID'] . '" />';

if (!isset($_SESSION['Adjustment' . $identifier])) {
	$StockID='';
	$Controlled= 0;
	$Quantity = 0;
	$DecimalPlaces =2;
} else {
	$StockID = $_SESSION['Adjustment' . $identifier]->StockID;
	$Controlled = $_SESSION['Adjustment' . $identifier]->Controlled;
	$Quantity = $_SESSION['Adjustment' . $identifier]->Quantity;
	$sql="SELECT materialcost,
				labourcost,
				overheadcost,
				units,
				decimalplaces
			FROM stockmaster
			WHERE stockid='".$StockID."'";

	$result=DB_query($sql);
	$myrow=DB_fetch_array($result);
	$_SESSION['Adjustment' . $identifier]->PartUnit=$myrow['units'];
	$_SESSION['Adjustment' . $identifier]->StandardCost=$myrow['materialcost']+$myrow['labourcost']+$myrow['overheadcost'];
	$DecimalPlaces = $myrow['decimalplaces'];
}
echo '<br />
	<table class="selection">
	<tr>
		<th colspan="4"><h3>' . _('Reverse Work Order Details') . '</h3></th>
	</tr>';

echo '<tr><td>' .  _('Stock Code'). ':</td><td>';

echo '<select name="StockID"><option selected value = "" hidden >Please select</option>';

$sql = "SELECT stockid
		FROM stockmaster
		WHERE mbflag = 'M' AND controlled = '0' AND serialised = '0' AND discontinued = '0'";
$result=DB_query($sql);
while($myrow=DB_fetch_array($result))
{
	if($StockID == $myrow['stockid'])
	{
		echo '<option selected value = "'.$myrow['stockid'].'">'.$myrow['stockid'].'</option>';
	}
	else
	{
		echo '<option value = "'.$myrow['stockid'].'">'.$myrow['stockid'].'</option>';
	}
}
echo '</select></td>';

echo '</td>
		<td><input type="submit" name="CheckCode" value="'._('Fetch Component List').'" /></td>
	</tr>';

if (isset($_SESSION['Adjustment' . $identifier]) AND mb_strlen($_SESSION['Adjustment' . $identifier]->ItemDescription)>1){
	echo '<tr>
			<td colspan="3"><h3>' . $_SESSION['Adjustment' . $identifier]->ItemDescription . ' ('._('In Units of').' ' . $_SESSION['Adjustment' . $identifier]->PartUnit . ' ) - ' . _('Unit Cost').' = ' . locale_number_format($_SESSION['Adjustment' . $identifier]->StandardCost,4) . '</h3></td>
		</tr>';
}

if($recipe_list != "")
{
	echo $recipe_list;
}

echo '<tr><td>'. _('Stock At Location').':</td>
		<td><select name="StockLocation" onchange="submit();"> ';
foreach ($LocationList as $Loccode=>$Locationname){
	if (isset($_SESSION['Adjustment'.$identifier]->StockLocation) AND $Loccode == $_SESSION['Adjustment' . $identifier]->StockLocation){
		 echo '<option selected="selected" value="' . $Loccode . '">' . $Locationname . '</option>';
	} else {
		 echo '<option value="' . $Loccode . '">' . $Locationname . '</option>';
	}
}

echo '</select></td></tr>';

//$Narrative = 'Reverse Work Order for ' . $_SESSION['Adjustment' . $identifier]->StockID . ' x ' . $_SESSION['Adjustment' . $identifier]->Quantity;


//echo '<input type="hidden" name="Narrative" size="32" onchange="submit()" maxlength="100" value="'.$Narrative.'" />';

echo '<tr><td>' . _('Quantity').':</td>';

echo '<td>';

echo '<input type="text" class="number" name="Quantity" size="12" maxlength="12" value="' . locale_number_format($Quantity,$DecimalPlaces) . '" />';

echo '</td></tr>';
	//Select the tag
echo '<tr>
		<td>' . _('Select Tag') . '</td>
		<td><select name="tag">';

$SQL = "SELECT tagref,
				tagdescription
		FROM tags
		ORDER BY tagref";

$result=DB_query($SQL);
echo '<option value="0">0 - ' . _('None') . '</option>';
while ($myrow=DB_fetch_array($result)){
	if (isset($_SESSION['Adjustment' . $identifier]->tag) AND $_SESSION['Adjustment' . $identifier]->tag==$myrow['tagref']){
		echo '<option selected="selected" value="' . $myrow['tagref'] . '">' . $myrow['tagref'].' - ' .$myrow['tagdescription'] . '</option>';
	} else {
		echo '<option value="' . $myrow['tagref'] . '">' . $myrow['tagref'].' - ' .$myrow['tagdescription']. '</option>';
	}
}
echo '</select></td></tr>';
// End select tag

echo '</table>
	<div class="centre">
	<br />
	<input type="submit" name="EnterAdjustment" value="'. _('Enter Work Order Reversal'). '" />
	<br />';

if (!isset($_POST['StockLocation'])) {
	$_POST['StockLocation']='';
}

echo '<br />
	<a href="'. $RootPath. '/StockStatus.php?StockID='. $StockID . '">' . _('Show Stock Status') . '</a>';
echo '<br />
	<a href="'.$RootPath.'/StockMovements.php?StockID=' . $StockID . '">' . _('Show Movements') . '</a>';
echo '<br />
	<a href="'.$RootPath.'/StockUsage.php?StockID=' . $StockID . '&amp;StockLocation=' . $_POST['StockLocation'] . '">' . _('Show Stock Usage') . '</a>';
echo '<br />
	<a href="'.$RootPath.'/SelectSalesOrder.php?SelectedStockItem='. $StockID .'&amp;StockLocation=' . $_POST['StockLocation'] . '">' .  _('Search Outstanding Sales Orders') . '</a>';
echo '<br />
	<a href="'.$RootPath.'/SelectCompletedOrder.php?SelectedStockItem=' . $StockID .'">' . _('Search Completed Sales Orders') . '</a>';

echo '</div>
      </div>
      </form>';
include('includes/footer.php');
?>
