<?php session_name('CAKEPHP'); session_start();
$PageSecurity = 2;
if (empty($_GET['identifier'])) {
			 $identifier=date('U');
		} else {
			$identifier=$_GET['identifier'];
		}
$title = _('Physical Stock Adjustment');
$_SESSION['modid']=$_REQUEST['modid'];
$_SESSION['frmid']=$_REQUEST['frmid'];
$frmpermission= $px->GetFileAccess($_SESSION['modid'],$_SESSION['frmid'],$_SESSION['ACGRoleId']);
$_SESSION['frmAdd']=$frmpermission[0];
$_SESSION['frmEdit']=$frmpermission[1];
$_SESSION['frmDelete']=$frmpermission[2];
$_SESSION['frmView']=$frmpermission[3];



$url_cancel= "index.php?route=Inventory/transation/material_receipt_note_index".$rurl;
$url_add= "index.php?route=Inventory/transation/physical_adjustment".$rurl;
$url_edit= "index.php?route=Inventory/transation/material_receipt_note_edit".$rurl;
$url_view= "index.php?route=Inventory/transation/material_receipt_note_view".$rurl;



if($_REQUEST['action']=='Cancel')
{

$AddMRN_Row= DB_fetch_array(DB_query("Select * from addmrn where id='".$_REQUEST['mrnid']."'",$db));

 $Update_Query =DB_query("update addmrn set Cancel_Status='Y' where id='".$_REQUEST['mrnid']."'",$db);

$AddMRN_Row= DB_fetch_array(DB_query("Select * from addmrn where id='".$_REQUEST['mrnid']."'",$db));

$AddMRN_Row2=DB_query("Select * from addmrn where PO_WO_MTO='".$AddMRN_Row['PO_WO_MTO']."' and Cancel_Status='N'",$db);
$AddMRN_Row1= DB_fetch_array($AddMRN_Row2);
$numdata=DB_num_rows($AddMRN_Row2);
if($numdata>0)
{
//$PO_Qty=DB_fetch_array(DB_query("Select * from purchorderdetails where orderno='".$PURCH_Row['orderno']."'",$db));
//echo "update purchorderdetails set status='Receive' where orderno='".$AddMRN_Row1['PO_WO_MTO']."'";
$Purch_Sql=DB_query("update purchorderdetails set status='Receive' where orderno='".$AddMRN_Row1['PO_WO_MTO']."'",$db);
//echo "update purchorders set Po_recive_status='Pending' where orderno='".$PURCH_Row['orderno']."'";
//echo "update purchorders set Po_recive_status='Receive' where orderno='".$PURCH_Row['PO_WO_MTO']."'";
$Purch_Sql=DB_query("update purchorders set Po_recive_status='Receive' where orderno='".$PURCH_Row['PO_WO_MTO']."'",$db);


$Purch_Sql=DB_query("update update_mrn_qty set po_qty='".$PO_Qty['quatity']."',status='1' where order_no='".$PURCH_Row['orderno']."'",$db);
}
else
{
$PURCH_Row= DB_fetch_array(DB_query("Select * from purchorders where orderno='".$AddMRN_Row['PO_WO_MTO']."'",$db));
//$PO_Qty=DB_fetch_array(DB_query("Select * from purchorderdetails where orderno='".$PURCH_Row['orderno']."'",$db));

$Purch_Sql=DB_query("update purchorderdetails set status='Pending' where orderno='".$PURCH_Row['orderno']."'",$db);
//echo "update purchorders set Po_recive_status='Pending' where orderno='".$PURCH_Row['orderno']."'";
$Purch_Sql=DB_query("update purchorders set Po_recive_status='Pending' where orderno='".$PURCH_Row['orderno']."'",$db);


$Purch_Sql=DB_query("update update_mrn_qty set po_qty='".$PO_Qty['quatity']."',status='1' where order_no='".$PURCH_Row['orderno']."'",$db);
}



}








?>
<script src="js/jsapi.js" type="text/javascript">
</script>
<script type="text/javascript">
google.load("jquery", "1"); 
</script>
<style>
#slidingDiv {
    display: none;
	height:100px;
	background-color: #D9D6DA;
	padding:20px;
}
</style>
<?php
	$type="paging";
	$rowsPerPage = 10;
	$pageNum = 1;
	if(isset($_GET['page']))
	{
		$pageNum = $_GET['page'];
	}
	$offset = ($pageNum - 1) * $rowsPerPage;

if (isset($_GET['SelectedStockItem'])){
	$SelectedStockItem=trim($_GET['SelectedStockItem']);
} elseif (isset($_POST['SelectedStockItem'])){
	$SelectedStockItem=trim($_POST['SelectedStockItem']);
}

