<?php

include('includes/session.php');

if ($_SESSION['StockLocatorIntegrated'] == '0')
{
    $Title = _('Warehouse Stock Integration Not Enabled');
	include('includes/header.php');
	echo '<p class="page_title_text"><img alt="" src="', $RootPath, '/css/', $Theme,
		'/images/error.png" title="', // Icon image.
		$Title, '" /> ', // Icon title.
		$Title, '</p>';// Page title.
	echo '<br />';
	prnMsg(_('The system is not configured for warehouse stock integration. A configuration parameter is required for warehouse stock integration. Please consult your system administrator.'), 'info');
	include('includes/footer.php');
	exit;
}

$Title=_('Stock Placement Management');
include('includes/header.php');
echo '<p class="page_title_text"><img src="'.$RootPath.'/css/'.$Theme.'/images/inventory.png" title="' . _('Inventory') . '" alt="" />' . ' ' . _('Stock Placement Management') . '</p>';
echo '<div class="page_help_text">' . _('Rack is the physical holder of many row and bins inside a warehouse.<br>Row is the level inside the rack.<br>Bin is the finest physical location.') . '</div><br />';


if(isset($_GET['remove']) && $_GET['remove']==$_SESSION['FormID'])
{
	if(isset($_GET['loccode']) && $_GET['loccode'] != '' &&
		isset($_GET['rack']) && $_GET['rack'] != '' &&
		isset($_GET['row']) && $_GET['row'] != '' &&
		isset($_GET['bin']) && $_GET['bin'] != '')
	{
		// check for any stock movement records
		$sql = "SELECT stock_locators.quantity, stock_locator_moves.stkmoveno
				FROM stock_locators
				LEFT JOIN stock_locator_moves
				ON stock_locators.loccode = stock_locator_moves.loccode
					AND stock_locators.rack = stock_locator_moves.rack
					AND stock_locators.row = stock_locator_moves.row
					AND stock_locators.bin = stock_locator_moves.bin
				WHERE stock_locators.loccode = '".$_GET['loccode']."' 
				AND stock_locators.rack = '".$_GET['rack'] ."' 
				AND stock_locators.row = '".$_GET['row'] ."' 
				AND stock_locators.bin = '".$_GET['bin'] ."'
				LIMIT 1";
		$result = DB_query($sql);
		while($myrow=DB_fetch_array($result))
		{
			if($myrow['quantity']==0 && $myrow['stkmoveno'] == '')
			{
				// delete from table if no movement recorded
				$SQL = "DELETE FROM stock_locators WHERE loccode='".$_GET['loccode']."' AND rack='".$_GET['rack']."' AND row='".$_GET['row']."' AND bin='".$_GET['bin']."'";
				$ErrMsg =  _('Could not update the inventory placement because');
				$DbgMsg =  _('The SQL that failed was');
				$Result = DB_query($SQL, $ErrMsg, $DbgMsg);
				if($Result)
				{
					prnMsg('An inventory placement at location ' . $_GET['loccode']. ' ['.$_GET['rack'].'-'.$_GET['row'].'-'.$_GET['bin'].'] has been removed', 'success');
				}
				else
				{
					prnMsg('Failed to remove inventory placement at location ' . $_GET['loccode']. ' ['.$_GET['rack'].'-'.$_GET['row'].'-'.$_GET['bin'].']', 'error');
				}
			}
			else if($myrow['quantity']==0)
			{
				// de-activate location from table if prior movement recorded
				$SQL = "UPDATE stock_locators SET active = 0, stockid = NULL WHERE quantity <= 0 AND loccode='".$_GET['loccode']."' AND rack='".$_GET['rack']."' AND row='".$_GET['row']."' AND bin='".$_GET['bin']."'";
				$ErrMsg =  _('Could not update the inventory placement because');
				$DbgMsg =  _('The SQL that failed was');
				$Result = DB_query($SQL, $ErrMsg, $DbgMsg);
				if($Result)
				{
					prnMsg('An inventory placement at location ' . $_GET['loccode']. ' ['.$_GET['rack'].'-'.$_GET['row'].'-'.$_GET['bin'].'] has been removed', 'success');
				}
				else
				{
					prnMsg('Failed to remove inventory placement at location ' . $_GET['loccode']. ' ['.$_GET['rack'].'-'.$_GET['row'].'-'.$_GET['bin'].']', 'error');
				}
			}
			else
			{
				// This should never happen!
				prnMsg('Failed to remove inventory placement at location ' . $_GET['loccode']. ' ['.$_GET['rack'].'-'.$_GET['row'].'-'.$_GET['bin'].']', 'error');
			}
		}
	}
}
else if(isset($_POST['Create']))
{
	if($_POST['StockLocation'] && $_POST['Rack'] != '' && $_POST['Row'] != '' && $_POST['Bin'] != '')
	{
		// check if location exist
		$sql = "SELECT stockid, active FROM stock_locators WHERE loccode='".$_POST['StockLocation']."' AND rack='".$_POST['Rack']."' AND row='".$_POST['Row']."' AND bin='".$_POST['Bin']."'";

		$result = DB_query($sql);
		if(DB_num_rows($result) == 1)
		{
			$myrow = DB_fetch_array($result);

			if($myrow['active'] == 0)
			{
				// if previously defined, set it back to active
				$SQL = "UPDATE stock_locators SET active = 1 WHERE loccode='".$_POST['StockLocation']."' AND rack='".$_POST['Rack']."' AND row='".$_POST['Row']."' AND bin='".$_POST['Bin']."'";
				$ErrMsg =  _('Could not update the inventory placement because');
				$DbgMsg =  _('The SQL that failed was');
				$Result = DB_query($SQL, $ErrMsg, $DbgMsg);
				if($Result)
				{
					prnMsg('An inventory placement at location ' . $_POST['StockLocation']. ' ['.$_POST['Rack'].'-'.$_POST['Row'].'-'.$_POST['Bin'].'] has been activated successfully', 'success');
				}
				else
				{
					prnMsg('Failed to activate inventory placement for location ' . $_POST['StockLocation']. ' ['.$_POST['Rack'].'-'.$_POST['Row'].'-'.$_POST['Bin'].']', 'error');
				}
			}
			else
			{
				prnMsg('Inventory placement for location ' . $_POST['StockLocation']. ' ['.$_POST['Rack'].'-'.$_POST['Row'].'-'.$_POST['Bin'].'] already exist', 'error');
			}
		}
		else
		{
			if($_POST['StockID'] == '')
			{
				$StockID = "NULL";
			}
			else
			{
				$StockID = "'".$_POST['StockID']."'";
			}

			// no prior records found and we can add to stock locator
			$SQL = "INSERT INTO stock_locators (loccode, rack, row, bin, stockid)
					VALUES ('".$_POST['StockLocation']."', '".$_POST['Rack']."', '".$_POST['Row']."', '".$_POST['Bin']."', $StockID)";
			$ErrMsg =  _('Could not update the inventory placement because');
			$DbgMsg =  _('The SQL that failed was');
			$Result = DB_query($SQL, $ErrMsg, $DbgMsg);
			if($Result)
			{
				prnMsg('An inventory placement at location ' . $_POST['StockLocation']. ' ['.$_POST['Rack'].'-'.$_POST['Row'].'-'.$_POST['Bin'].'] has been created successfully', 'success');
			}
			else
			{
				prnMsg('Failed to create inventory placement for location ' . $_POST['StockLocation']. ' ['.$_POST['Rack'].'-'.$_POST['Row'].'-'.$_POST['Bin'].']', 'error');
			}
		}
	}
	else
	{
		prnMsg('Stock placement info must be filled in and cannot be empty', 'error');
	}
}