if (isset($_GET['RequisitionNumber'])){
	$RequisitionNumber=trim($_GET['RequisitionNumber']);
} elseif (isset($_POST['RequisitionNumber'])){
	$RequisitionNumber=trim($_POST['RequisitionNumber']);
}


if (isset($_GET['SelectedSupplier'])){
	$SelectedSupplier=trim($_GET['SelectedSupplier']);
} elseif (isset($_POST['SelectedSupplier'])){
	$SelectedSupplier=trim($_POST['SelectedSupplier']);
}


echo '<form action="' . $_SERVER['PHP_SELF'] . '?' . 'route=Inventory/transation/material_receipt_note_index&modid='.$_REQUEST['modid'].'&frmid=' .$_REQUEST['frmid'].'" method=post>';

if (isset($_POST['ResetPart'])){
     unset($SelectedStockItem);
}

if (isset($RequisitionNumber) && $RequisitionNumber!='') 
{
	if (!is_numeric($RequisitionNumber)){
		  echo '<br><b>' . _('The Requisition Number entered') . ' <U>' . _('MUST') . '</U> ' . _('be numeric') . '.</b><br>';
		  unset ($RequisitionNumber);
	} else {
		echo _('Requisition Number') . ' - ' . $RequisitionNumber;
}
} else {
	if (isset($SelectedSupplier)) {
		echo '<br><div class="page_help_text">' . _('For supplier') . ': ' . $SelectedSupplier . ' ' . _('and') . ' ';
		echo '<input type=hidden name="SelectedSupplier" value="' . $SelectedSupplier . '"></div>';
	}
	if (isset($SelectedStockItem)) {
		 echo '<input type=hidden name="SelectedStockItem" value="' . $SelectedStockItem . '">';
	}
}

if (isset($_GET['orderno']) && isset($_GET['orderno'])!='' && isset($_GET['DeleteOnly']) ==1 && isset($_GET['mrnid']) !='')
 {
 	
$sql = 'Delete From addmrn Where id='.$_GET['mrnid'].'';
$Delresult = DB_query($sql,$db);
$Delsql = 'Delete From addmrnqty Where issue_id ='.$_GET['mrnid'].'';
$issuedelresult = DB_query($Delsql,$db);
$chargedelete="delete from mrn_charges where MRN_id='".$_GET['mrnid']."'";
$charge_res=DB_query($chargedelete,$db);

$poqty_sql="Delete from po_quantity where orderno='".$_GET['orderno']."' ";
$poqty_res=DB_query($poqty_sql,$db);

echo $url_cancel;
prnMsg(_('MaterialReceiptNote Number') . '  ' . $_GET['mrnid'] . ' ' . _('has been Deleted') ,'success');
}