echo '<br />
	<form action="' . htmlspecialchars($_SERVER['PHP_SELF'],ENT_QUOTES,'UTF-8') . '" method="post">
	<div>
	<input type="hidden" name="FormID" value="' . $_SESSION['FormID'] . '" />
	<table class="selection">
	<tr>
		<td>' . _('Location').':</td>
		<td><select name="StockLocation">';

    $sql = "SELECT locations.loccode, locationname FROM locations INNER JOIN locationusers ON locationusers.loccode=locations.loccode AND locationusers.userid='" .  $_SESSION['UserID'] . "' AND locationusers.canview=1";
    $resultStkLocs = DB_query($sql);
    while($myrow=DB_fetch_array($resultStkLocs)) {
        if($myrow['loccode']==$_SESSION['UserStockLocation']) {
            echo '<option selected="selected" value="' . $myrow['loccode'] . '">' . $myrow['locationname'] . '</option>';
        } else {
            echo '<option value="' . $myrow['loccode'] . '">' . $myrow['locationname'] . '</option>';
        }
    }
	echo '</select>
			</td>
		</tr>
		<tr>
			<td>' .  _('Rack'). ':</td>
			<td><input type="text" name="Rack" size="21" value="" maxlength="20" /></td>
		</tr>
		<tr>
			<td>' .  _('Row'). ':</td>
			<td><input type="text" name="Row" size="21" value="" maxlength="20" /></td>
		</tr>
		<tr>
			<td>' .  _('Bin'). ':</td>
			<td><input type="text" name="Bin" size="21" value="" maxlength="20" /></td>
		</tr>
		<tr>
			<td>' .  _('Stock Code'). ':</td>
			<td><input type="text" name="StockID" size="21" value="" maxlength="20" /></td>
		</tr>
		<tr>
			<td></td>
			<td>
				<input type="submit" name="Search" value="Search" />
				<input type="submit" name="Create" value="Create Placement" />
			</td>
		</tr>
	</table>';