if ($_SESSION['UserStockLocation'] == $_SESSION['UserStockLocation'])
  {
	if (!isset($RequisitionNumber) or $RequisitionNumber==''){
	
		
?>		
<h2 align="center"><strong>Physical Stock Adjustment</strong></h2>
<br>
<?php if($_SESSION['frmAdd']=='1'){?>

		<a href="<?php echo $url_add;?>">Add New</a><?php }?>

<div id="container">
<script type="text/javascript">
function showSlidingDiv(){
$("#slidingDiv").animate({"height": "toggle"}, { duration: 700 });
}
</script>


<!--<br />
<div align="center"><a href="#" onClick="showSlidingDiv(); return false;">SEARCH</a></div>
<br />-->
<div id="slidingDiv" class="centre" >
<table width="50%" border="0" cellspacing="1" cellpadding="2" align="center">
  <tr>
	<th width="40%"><strong>Site</strong></th>
    <td width="10%"> <select name="site"> 
    <option  value="000">Select Site</option>
	<?php 
		$sql = "SELECT loccode, locationname FROM locations";
		$resultStkLocs = DB_query($sql,$db);
		while ($myrow=DB_fetch_array($resultStkLocs)){
 				echo '<option Value="' . $myrow['loccode'] . '">' . $myrow['locationname'].'</option>';
 		}
       }

	?> </select></td>
	<th width="40%"><strong>MRN Number</strong></th>
    <td width="10%"><input type="text" name="MRnumber" MAXLENGTH="30" size="10" /></td></tr>
    <tr>
    <th scope="col"><strong>Vendor</strong></th>	
    <td>
		<select name="vendor" id="vendor">
		<option value="000">---Select---</option>-->
		<?php 
		$vendor_sql=DB_query("Select id,vendor_code,vendor_name from suppliers",$db);
		while($vendor_res=DB_fetch_array($vendor_sql))
		{?>
		<option value="<?php echo $vendor_res['id'];?>"><?php echo $vendor_res['vendor_code'];?></option>
		<?php } ?>
		</select>
	</td>
	<th scope="col"><strong>Vendor Name</strong></th>
	<td><select name="vendor_name" id="vendor_name">
		<option value="000">---Select---</option>-->
		<?php 
	$vendor_sql=DB_query("Select id,vendor_code,vendor_name from suppliers",$db);
		while($vendor_res=DB_fetch_array($vendor_sql))
		{?>
		
		<option value="<?php echo $vendor_res['id'];?>"><?php echo $vendor_res['vendor_name'];?></option>
		<?php } ?>
		</select></td>
  
    </tr>	
	<tr>
	<th><strong>From Date</strong></th>
	<td><input type="text" name="fromdate" class="datepicker"  size="12" /></td>
	<th><strong>To Date</strong></th>
	<td><input type="text" name="todate" class="datepicker"  size="12"  /></td>
	</tr>
  </table>
  <br />
  <table width="30%" border="0" cellspacing="1" cellpadding="2" align="center">
<!--  <tr>
    <th scope="col"><strong>Vendor</strong></th>
    <th scope="col"><strong>Client</strong></th>
</tr>-->
  <!--<tr>
    <td>
		<select name="vendor" id="vendor">
		<option value="000">---Select Vendor---</option>-->
		<?php 
		//$vendor_sql=DB_query("Select vendor_code,vendor_name from suppliers",$db);
		//while($vendor_res=DB_fetch_array($vendor_sql))
		//{?>
		<!--<option value="<?php echo $vendor_res['vendor_code'];?>"><?php echo $vendor_res['vendor_name'];?></option>-->
		<?php //} ?>
		<!--</select>
	</td>
    
    <td><select name="client" id="client">
		<option value="000">---Select Client---</option>-->
		<?php 
		//$client_sql=DB_query("Select client_code,c_name from clientmaster",$db);
		//while($client_res=DB_fetch_array($client_sql))
		//{?>
		<!--<option value="<?php echo $client_res['client_code'];?>"><?php echo $client_res['c_name'];?></option>-->
		<?php //} ?>
		<!--</select></td>
  </tr>-->
</table>
  <p align="center"><input name="Search" type="submit" value="Search" /></p>
</div>
	<br /><br />
	<br />
	<?php
	if($site='0')
	{
		$SQL="select * from addmrn";
	}
	if(isset($_POST['Search']))
	{
		
	  
		$SQL="select * from addmrn";
        $MRnumber=$_REQUEST['MRnumber'];
		$site=$_REQUEST['site'];
		$vendor=$_REQUEST['vendor'];
		$vendor_name=$_REQUEST['vendor_name'];
		$fromdate=ConvertSQLDate($_POST['fromdate']);
	    $todate=ConvertSQLDate($_POST['todate']); 
	    $filter=array();
		if($fromdate!='//' ||$todate!='//')
		{
			 $filter[]="MRNDate BETWEEN '".$fromdate."' AND '".$todate."'";
		}
		if($site!='000')
		{
			$filter[]="site='".$site."'";
		}
		if($MRnumber!='')
		{
			$filter[]="MRNNo like '%".$MRnumber."'";
		}
		if($vendor!='000')
		{
			$filter[]="ReceivedFrom='".$vendor."'";
		}
		if($vendor_name!='000')
		{
			$filter[]="ReceivedFrom='".$vendor_name."'";
		}
		
		if(isset($filter))
		{
		 if(count($filter)>0)
		
			{
			$SQL=$SQL." where ".implode(" and ",$filter);
		
			}
		else
			{
				$filter1="1=1";
	        }
			
		}
	}
		
/*if(isset($_POST['Search']))
{
 
	$filter=array();
	$MRnumber=$_POST['MRnumber'];
	$StockLocation=$_POST['StockLocation'];
	$fromdate=ConvertSQLDate($_POST['fromdate']);
	$todate=ConvertSQLDate($_POST['todate']); 
	
	if($MRnumber!='')
	{
	   $filter[]="MRNNo  like '%".$MRnumber."'";
	}
	
	if($StockLocation!='0')
	{
	   $filter[]="OrderFromSite   ='".$StockLocation."'";
	}
	
	if($fromdate!='//' ||$todate!='//')
	{
	   $filter[]="MRNDate BETWEEN '".$fromdate."' AND '".$todate."'";
	}
	
	if($_POST['vendor']!='000')
	{
		$filter[]="ReceivedFrom='".$_POST['vendor']."'";
	}
	if($_POST['pc']!='000')
	{
		$filter[]="ReceivedFrom   ='".$_POST['pc']."'";
	}
	if($_POST['client']!='000')
	{
		$filter[]="ReceivedFrom   ='".$_POST['client']."'";
	}
	
	if( isset($filter))
	{
 			if(count($filter)>0)
			{
	  		$filter1=implode("and",$filter);
			}else{
			$filter1="1=1";
			}
 			 $SQL = "Select * from addmrn
			 		 Where $filter1 ORDER BY MRNNo ASC";
 			 $resultpaging_SQL = "Select MRNNo, MRNDate, OrderFromSite, StoreName, ReceivedAgainst, createdby from addmrn
			 		 			  Where $filter1 ORDER BY MRNNo ASC ";
 	}*/
		
else 
{   
  $SQL = "SELECT a.site ,a.store , ad.itemname ,ad.uom, ad.adjustment_qty ,ad.adjustment_type ,ad.remarks  FROM 

`physical_stock_adj_details` AS ad , `physical_stock_adjustment` AS a WHERE a.id=ad.physical_stock_id";
// $resultpaging_SQL = "Select MRNNo, MRNDate, OrderFromSite, StoreName, ReceivedAgainst, createdby from addmrn
					 // Where 1=1 ORDER BY MRNNo ASC ";
		   }


        $ErrMsg = _('No orders were returned by the SQL because');
		$purchordersResult = DB_query($SQL,$db,$ErrMsg);
		$resultpaging = DB_query($SQL, $db, $ErrMsg);
		/*show a table of the orders returned by the SQL */
	?>
		<table border="1" cellpadding="3" cellspacing="0" WIDTH="100%">
		<tr>
		
		
		<th><strong>S.No</strong></th>
		<th><strong>Site</strong></th>
		<th><strong>Store</strong></th>

		<th><strong>Item name</strong></th>
		<th><strong>UOM</strong></th>
		<th><strong>Adjustment Qty</strong></th>
		<th><strong>Adjustment Type</strong></th>
		<th><strong>Remarks</strong></th>
		 
		</tr>
		<?php 
		$j = 1;$i=1;
		$k=0;
		if(DB_num_rows($purchordersResult)>0){
		
			$rpp = 10; // results per page
			$adjacents = 5;
			
			$page = intval($_GET["page"]);
			if($page<=0) $page = 1;
			
			$reload ="index.php?route=Inventory/transation/physical_adjustment_index".$rurl;
			
			
			// select appropriate results from DB:
			
			
			//$sql = "SELECT * FROM sub_preparation";
			$result =$purchordersResult;
			
			// count total number of appropriate listings:
			$tcount = DB_num_rows($result);
			
			// count number of pages:
			$tpages = ($tcount) ? ceil($tcount/$rpp) : 1; // total pages, last page number
			
			$count = 0;
			$i = ($page-1)*$rpp;
			while(($count<$rpp) && ($i<$tcount)) {
				DB_data_seek($result,$i);
				$query = DB_fetch_array($result);
			 
				@extract($query);
		
		
		if($Cancel_Status!='Y')
		{
		
		
		
			if ($k==1){/*alternate bgcolour of row for highlighting */ ?>
				<tr class="EvenTableRows">
			<?php	$k=0;
			} else {?>
				<tr class="OddTableRows">
		<?php 		$k++;
			}
			$ModifyPage = $rootpath . "/MR_Header.php?" . SID . "&ModifyRequisitionNumber=" . $requisitionno;
			if ($status==_('Printed')) {
				$ReceiveOrder = "<a href='".$rootpath . "/GoodsReceived.php?" . SID . "&MRNumber=" . $requisitionno."'>".
					_('Create Purchase Order').'</a>';
			} 
	        else {
				//$ReceiveOrder = "Create Purchase Order";$url_edit
				
				$modification = '<a href="index.php?route=Inventory/transation/material_receipt_note_edit&modid='.$_REQUEST['modid'].'&frmid='.$_REQUEST['frmid'].'&ModfingOnly=1&mrnid='.$id.'">' . "<img src='images/icon-edit.png' height='15' width='15'>". '</a>';
				$view = '<a href="index.php?route=Inventory/transation/material_receipt_note_view&modid='.$_REQUEST['modid'].'&frmid='.$_REQUEST['frmid'].'&ViewingOnly=1&mrnid='.$id.'">' . "<img src='images/search.gif' height='15' width='15'>". '</a>';
				$delete = '<a href="' . $rootpath . 'Inventory/transation/material_receipt_note_index.php?' . SID . '&orderno=' . $order_no.'&DeleteOnly=1&mrnid='.$id.'" onclick="return confirm("Are You Sure You Want To Delete This Record?")">' . "<img src='images/icon-edit.png' height='15' width='15'>". '</a>';
			}
			if ($allowprint==1){
				$PrintPurchOrder = '<a target="_blank" href="' . $rootpath . '/MR_PDFMaterialRequisition.php?' . SID . '&RequisitionNo=' . $requisitionno. ' ">' . _('Print Now') . '</a>';
			} else {
			}
			if ($status==_('Authorised')) {
				$PrintPurchOrder = '<a target="_blank" href="' . $rootpath . '/MR_PDFMaterialRequisition.php?' . SID . '&RequisitionNo=' . $requisitionno. '&realorderno=' . $realorderno. '&ViewingOnly=2">' . _('Print') . '</a>';
			} else {
				$PrintPurchOrder = 'Print';
			}
			$site_query=DB_query("Select locationname from locations where loccode='".$site."'",$db);
			$site_row=DB_fetch_array($site_query);
		?>
			<tr bgcolor="#FFFFFF">
			<td> <?php  echo $j;?></td>
			<td><?php echo $query['site'] ;?></td>
			<td><?php echo $query['store'];?></td>
			<td><?php echo $query['itemname'];?></td>
			<td><?php  echo $query['uom'];?></td>
			<td><?php  echo $query['adjustment_qty'];?></td>
			<td width="4%"><?php echo $query['adjustment_type']; ?></td>
			<td width="4%"><?php echo $query['remarks'];?></td> 
			</tr>
			<?php 
			$j++;
			If ($j == 12){
				$j=1;
				 echo $TableHeader;
			}
		//end of page full new headings if
		}
		$i++;  $count++;		}
		echo paginate_two($reload, $page, $tpages, $adjacents);
		}
		else
		{?>
		<tr>
		<td colspan="10"><h2 align="center"><strong><font color="#FF0000">No Record Found!</font></strong></h2></td>
		</tr>	
		<?php }
		//end of while loop ?>
		</table>
	<input type="hidden" name="ReqNo" value="<?php echo $_POST['ShowRequisition'];?>">
	<?php 
	echo "<script>defaultControl(document.forms[0].StockCode);</script>"; ?>
	</form>
<?php 
}
else 
{
		echo '<form action="' . $_SERVER['PHP_SELF'] . '?' . SID . '" method=post>';
			
		if (isset($_POST['ResetPart'])){
			 unset($SelectedStockItem);
		}
		
		if (isset($RequisitionNumber) && $RequisitionNumber!='') {
			if (!is_numeric($RequisitionNumber)){
				  echo '<br><b>' . _('The Requisition Number entered') . ' <U>' . _('MUST') . '</U> ' . _('be numeric') . '.</b><br>';
				  unset ($RequisitionNumber);
			} else {
				echo _('Requisition Number') . ' - ' . $RequisitionNumber;
			}
		} else {
			if (isset($SelectedSupplier)) {
				echo '<br><div class="page_help_text">' . _('For supplier') . ': ' . $SelectedSupplier . ' ' . _('and') . ' ';
				echo '<input type=hidden name="SelectedSupplier" value="' . $SelectedSupplier . '"></div>';
			}
			if (isset($SelectedStockItem)) {
				 echo '<input type=hidden name="SelectedStockItem" value="' . $SelectedStockItem . '">';
			}
		}
		
		if (isset($_POST['SearchParts'])) {
			$completed='purchorderdetails.completed=0';
		
			
			if ($_POST['Keywords']) {
				//insert wildcard characters in spaces
		//	$completed = "purchorderdetails.completed=0 AND ";
				$i=0;
				$SearchString = '%';
				while (strpos($_POST['Keywords'], ' ', $i)) {
					$wrdlen=strpos($_POST['Keywords'],' ',$i) - $i;
					$SearchString=$SearchString . substr($_POST['Keywords'],$i,$wrdlen) . '%';
					$i=strpos($_POST['Keywords'],' ',$i) +1;
				}
				$SearchString = $SearchString. substr($_POST['Keywords'],$i).'%';
		
				$SQL = "SELECT stockmaster.stockid, 
						stockmaster.description, 
						SUM(locstock.quantity) AS qoh,  
						stockmaster.units, 
						SUM(purchorderdetails.quantityord-purchorderdetails.quantityrecd) AS qord 
					FROM stockmaster INNER JOIN locstock 
						ON stockmaster.stockid = locstock.stockid 
						INNER JOIN purchorderdetails 
							ON stockmaster.stockid=purchorderdetails.itemcode 
					WHERE $completed
					stockmaster.description " . LIKE . " '$SearchString' 
					AND stockmaster.categoryid='" . $_POST['StockCat'] . "' 
					GROUP BY stockmaster.stockid, 
						stockmaster.description, 
						stockmaster.units 
					ORDER BY stockmaster.stockid";
					
					
			 } elseif ($_POST['StockCode']){
				$SQL = "SELECT stockmaster.stockid, 
						stockmaster.description, 
						SUM(locstock.quantity) AS qoh, 
						SUM(purchorderdetails.quantityord-purchorderdetails.quantityrecd) AS qord, 
						stockmaster.units 
					FROM stockmaster INNER JOIN locstock 
						ON stockmaster.stockid = locstock.stockid 
						INNER JOIN purchorderdetails 
							ON stockmaster.stockid=purchorderdetails.itemcode 
					WHERE $completed
					AND stockmaster.stockid " . LIKE . " '%" . $_POST['StockCode'] . "%' 
					AND stockmaster.categoryid='" . $_POST['StockCat'] . "' 
					GROUP BY stockmaster.stockid, 
						stockmaster.description, 
						stockmaster.units 
					ORDER BY stockmaster.stockid";
					
			 } elseif (!$_POST['StockCode'] AND !$_POST['Keywords']) {
				$SQL = "SELECT stockmaster.stockid, 
						stockmaster.description, 
						SUM(locstock.quantity) AS qoh, 
						stockmaster.units, 
						SUM(purchorderdetails.quantityord-purchorderdetails.quantityrecd) AS qord 
					FROM stockmaster INNER JOIN locstock 
						ON stockmaster.stockid = locstock.stockid 
						INNER JOIN purchorderdetails 
							ON stockmaster.stockid=purchorderdetails.itemcode 
					WHERE $completed 
					AND stockmaster.categoryid='" . $_POST['StockCat'] . "' 
					GROUP BY stockmaster.stockid, 
						stockmaster.description, 
						stockmaster.units 
					ORDER BY stockmaster.stockid";
			 }
		
			$ErrMsg = _('No stock items were returned by the SQL because');
			$DbgMsg = _('The SQL used to retrieve the searched parts was');
			$StockItemsResult = DB_query($SQL,$db, $ErrMsg, $DbgMsg);
		}
	
		
			echo '<div class="centre">'._('Puchase Requisition number') . ': <input type=text name="RequisitionNumber" MAXLENGTH =8 size=9>  ' . _('Into Site') . ':<select name="StockLocation"> ';
			$sql = 'SELECT locationname FROM locations WHERE loccode='."'$_SESSION[UserStockLocation]'".';';
			$resultStkLocs = DB_query($sql,$db);
			while ($myrow=DB_fetch_array($resultStkLocs)){
		if (isset($_POST['StockLocation'])){
			if ($myrow['loccode'] == $_POST['StockLocation']){
				echo '<option selected Value="' . $myrow['loccode'] . '">' . $myrow['locationname'];
			} else {
				echo '<option Value="' . $myrow['loccode'] . '">' . $myrow['locationname'];
			}
		} elseif ($myrow['loccode']== $_SESSION['UserStockLocation']){
			echo '<option selected Value="' . $myrow['loccode'] . '">' . $myrow['locationname'];
		} else {
			echo '<option Value="' . $myrow['loccode'] . '">' . $myrow['locationname'];
		}
	}
		echo '</select>  <input type=submit name="SearchOrders" VALUE="' . _('Search Puchase Requisition') . '"></div>';
				
	$SQL='SELECT categoryid, categorydescription FROM stockcategory ORDER BY categorydescription';
	$result1 = DB_query($SQL,$db);
	
	?>
<hr />
<br>
	<br>
	<?php
	
	if (isset($StockItemsResult)) {
	
		echo '<table cellpadding=2 colspan=7 BORDER=2>';
		$TableHeader = 	'<tr><th>' . _('Code') . '</th>
				<th>' . _('Description') . '</th>
				<th>' . _('On Hand') . '</th>
				<th>' . _('Orders') . '<br>' . _('Outstanding') . '</th>
				<th>' . _('Units') . '</th>
				</tr>';
		echo $TableHeader;
		$j = 1;
		$k=0; //row colour counter
	
		while ($myrow=DB_fetch_array($StockItemsResult)) {
	
			if ($k==1){
				echo '<tr class="EvenTableRows">';
				$k=0;
			} else {
				echo '<tr class="OddTableRows">';
				$k=1;
			}
	
			printf("<td><input type=submit name='SelectedStockItem' VALUE='%s'</td>
					<td>%s</td>
				<td align=right>%s</td>
				<td align=right>%s</td>
				<td>%s</td></tr>",
				$myrow['stockid'],
				$myrow['description'],
				$myrow['qoh'],
				$myrow['qord'],
				$myrow['units']);
	
			$j++;
			If ($j == 12){
				$j=1;
				echo $TableHeader;
			}
	//end of page full new headings if
		}
	//end of while loop
	
		echo '</table>';
	
	}	
	//end if stock search results to show
	else 
	{
		//figure out the SQL required from the inputs available
	$completed = " AND purchorderdetails.completed=0";
		if (isset($RequisitionNumber) && $RequisitionNumber !='') 
		{
				$SQL = 'SELECT * FROM addmrn';
		} 
		else if (isset($SelectedSupplier)) 
		{
				if (!isset($_POST['StockLocation'])) 
				{
					$_POST['StockLocation']='';
				}
				
				if (isset($SelectedStockItem)) 
				{
				$SQL = 'SELECT * FROM addmrn';
				} else 
				{
					$SQL = 'SELECT * FROM addmrn';
				}
			} 
			else 
			{ //no supplier selected
				if (!isset($_POST['StockLocation'])) {$_POST['StockLocation']='';
				}
				if (isset($SelectedStockItem) and isset($_POST['StockLocation'])) {
					$SQL = 'SELECT * FROM addmrn';
				} 
				else 
				{
				$SQL = 'SELECT * FROM addmrn';
				}
			} //end selected supplier
		} //end not order number selected
		$ErrMsg = _('No orders were returned by the SQL because');
		$PurchOrdersResult = DB_query($SQL,$db,$ErrMsg);
	
		/*show a table of the orders returned by the SQL */
	
		echo '<table cellpadding=2 colspan=7 WIDTH=100%>';
	
	//	               '</td><td class="tableheader">' . _('Receive') .	
		$TableHeader = '<tr><th>' . _('Site Name') .
		        '</th><th>' . _('Purchase Req. No.') .
				'</th><th>' . _('Purchase Req. Date') .
				'</th><th>' . _('Purchase At') .
				'</th><th>' . _('Created by') .
				'</th><th>' . _('Create Vendor Quotation') .
				'</th><th>' . _('Create Comperitive Quotation') .
		'</th></tr>';
	
		echo $TableHeader;
		$j = 1;
		$k=0; //row colour counter
		while ($myrow=DB_fetch_array($PurchOrdersResult)) {
		
		
		
	
	
			if ($k==1){ /*alternate bgcolour of row for highlighting */
				echo '<tr class="EvenTableRows">';
				$k=0;
			} else {
				echo '<tr class="OddTableRows">';
				$k++;
			}
	
			$ModifyPage = $rootpath . "/MR_Header.php?" . SID . "&ModifyRequisitionNumber=" . $myrow["requisitionno"];
			if ($myrow['status']==_('Printed')) {
				$ReceiveOrder = "<a href='".$rootpath . "/GoodsReceived.php?" . SID . "&MRNumber=" . $myrow["requisitionno"]."'>".
					_('Create Purchase Order').'</a>';
			} else {
				//$ReceiveOrder = "Create Purchase Order";
				$ReceiveOrder = "<a href='".$rootpath . "/PO_Header.php?" . SID . "&MRNumber=" . $myrow["requisitionno"]."&sitename=" . $myrow["requisition_site"]."&purchaseat=" . $myrow["intostocklocation"]."&reqdate=" . $myrow["prdate"]."&status=" . $myrow["status"]."&identifier=" .$identifier."'>".
					_('Create Purchase Order').'</a>';
			}
			if ($myrow["allowprint"]==1){
				$PrintPurchOrder = '<a target="_blank" href="' . $rootpath . '/MR_PDFMaterialRequisition.php?' . SID . '&RequisitionNumber=' . $myrow['requisitionno'] . '">' . _('Print Now') . '</a>';
			} else {
	// not open yet
	//			$PrintPurchOrder = '<font color=GREY>' . _('Printed') . '</font>';
	
			}
			if ($myrow['status']==_('Authorised')) {
				$PrintPurchOrder = '<a target="_blank" href="' . $rootpath . '/PO_PDFPurchOrder.php?' . SID . '&OrderNo=' . $myrow['orderno'] . '&realorderno=' . $myrow['realorderno'] . '&ViewingOnly=2">' . _('Print') . '</a>';
			} else {
				$PrintPurchOrder = 'Print';
			}
			$PrintPurchOrder2 = '<a target="_blank" href="' . $rootpath . '/PO_PDFPurchOrder.php?' . SID . '&OrderNo=' . $myrow['orderno'] . '&realorderno=' . $myrow['realorderno'] . '&ViewingOnly=1">' . _('Show') . '</a>';
			$s2 = '<a target="_blank" href="' . $rootpath . '/PO_PDFPurchOrder.php?' . SID . '&OrderNo=' . $myrow['orderno'] . '&realorderno=' . $myrow['realorderno'] . '&ViewingOnly=1">' . $myrow['realorderno']. '</a>';
	
			$FormatedOrderDate = ConvertSQLDate($myrow['orddate']);
			$FormatedOrderValue = number_format($myrow['ordervalue'],2);
	        $VenderQuotation = '<a href="' . $rootpath . '/VenderQutations.php?' . SID . '&RequisitionNo=' . $myrow['requisitionno'] . '&ViewingOnly=1">' . "Create Vendor Quotation". '</a>';
			$ComperitiveQuotation = '<a href="' . $rootpath . '/Comperitive.php?' . SID . '&RequisitionNo=' . $myrow['requisitionno'] . '&ViewingOnly=1">' . "Create Comperitive Quotation". '</a>';
			$RequisitionNo=$myrow["requisitionno"];
	// the tailed two column
	//			<td>%s</font></td>
	//			<td align=right>%s</font></td>
	//			$myrow['requisitionno'],	
	//			$myrow['initiator']);
	//			'</td><td class="tableheader">' . _('Requisition') .
	//			'</td><td class="tableheader">' . _('Initiator') .	               		
	//		        <td><a href='%s'>" . _('Receive') . "</a></td>			
			printf("<td><input type=submit name='ShowRequisition' value='%s'></td>
				<td>%s</td>
				<td>%s</td>
				<td>%s</td>
				<td>%s</font></td>
				<td>%s</font></td>
				<td>%s</font></td>
				</tr>",
				$RequisitionNo,						
				ConvertSQLDate($myrow['req_date']),
				$myrow['requisition_site'],	
				$myrow['intostocklocation'],		
				$myrow['initiator'],			
				$VenderQuotation,
				$ComperitiveQuotation
				);
	
			$j++;
			If ($j == 12){
				$j=1;
				 echo $TableHeader;
			}
		//end of page full new headings if
		}
		//end of while loop
	
							
	}
	
					/*$rows = DB_num_rows($resultpaging);

					$maxPage = ceil($rows/$rowsPerPage);
					$self = $_SERVER['PHP_SELF'];
					$nav  = '';
				     for($page = 1; $page <= $maxPage; $page++)
				     {
					if ($page == $pageNum)
					{
						$nav .= " $page "; 
					}
					else
					{
					   $nav .= " <a href=\"$self?page=$page\" class=\"gllink\">$page</a> ";
					} 
				}
				if ($pageNum > 1)
				{
					$page  = $pageNum - 1;
					echo $first = " <a href=\"$self?page=1\" class=\"gllink\">[First Page]</a> ";
					echo $prev  = " <a href=\"$self?page=$page\" class=\"gllink\">[Prev]</a> ";
				} 
				else
				{
				  echo $prev  = "&nbsp;"; 
				  echo $first = "&nbsp;";
				}
				if ($pageNum < $maxPage)
				{
					$page = $pageNum + 1;
					echo $next = " <a href=\"$self?page=$page\" class=\"gllink\">[Next]</a>";
					echo $last = " <a href=\"$self?page=$maxPage\" class=\"gllink\">[Last Page]</a>";
				} 
				else
				{
				   echo $next = "&nbsp;";
				   echo $last = "&nbsp;"; 
				}*/
		
	echo '<input type="hidden" name="ReqNo" value="'.$_POST['ShowRequisition'].'">';
	echo "<script>defaultControl(document.forms[0].StockCode);</script>";
	echo '</table>';
	echo '</form>';
  
include('includes/footer.inc');
?>
<link rel="stylesheet" href="css/jquery.ui.all.css" />
<script src="js/jquery-1.5.1.js"></script>
<script src="ui/jquery.ui.core.js"></script>
<script src="ui/jquery.ui.widget.js"></script>



<script>
$(function() {
$(".datepicker").datepicker({ dateFormat: 'dd/mm/yy' ,changeMonth: true,
		changeYear: true,
		yearRange: '-80:+20'});
});
</script>

<?php




if(isset($_SESSION['success_msg']))
{ ?>
	<script> alert("<?php echo ($_SESSION['success_msg']);?>");</script>
<?php 
}
unset($_SESSION['success_msg']);
?>