if(isset($_POST['Search'])) {

	$search_critirea = "";

	if($_POST['Rack'] != '')
	{
		$search_critirea .= " AND rack " . LIKE . " '%" . $_POST['Rack']."%'";
	}
	if($_POST['Row'] != '')
	{
		$search_critirea .= " AND row " . LIKE . " '%" . $_POST['Row']."%'";
	}
	if($_POST['Bin'] != '')
	{
		$search_critirea .= " AND bin " . LIKE . " '%" . $_POST['Bin']."%'";
	}
	if($_POST['StockID'] != '')
	{
		$search_critirea .= " AND stockid " . LIKE . " '%" . $_POST['StockID']."%'";
	}

	$sql = "SELECT rack, row, bin, stockid, quantity FROM stock_locators WHERE active = 1 AND loccode = '".$_POST['StockLocation']."'". $search_critirea ." ORDER BY stockid, rack, row, bin";
	$ErrMsg=_('The stock information cannot be retrieved because');
    $DbgMsg=_('The SQL to get the stock description was');
    $result = DB_query($sql,$ErrMsg,$DbgMsg);
	
	if(DB_num_rows($result) > 0) {
		echo '<table class="selection">
			<thead>
				<tr>
					<th class="ascending">' . _('Stock Code') . '</th>
					<th class="ascending">' . _('Rack') . '</th>
					<th class="ascending">' . _('Row') . '</th>
					<th class="ascending">' . _('Bin') . '</th>
					<th class="ascending">' . _('Qty') . '</th>
					<th>' . _('Action') . '</th>
				</tr>
			</thead>
			<tbody>';

		while($myrow = DB_fetch_array($result))
		{
			if($prev_stockid != $myrow['stockid'])
			{
				if($prev_stockid != '' && $total_quantity_at_location != 0)
				{
					echo '<tr class="striped_row">
						<td>' . $prev_stockid . '</td>
						<td> - </td>
						<td> - </td>
						<td> - </td>
						<td>' . $total_quantity_at_location . '</td>
						<td></td>
					</tr>';
				}

				$sql = "SELECT quantity FROM locstock WHERE loccode = '".$_POST['StockLocation']."' AND stockid = '".$myrow['stockid']."'";
				$result_total = DB_query($sql);
				if(DB_num_rows($result_total) == 1) {
					$total_quantity_at_location = 0;
					while($row=DB_fetch_array($result_total)) {
						$total_quantity_at_location = $row['quantity'];
					}
				}
				$prev_stockid = $myrow['stockid'];
			}

			echo '<tr class="striped_row">
					<td>' . $myrow['stockid'] . '</td>
					<td>' . $myrow['rack'] . '</td>
					<td>' . $myrow['row'] . '</td>
					<td>' . $myrow['bin'] . '</td>
					<td>' . $myrow['quantity'] . '</td>
					<td>' . ($myrow['quantity'] > 0 ? '' : '<a href="'. htmlspecialchars($_SERVER['PHP_SELF'],ENT_QUOTES,'UTF-8').'?remove='.$_SESSION['FormID'].'&loccode='.$_POST['StockLocation'].'&rack='.$myrow['rack'].'&row='.$myrow['row'].'&bin='.$myrow['bin'].'" onclick="return confirm(\'Are you sure?\')">Remove</a>') . '</td>
				</tr>';

			$total_quantity_at_location -= $myrow['quantity'];
		}

		if($prev_stockid != '' && $total_quantity_at_location != 0)
		{
			echo '<tr class="striped_row">
					<td>' . $prev_stockid . '</td>
					<td> - </td>
					<td> - </td>
					<td> - </td>
					<td>' . $total_quantity_at_location . '</td>
					<td></td>
				</tr>';
		}

		echo '</tbody></table>';
	}
}

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