<?php ob_start();
$PageSecurity = 4;
include('includes/DefinePOClass.php');
if (isset($_GET['ModifyOrderNumber'])) {
	$title = _('Modify Purchase Order') . ' ' . $_GET['ModifyOrderNumber'];
} else {
	$title = _('Purchase Order Entry');
}
/*If the page is called is called without an identifier being set then
 * it must be either a new order, or the start of a modification of an
 * order, and so we must create a new identifier.
 * 
 * The identifier only needs to be unique for this php session, so a 
 * unix timestamp will be sufficient.
 */

 if (empty($_GET['identifier'])) {
	$identifier=date('U');
} else {
	$identifier=$_GET['identifier'];
}
/*Page is called with NewOrder=Yes when a new order is to be entered
 * the session variable that holds all the PO data $_SESSION['PO'][$identifier] 
 * is unset to allow all new details to be created */
	$compnum = $_REQUEST['comprativeno'];
	$compdate = $_REQUEST['comprative_date'];
	$ModifyOrderNumber=$_GET['ModifyOrderNumber'];
	$final_Quot         = $_REQUEST['final_Quot'];
	$sitecode           = $_REQUEST['sitecode'];
	$sitename           = $_REQUEST['sitename'];
	$suppid             = $_REQUEST['vendercode'];
	$vendername         = $_REQUEST['vendername'];
	$RequisitionNo      = $_REQUEST['reqno'];
	$Total_Amount       = $_REQUEST['Total_Amount'];
	$Total_Tax          = $_REQUEST['Total_Tax'];
	$Total_Charge       = $_REQUEST['Total_Charge'];
	$Grand_Total        = $_REQUEST['Grand_Total'];
	$comprative_date    = $_REQUEST['comprative_date'];
///////////////////////////////////////////////////// Only Save Record ////////////////////////////////////////////////////////////////////
if(isset($_POST['Save']))
	{
	$comprativeno  = $_REQUEST['comprativeno'];
    $com_Sql = "Select * from  comprative_detail Where comprative_no ='".$comprativeno."'";
	$com_result = DB_query($com_Sql,$db);
	$noofpow =DB_num_rows($com_result);
	if($noofpow ==0)
		{	
		$comprativeno  = $_REQUEST['comprativeno'];
		$final_Quot        = $_REQUEST['final_Quot'];
		$sitecode          = $_REQUEST['sitecode'];
		$sitename          = $_REQUEST['sitename'];
		$suppid            = $_REQUEST['vendercode'];
		$vendername        = $_REQUEST['vendername'];
		$RequisitionNo     = $_REQUEST['reqno'];
		$Total_Amount      = $_REQUEST['Total_Amount'];
		$Total_Tax         = $_REQUEST['Total_Tax'];
		$Total_Charge      = $_REQUEST['Total_Charge'];
		$Grand_Total       = $_REQUEST['Grand_Total'];   
	    $comprative_date   = $_REQUEST['comprative_date'];
    	$comprative_SQL = "INSERT INTO comprative_detail(`comprative_id`, `comprative_no`, `vendor_id`, `vendoe_name`, `Vendor_Quot_No`, `RequisitionNo`, `sitecode`, `Status`, `Total_ Amount`, `Total_Tax`, `Total_Charge`, `Grand_Total`, `Comprative_date`) 
     Value('', '".$comprativeno."', '".$suppid."', '".$vendername."', '".$final_Quot."', '".$RequisitionNo."', '".$sitecode."', 'No', '".$Total_Amount."', '".$Total_Tax."', '".$Total_Charge ."', '".$Grand_Total."', '".ConvertSQLDate($comprative_date)."')";
  $Comprative_result=DB_query($comprative_SQL,$db);
	  if($Comprative_result ==true)
	  {
	   header('Location: Comperitive_listing.php?NewOrder=Yes');
	  }	 
 }
	}
///////////////////////////////////////// Save Record With Make Po Order//////////////////////////////////
	if(isset($_REQUEST['FinalQuot']))
	{
	$comprativeno  = $_REQUEST['comprativeno'];
 $com_Sql = "Select * from  comprative_detail Where comprative_no ='".$comprativeno."' and CompanyId='".$_SESSION['ACGCompanyId']."'";

	$com_result = DB_query($com_Sql,$db);
	$noofpow =DB_num_rows($com_result);
		if($noofpow ==0)
		{
			
			 $final_Quot         = $_REQUEST['final_Quot'];
			 $sitecode           = $_REQUEST['sitecode'];
			 $sitename           = $_REQUEST['sitename'];
			 $suppid             = $_REQUEST['vendercode'];
			 $vendername         = $_REQUEST['vendername'];
			 $RequisitionNo      = $_REQUEST['reqno'];
			 $Total_Amount       = $_REQUEST['Total_Amount'];
			 $Total_Tax          = $_REQUEST['Total_Tax'];
			 $Total_Charge       = $_REQUEST['Total_Charge'];
			 $Grand_Total        = $_REQUEST['Grand_Total'];
			 $comprative_date    = $_REQUEST['comprative_date'];
			
		$comprative_SQL = "INSERT INTO comprative_detail set 
											`comprative_id`='', 
											`comprative_no`='".$comprativeno."',  
											`Vendor_Quot_No`='".$final_Quot."',  
											`RequisitionNo`='".$RequisitionNo."',
											`sitecode`='".$sitecode."',
											`Status`='Yes', 
											CompanyId='".$_SESSION['ACGCompanyId']."',
											 `Comprative_date`='".ConvertSQLDate($comprative_date)."', 
											`status_active`='0' ";
											
			//echo "<pre>";
			//print_r($comprative_SQL);
			//exit;
		  	$Comprative_result=DB_query($comprative_SQL,$db);
			$_SESSION['lastcomprative_id']=DB_Last_Insert_ID($db,'comprative_detail','comprative_id');
		}
	}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  	$sql="SELECT intostocklocation FROM materialrequisitions WHERE requisitionno='".$RequisitionNo."'";
	$result=DB_query($sql,$db);
	$myrow=DB_fetch_array($result);
	$purchaseat=$myrow['intostocklocation'];
	
$sql1 = "SELECT Reqno FROM materialrequisitions WHERE requisitionno='".$RequisitionNo."' and CompanyId='".$_SESSION['ACGCompanyId']."'";

	$ReqResult= DB_query($sql1,$db);
	$result1 = DB_fetch_array($ReqResult);
	$Reqno = $result1['Reqno'];

	
	/*$sql6 = "SELECT comprative_no FROM comprative_detail WHERE RequisitionNo='".$RequisitionNo."'";
	$ReqResult6 = DB_query($sql6,$db);
	$result6 = DB_fetch_array($ReqResult6);
	$comprative_no = $result6['comprative_no'];*/
	
	
	$sql3 = "SELECT prdate FROM materialrequisitions WHERE requisitionno='".$RequisitionNo."' and CompanyId='".$_SESSION['ACGCompanyId']."'";

	$PRResult= DB_query($sql3,$db);
	$result3 = DB_fetch_array($PRResult);
	$prdate = $result3['prdate'];
	
	$sql4="SELECT vernder_quotation FROM venderquotations WHERE id='".$final_Quot."' and CompanyId='".$_SESSION['ACGCompanyId']."' ";
	
	$result4=DB_query($sql4,$db);
	$myrow4=DB_fetch_array($result4);
	$vernder_quotation =$myrow4['vernder_quotation'];
	
  $sql5="SELECT date1 FROM venderquotations WHERE id='".$final_Quot."' and CompanyId='".$_SESSION['ACGCompanyId']."'";

	$result5=DB_query($sql5,$db);
	$myrow5=DB_fetch_array($result5);
	$date1 =$myrow5['date1'];
	
$sql2="SELECT * FROM purchorders WHERE orderno='".$ModifyOrderNumber."'";

	$result2=DB_query($sql2,$db);
	$myrow2=DB_fetch_array($result2);
	$comments=$myrow2['comments'];
	$PO_Orderno=$myrow2['PO_Orderno'];
	
if (isset($_GET['NewOrder']) and isset($_SESSION['PO'.$identifier])){
	unset($_SESSION['PO'.$identifier]);
	$_SESSION['ExistingOrder']=0;
}

if (isset($_POST['Select']) and empty($_POST['SupplierContact'])) {
	$sql = "SELECT contact 
			FROM suppliercontacts 
			WHERE supplierid='". $_POST['Select'] ."'";

	$SuppCoResult = DB_query($sql,$db);
	if (DB_num_rows($SuppCoResult)>0) {
		$myrow = DB_fetch_row($SuppCoResult);
		$_POST['SupplierContact'] = $myrow[0];
	} else {	
		$_POST['SupplierContact']='';
	}
}

if (isset($_POST['UpdateStat']) AND $_POST['UpdateStat']!='') { 
	/*The cancel button on the header screen - to delete order */
	$OK_to_updstat = 1;	
	$OldStatus=$_SESSION['PO'.$identifier]->Stat;
	$NewStatus=$_POST['Stat'];
	$emailsql='SELECT email FROM www_users WHERE userid="'.$_SESSION[UserID].'"';
	$emailresult=DB_query($emailsql, $db);
	$emailrow=DB_fetch_array($emailresult);
	$date = date($_SESSION['DefaultDateFormat']);
	
	
	if ($OldStatus!=$NewStatus) {
	/* assume this in the first instance */
		$authsql='SELECT authlevel 
			FROM purchorderauth 
			WHERE userid="'. $_SESSION['UserID'] .'"';
		$authresult=DB_query($authsql,$db);
		$myrow=DB_fetch_array($authresult);
		$AuthorityLevel=$myrow['authlevel'];
		$OrderTotal=$_SESSION['PO'.$identifier]->Order_Value();
		if ($_POST['StatComments']!='') {
			$_POST['StatComments']=' - '.$_POST['StatComments'];
		}

		if ($NewStatus==_('Authorised')) {
			if ($AuthorityLevel>$OrderTotal) {
				$StatusComment=$date.' - Authorised by <a href="mailto:'.$emailrow['email'].'">'.$_SESSION['UserID'].
					'</a>'.$_POST['StatComments'].'<br>'.$_POST['statcommentscomplete'];
				$_SESSION['PO'.$identifier]->StatComments=$StatusComment;
				$_SESSION['PO'.$identifier]->Stat=$NewStatus;
				$SQL = "UPDATE purchorders SET Current_Status='" . $_POST['Stat']. "', stat_comment1='" . $StatusComment ."'	WHERE purchorders.orderno =" . $_REQUEST['ModifyOrderNumber'];
				prnMsg('The order has been updated and Status  '. $_POST['Stat'],'success');
				$ErrMsg = _('The order status could not be updated because');
				$Result=DB_query($SQL,$db,$ErrMsg);
				
			} else {
				$OK_to_updstat=0;
				prnMsg( _('You do not have permission to authorise this purchase order').'.<br>'. _('This order is for').' '.
					$_SESSION['PO'.$identifier]->CurrCode.' '.$OrderTotal.'. '.
					_('You can only authorise up to').' '.$_SESSION['PO'.$identifier]->CurrCode.' '.$AuthorityLevel.'.<br>'.
					_('If you think this is a mistake please contact the systems administrator') , 'warn');
			}
		}

		if ($NewStatus==_('Cancelled') and $OK_to_updstat==1) {
			if ($AuthorityLevel>$OrderTotal or $_SESSION['UserID']==$_SESSION['PO'.$identifier]->Initiator ) {
				$StatusComment=$date.' - Cancelled by <a href="mailto:'.$emailrow['email'].'">'.$_SESSION['UserID'].
					'</a>'.$_POST['StatComments'].'<br>'.$_POST['statcommentscomplete'];
				$_SESSION['PO'.$identifier]->StatComments=$StatusComment;
				$_SESSION['PO'.$identifier]->Stat=$NewStatus;
				echo  $SQL = "UPDATE purchorders SET Current_Status='" . $_POST['Stat']. "', stat_comment1='" . $StatusComment ."'	WHERE purchorders.orderno =" . $_REQUEST['ModifyOrderNumber'];
				prnMsg('The order has been updated and Status  '. $_POST['Stat'],'success');
				$ErrMsg = _('The order status could not be updated because');
				$Result=DB_query($SQL,$db,prnMsg);		
			} else {
				$OK_to_updstat=0;
				prnMsg( _('You do not have permission to cancel this purchase order').'.<br>'. _('This order is for').' '.
					$_SESSION['PO'.$identifier]->CurrCode.' '.$OrderTotal.'. '.
					_('Your authorisation limit is set at').' '.$_SESSION['PO'.$identifier]->CurrCode.' '.$AuthorityLevel.'.<br>'.
					_('If you think this is a mistake please contact the systems administrator') , 'warn');
			}
		}

		if ($NewStatus==_('Rejected') and $OK_to_updstat==1) {
			if ($AuthorityLevel>$OrderTotal) {
				$StatusComment=$date.' - Rejected by <a href="mailto:'.$emailrow['email'].'">'.$_SESSION['UserID'].
					'</a>'.$_POST['StatComments'].'<br>'.$_POST['statcommentscomplete'];
					
				$_SESSION['PO'.$identifier]->StatComments=$StatusComment;
				$_SESSION['PO'.$identifier]->Stat=$NewStatus;
				 $SQL = "UPDATE purchorders SET Current_Status='" . $_POST['Stat']. "',	stat_comment1='" . $StatusComment ."'	WHERE purchorders.orderno =" . $_REQUEST['ModifyOrderNumber'];
				prnMsg('The order has been updated and Status  '. $_POST['Stat'],'success');
				$ErrMsg = _('The order status could not be updated because');
				$Result=DB_query($SQL,$db,$ErrMsg);
			} else {
				$OK_to_updstat=0;
				prnMsg( _('You do not have permission to reject this purchase order').'.<br>'. _('This order is for').' '.
					$_SESSION['PO'.$identifier]->CurrCode.' '.$OrderTotal.'. '.
					_('Your authorisation limit is set at').' '.$_SESSION['PO'.$identifier]->CurrCode.' '.$AuthorityLevel.'.<br>'.
					_('If you think this is a mistake please contact the systems administrator') , 'warn');
			}
		}

		if ($NewStatus==_('Pending') and $OK_to_updstat==1) {
			if ($AuthorityLevel>$OrderTotal or $_SESSION['UserID']==$_SESSION['PO'.$identifier]->Initiator ) {
				$StatusComment=$date.' - Returned to Pending status by <a href="mailto:'.$emailrow['email'].'">'.$_SESSION['UserID'].
					'</a>'.$_POST['StatComments'].'<br>'.$_POST['statcommentscomplete'];
				
				$_SESSION['PO'.$identifier]->StatComments=$StatusComment;
				$_SESSION['PO'.$identifier]->Stat=$NewStatus;
				 $SQL = "UPDATE purchorders SET Current_Status='" . $_POST['Stat']. "', stat_comment1='" . $StatusComment ."'	WHERE purchorders.orderno =" . $_REQUEST['ModifyOrderNumber'];
				prnMsg('The order has been updated and Status  '. $_POST['Stat'],'success');
				$ErrMsg = _('The order status could not be updated because');
				$Result=DB_query($SQL,$db,$ErrMsg);
				} else {
				$OK_to_updstat=0;
				prnMsg( _('You do not have permission to change the status of this purchase order').'.<br>'. _('This order is for').' '.
					$_SESSION['PO'.$identifier]->CurrCode.' '.$OrderTotal.'. '.
					_('Your authorisation limit is set at').' '.$_SESSION['PO'.$identifier]->CurrCode.' '.$AuthorityLevel.'.<br>'.
					_('If you think this is a mistake please contact the systems administrator') , 'warn');
			}
		}
		
		if ($OK_to_updstat==1){
//			unset($_SESSION['PO'.$identifier]->LineItems);
//			unset($_SESSION['PO'.$identifier]);
//			$_SESSION['PO'.$identifier] = new PurchOrder;
//			$_SESSION['RequireSupplierSelection'] = 1;




			/*if($_SESSION['ExistingOrder']!=0){
				echo $SQL = "UPDATE purchorders SET 
				status='" . $_POST['Stat']. "',
				stat_comment='" . $StatusComment ."'
				WHERE purchorders.orderno =" . $_SESSION['ExistingOrder'];

				$ErrMsg = _('The order status could not be updated because');
				$DelResult=DB_query($SQL,$db,$ErrMsg);

//				$SQL = 'DELETE FROM purchorders WHERE purchorders.orderno=' . $_SESSION['ExistingOrder'];
//				$ErrMsg = _('The order header could not be deleted because');
//				$DelResult=DB_query($SQL,$db,$ErrMsg);
			} else {
				// Re-Direct to right place
				prnMsg( _('This is a new order. It must be created before you can change the status'), 'warn');
			}*/
		}
	}
}

/**
* 2008-08-19 ToPu at WAT
* add extra functionality:
* enter a purchase order with the item's stockid and maintained
* suppliers (in purchdata) form the screen "Search Inventory Items"
* of SelectProduct.php
*/
if (isset($_GET['NewOrder']) and isset($_GET['StockID']) and isset($_GET['SelectedSupplier'])) {
		/*
		* initialize a new order
		*/
		$_SESSION['ExistingOrder']=0;
		unset($_SESSION['PO'.$identifier]);
		/* initialize new class object */
		$_SESSION['PO'.$identifier] = new PurchOrder;
		/**
		* and fill it with essential data
		*/
		$_SESSION['PO'.$identifier]->AllowPrintPO = 1; /* Of course cos the
		* order aint even started !!*/
		$_SESSION['PO'.$identifier]->GLLink = $_SESSION['CompanyRecord']['gllink_stock'];
		/* set the SupplierID we got */
		$_SESSION['PO'.$identifier]->SupplierID = $_GET['SelectedSupplier'];
		/**/
		$_SESSION['RequireSupplierSelection'] = 0;
		/**/
		$_POST['Select'] = $_GET['SelectedSupplier'];

		/**
		* the item (its item code) that should be purchased
		*/
		$purch_item = $_GET['StockID'];

}

if (isset($_POST['EnterLines'])){
/*User hit the button to enter line items -
 *  ensure session variables updated then meta refresh to PO_Items.php*/
	  $suppierid = $_POST['suppierid'];
	 $final_quatation = $_POST['final_qtation'];	
	$_SESSION['PO'.$identifier]->Location=$_POST['StkLocation'];
	$_SESSION['PO'.$identifier]->SupplierContact=$_POST['SupplierContact'];
	$_SESSION['PO'.$identifier]->DelAdd1 = $_POST['DelAdd1'];
	$_SESSION['PO'.$identifier]->DelAdd2 = $_POST['DelAdd2'];
	$_SESSION['PO'.$identifier]->DelAdd3 = $_POST['DelAdd3'];
	$_SESSION['PO'.$identifier]->DelAdd4 = $_POST['DelAdd4'];
	$_SESSION['PO'.$identifier]->DelAdd5 = $_POST['DelAdd5'];
	$_SESSION['PO'.$identifier]->DelAdd6 = $_POST['DelAdd6'];
	$_SESSION['PO'.$identifier]->Initiator = $_POST['Initiator'];
	$_SESSION['PO'.$identifier]->RequisitionNo = $_POST['Requisition'];
	$_SESSION['PO'.$identifier]->version = $_POST['version'];
	$_SESSION['PO'.$identifier]->deliverydate = $_POST['deliverydate'];
	$_SESSION['PO'.$identifier]->revised = $_POST['revised'];
	$_SESSION['PO'.$identifier]->ExRate = $_POST['ExRate'];
	$_SESSION['PO'.$identifier]->Comments = $_POST['Comments'];
	$_SESSION['PO'.$identifier]->deliveryby = $_POST['deliveryby'];
	$_SESSION['PO'.$identifier]->StatusMessage = $_POST['StatComments'];
	$_SESSION['PO'.$identifier]->paymentterms1 = $_POST['PaymentTerms'];
	$_SESSION['PO'.$identifier]->port = $_POST['port'];
	$_SESSION['PO'.$identifier]->supptel = $_POST['supptel'];
	$_SESSION['PO'.$identifier]->Contact = $_POST['Contact'];

	/*
	  $sql_payment = 'insert  into purchorders set payment_terms = '.$_SESSION['PO'.$identifier]->payment_terms; 
					
	$ErrMsg = _('An error occurred updating the purchase order to allow reprints') . '. ' . _('The error says');
	$insertResult = DB_query($sql_payment,$db,$ErrMsg); */
	
	if (isset($_POST['RePrint']) and $_POST['RePrint']==1){

		$_SESSION['PO'.$identifier]->AllowPrintPO=1;

		$sql = 'UPDATE purchorders
			SET purchorders.allowprint=1
			WHERE purchorders.orderno=' . $_SESSION['PO'.$identifier]->OrderNo;

		$ErrMsg = _('An error occurred updating the purchase order to allow reprints') . '. ' . _('The error says');
		$updateResult = DB_query($sql,$db,$ErrMsg);
	}
	
	
	//header("Location:index.php?route=PO_Items&identifier=".$identifier."&suppid=".$suppierid. "&final_quat=".$final_quatation."&sitecode=".$_POST['Stkcode']."&sitename=".$_POST['StkLocation']."&requisiton=".$_POST['Requi']."&modid=".$_REQUEST['modid']."&frmid=".$_REQUEST['frmid']."");
	
	echo "<script>location.href='index.php?route=PO_Items&identifier=".$identifier."&suppid=".$suppierid. "&final_quat=".$final_quatation."&sitecode=".$_POST['Stkcode']."&sitename=".$_POST['StkLocation']."&requisiton=".$_POST['Requi']."&modid=".$_REQUEST['modid']."&frmid=".$_REQUEST['frmid']."'</script>";
	echo '<p>';
	prnMsg(_('You should automatically be forwarded to the entry of the purchase order line items page') . '. ' . 
		_('If this does not happen') . ' (' . _('if the browser does not support META Refresh') . ') ' . 
		"<a href='$rootpath/PO_Items.php?" . SID . "'>" . _('click here') . '</a> ' . _('to continue'),'info');
} /* end of if isset _POST'EnterLines' */
/*update isset_Post'EnterLines' /////// */       
if (isset($_POST['EnterLinesEdit'])){
/*User hit the button to enter line items -
 *  ensure session variables updated then meta refresh to PO_Items.php*/
	 $suppierid 			= $_POST['suppierid'];
	 $final_quatation 		= $_POST['final_qtation'];
	 $ModifyOrderNumber		=$_POST['ModifyOrderNumber'];
	$_SESSION['PO'.$identifier]->Location=$_POST['StkLocation'];
	$_SESSION['PO'.$identifier]->SupplierContact=$_POST['SupplierContact'];
	$_SESSION['PO'.$identifier]->DelAdd1 = $_POST['DelAdd1'];
	$_SESSION['PO'.$identifier]->DelAdd2 = $_POST['DelAdd2'];
	$_SESSION['PO'.$identifier]->DelAdd3 = $_POST['DelAdd3'];
	$_SESSION['PO'.$identifier]->DelAdd4 = $_POST['DelAdd4'];
	$_SESSION['PO'.$identifier]->DelAdd5 = $_POST['DelAdd5'];
	$_SESSION['PO'.$identifier]->DelAdd6 = $_POST['DelAdd6'];
	$_SESSION['PO'.$identifier]->Initiator = $_POST['Initiator'];
	$_SESSION['PO'.$identifier]->RequisitionNo = $_POST['Requisition'];
	$_SESSION['PO'.$identifier]->version = $_POST['version'];
	$_SESSION['PO'.$identifier]->deliverydate = $_POST['deliverydate'];
	$_SESSION['PO'.$identifier]->revised = $_POST['revised'];
	$_SESSION['PO'.$identifier]->ExRate = $_POST['ExRate'];
	$_SESSION['PO'.$identifier]->Comments = $_POST['Comments'];
	$_SESSION['PO'.$identifier]->deliveryby = $_POST['deliveryby'];
	$_SESSION['PO'.$identifier]->StatusMessage = $_POST['StatComments'];
	$_SESSION['PO'.$identifier]->payment_terms = $_POST['PaymentTerms'];
	$_SESSION['PO'.$identifier]->port = $_POST['port'];
	$_SESSION['PO'.$identifier]->supptel = $_POST['supptel'];
	$_SESSION['PO'.$identifier]->Contact = $_POST['Contact'];
	
	/*
	  $sql_payment = 'insert  into purchorders set payment_terms = '.$_SESSION['PO'.$identifier]->payment_terms; 
					
	$ErrMsg = _('An error occurred updating the purchase order to allow reprints') . '. ' . _('The error says');
	$insertResult = DB_query($sql_payment,$db,$ErrMsg); */
	
	if (isset($_POST['RePrint']) and $_POST['RePrint']==1){

		$_SESSION['PO'.$identifier]->AllowPrintPO=1;

		$sql = 'UPDATE purchorders
			SET purchorders.allowprint=1
			WHERE purchorders.orderno=' . $_SESSION['PO'.$identifier]->OrderNo;

		$ErrMsg = _('An error occurred updating the purchase order to allow reprints') . '. ' . _('The error says');
		$updateResult = DB_query($sql,$db,$ErrMsg);
	}
	
	//echo '<meta http-equiv="Refresh content=0; url=' . $rootpath . '/PO_Items.php?' . SID . 'identifier='.$identifier.'&suppid='. $suppid.' ">';
	header("Location: ".$rootpath."/PO_Items_update.php?identifier=".$identifier."&suppid=".$suppierid. "&ModifyOrderNumbe=".$ModifyOrderNumber."&final_quat=".$final_quatation);
	echo '<p>';
	prnMsg(_('You should automatically be forwarded to the entry of the purchase order line items page') . '. ' . 
		_('If this does not happen') . ' (' . _('if the browser does not support META Refresh') . ') ' . 
		"<a href='$rootpath/PO_Items.php?" . SID . "'>" . _('click here') . '</a> ' . _('to continue'),'info');
}


/*The page can be called with ModifyOrderNumber=x where x is a purchase
 * order number. The page then looks up the details of order x and allows 
 * these details to be modified */

/*if (isset($_GET['ModifyOrderNumber'])){
	include ('includes/PO_ReadInOrder.inc');
}*/

if (isset($_POST['CancelOrder']) AND $_POST['CancelOrder']!='') { 
/*The cancel button on the header screen - to delete order */



	$OK_to_delete = 1;	 //assume this in the first instance

	if(!isset($_SESSION['ExistingOrder']) OR $_SESSION['ExistingOrder']!=0) { 
		/* need to check that not already dispatched or invoiced 
		 * by the supplier */

		if($_SESSION['PO'.$identifier]->Any_Already_Received()==1){
			$OK_to_delete =0;
			prnMsg( _('This order cannot be cancelled because some of it has already been received') . '. ' . 
				_('The line item quantities may be modified to quantities more than already received') . '. ' . 
				_('Prices cannot be altered for lines that have already been received') .' '. 
				_('and quantities cannot be reduced below the quantity already received'),'warn');
		}

	}

	if ($OK_to_delete==1){
		$emailsql='SELECT email FROM www_users WHERE userid="'.$_SESSION['PO'.$identifier]->Initiator.'"';
		$emailresult=DB_query($emailsql, $db);
		$emailrow=DB_fetch_array($emailresult);
		$StatusComment=date($_SESSION['DefaultDateFormat']).
			' - Order Cancelled by <a href="mailto:'.$emailrow['email'].'">'.$_SESSION['UserID'].'</a><br>'.$_POST['statcommentscomplete'];
		unset($_SESSION['PO'.$identifier]->LineItems);
		unset($_SESSION['PO'.$identifier]);
		$_SESSION['PO'.$identifier] = new PurchOrder;
		$_SESSION['RequireSupplierSelection'] = 1;

  
		if($_SESSION['ExistingOrder']!=0){
			
			echo $sql = 'UPDATE purchorderdetails 
				SET completed=1
				WHERE purchorderdetails.orderno =' . $_SESSION['ExistingOrder'];
			$ErrMsg = _('The order detail lines could not be deleted because');
			$DelResult=DB_query($sql,$db,$ErrMsg);

			echo $sql="UPDATE purchorders 
				SET status='Cancelled',
				stat_comment='".$StatusComment."'
				WHERE orderno=".$_SESSION['ExistingOrder'];
			
			$ErrMsg = _('The order header could not be deleted because');
			$DelResult=DB_query($sql,$db,$ErrMsg);
			prnMsg( _('Order number').' '.$_SESSION['ExistingOrder'].' '._('has been cancelled'), 'success');
			unset($_SESSION['PO'.$identifier]);
			unset($_SESSION['ExistingOrder']);
		} else {
		// Re-Direct to right place
			unset($_SESSION['PO'.$identifier]);
			prnMsg( _('The creation of the new order has been cancelled'), 'success');
		}
	}
}

if (!isset($_SESSION['PO'.$identifier])){
	/* It must be a new order being created 
	 * $_SESSION['PO'.$identifier] would be set up from the order modification
	 * code above if a modification to an existing order. Also
	 * $ExistingOrder would be set to 1. The delivery check screen
	 * is where the details of the order are either updated or 
	 * inserted depending on the value of ExistingOrder */
	
		$_SESSION['ExistingOrder']=0;
		$_SESSION['PO'.$identifier] = new PurchOrder;
		$_SESSION['PO'.$identifier]->AllowPrintPO = 1; /*Of course cos the order aint even started !!*/
		$_SESSION['PO'.$identifier]->GLLink = $_SESSION['CompanyRecord']['gllink_stock'];

		if ($_SESSION['PO'.$identifier]->SupplierID=='' OR !isset($_SESSION['PO'.$identifier]->SupplierID)){

/* a session variable will have to maintain if a supplier 
 * has been selected for the order or not the session 
 * variable supplierID holds the supplier code already 
 * as determined from user id /password entry  */
			$_SESSION['RequireSupplierSelection'] = 1;
		} else {
			$_SESSION['RequireSupplierSelection'] = 0;
		}
		
}

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

/* change supplier only allowed with appropriate permissions - 
 * button only displayed to modify is AccessLevel >10  
 * (see below)*/
	if ($_SESSION['PO'.$identifier]->Stat==_('Pending') and $_SESSION['UserID']==$_SESSION['PO'.$identifier]->Initiator) {
		if ($_SESSION['PO'.$identifier]->Any_Already_Received()==0){
			$emailsql='SELECT email FROM www_users WHERE userid="'.$_SESSION['PO'.$identifier]->Initiator.'"';
			$emailresult=DB_query($emailsql, $db);
			$emailrow=DB_fetch_array($emailresult);
			$date = date($_SESSION['DefaultDateFormat']);
			$_SESSION['RequireSupplierSelection']=1;
			$_SESSION['PO'.$identifier]->Stat=_('Pending');
			$StatusComment=$date.' - Supplier changed by <a href="mailto:'.$emailrow['email'].'">'.$_SESSION['UserID'].
				'</a> - '.$_POST['StatComments'].'<br>'.$_POST['statcommentscomplete'];
			$_SESSION['PO'.$identifier]->StatComments=$StatusComment;
		} else {
			echo '<br><br>';
			prnMsg(_('Cannot modify the supplier of the order once some of the order has been received'),'warn');
		}
	}
}

$msg='';
if (isset($_POST['SearchSuppliers'])){

	if (strlen($_POST['Keywords'])>0 AND strlen($_SESSION['PO'.$identifier]->SupplierID)>0) {
		$msg=_('Supplier name keywords have been used in preference to the supplier code extract entered');
	}
	if ($_POST['Keywords']=='' AND $_POST['SuppCode']=='') {
		$msg=_('At least one Supplier Name keyword OR an extract of a Supplier Code must be entered for the search');
	} else {
		if (strlen($_POST['Keywords'])>0) {
		//insert wildcard characters in spaces

			$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 suppliers.supplierid, 
					suppliers.suppname, 
					suppliers.address1, 
					suppliers.address2, 
					suppliers.address3, 
					suppliers.address4,
					suppliers.address5, 
					suppliers.address6, 
					suppliers.currcode
				FROM suppliers 
				WHERE suppliers.suppname " . LIKE . " '$SearchString'
				ORDER BY suppliers.suppname";

		} elseif (strlen($_POST['SuppCode'])>0){
			$SQL = "SELECT suppliers.supplierid, 
					suppliers.suppname,
					suppliers.address1, 
					suppliers.address2, 
					suppliers.address3, 
					suppliers.address4,
					suppliers.address5, 
					suppliers.address6, 
					suppliers.currcode		 
				FROM suppliers 
				WHERE suppliers.supplierid " . LIKE . " '%" . $_POST['SuppCode'] . "%'
				ORDER BY suppliers.supplierid";
		}

		$ErrMsg = _('The searched supplier records requested cannot be retrieved because');
		$result_SuppSelect = DB_query($SQL,$db,$ErrMsg);

		if (DB_num_rows($result_SuppSelect)==1){
			$myrow=DB_fetch_array($result_SuppSelect);
			$_POST['Select'] = $myrow['supplierid'];
		} elseif (DB_num_rows($result_SuppSelect)==0){
			prnMsg( _('No supplier records contain the selected text') . ' - ' . 
				_('please alter your search criteria and try again'),'info');
		}
	} /*one of keywords or SuppCode was more than a zero length string */
} /*end of if search for supplier codes/names */


// added by Hudson	
if((!isset($_POST['SearchSuppliers']) or $_POST['SearchSuppliers']=='' ) AND 
	(isset($_SESSION['PO'.$identifier]->SupplierID) AND $_SESSION['PO'.$identifier]->SupplierID!='')){

	/*The session variables are set but the form variables have been lost
	 * need to restore the form variables from the session */
	$_POST['SupplierID']=$_SESSION['PO'.$identifier]->SupplierID;
	$_POST['SupplierName']=$_SESSION['PO'.$identifier]->SupplierName;
	$_POST['CurrCode'] = $_SESSION['PO'.$identifier]->CurrCode;
	$_POST['ExRate'] = $_SESSION['PO'.$identifier]->ExRate;
	$_POST['paymentterms'] = $_SESSION['PO'.$identifier]->paymentterms;
	$_POST['DelAdd1']=$_SESSION['PO'.$identifier]->DelAdd1;
	$_POST['DelAdd2']=$_SESSION['PO'.$identifier]->DelAdd2;
	$_POST['DelAdd3']=$_SESSION['PO'.$identifier]->DelAdd3;
	$_POST['DelAdd4']=$_SESSION['PO'.$identifier]->DelAdd4;
	$_POST['DelAdd5']=$_SESSION['PO'.$identifier]->DelAdd5;
	$_POST['DelAdd6']=$_SESSION['PO'.$identifier]->DelAdd6;
}

if (isset($_POST['Select'])) {
	
/* will only be true if page called from supplier selection form 
 * or set because only one supplier record returned from a search 
 * so parse the $Select string into supplier code and branch code */
	$sql='SELECT currcode FROM suppliers where supplierid="'.$_POST['Select'].'"';
	$result=DB_query($sql,$db);
	$myrow=DB_fetch_array($result);
	$SupplierCurrCode=$myrow['currcode'];
	
	
	$authsql='SELECT cancreate 
			FROM purchorderauth 
			WHERE userid="'.$_SESSION['UserID'].'"
			AND currabrev="'.$SupplierCurrCode.'"';

	$authresult=DB_query($authsql,$db);
	
	$sql = "SELECT suppliers.vendor_name, 
			 suppliers.payterms,
			 suppliers.adrress1, 
			 suppliers.adrress2, 
			 suppliers.address3
			 FROM suppliers WHERE vendor_code ='".trim($suppid)."'";

	$ErrMsg = _('The supplier record of the supplier selected') . ': ' . $_POST['Select'] . ' ' . 
		_('cannot be retrieved because');
	$DbgMsg = _('The SQL used to retrieve the supplier details and failed was');
	$result =DB_query($sql,$db,$ErrMsg,$DbgMsg);
	$myrow = DB_fetch_row($result);

		// added for suppliers lookup fields

	if ($authmyrow=DB_fetch_array($authresult) and $authmyrow[0]==0) {
		$_POST['SupplierName']  = $myrow[0];
		$_POST['CurrCode']      = $myrow[1];
		$_POST['ExRate']        = $myrow[2];
		$_POST['paymentterms']  = $myrow[3];
		$_POST['suppDelAdd1']   = $myrow[4];
		$_POST['suppDelAdd2']   = $myrow[5];
		$_POST['suppDelAdd3']   = $myrow[6];
		$_POST['suppDelAdd4']   = $myrow[7];
		$_POST['suppDelAdd5']   = $myrow[8];
		$_POST['suppDelAdd6']   = $myrow[9];
		$_POST['supptel']       = $myrow[10];
		$_POST['port']          = $myrow[11];

		$_SESSION['PO'.$identifier]->SupplierID = $_POST['Select'];
		$_SESSION['RequireSupplierSelection'] = 0;
		$_SESSION['PO'.$identifier]->SupplierName = $_POST['SupplierName'];
		$_SESSION['PO'.$identifier]->CurrCode     = $_POST['CurrCode'];
		$_SESSION['PO'.$identifier]->ExRate       = $_POST['ExRate'];
		$_SESSION['PO'.$identifier]->paymentterms = $_POST['paymentterms'];
		$_SESSION['PO'.$identifier]->suppDelAdd1 = $_POST['suppDelAdd1'];
		$_SESSION['PO'.$identifier]->suppDelAdd2 = $_POST['suppDelAdd2'];
		$_SESSION['PO'.$identifier]->suppDelAdd3 = $_POST['suppDelAdd3'];
		$_SESSION['PO'.$identifier]->suppDelAdd4 = $_POST['suppDelAdd4'];
		$_SESSION['PO'.$identifier]->suppDelAdd5 = $_POST['suppDelAdd5'];
		$_SESSION['PO'.$identifier]->suppDelAdd6 = $_POST['suppDelAdd6'];
		$_SESSION['PO'.$identifier]->supptel     = $_POST['supptel'];
		$_SESSION['PO'.$identifier]->port        = $_POST['port'];
	} else {
		prnMsg( _('You do not have the authority to raise Purchase Orders for ').
			'<br>'.$SupplierName.'. '._('Please Consult your system administrator for more information').'. '
			._('You can setup authorisations ').'<a href=PO_AuthorisationLevels.php>'._('here:'). '</a>', 'warn');
		include('includes/footer.inc');
		exit;
	}
	
	// end of added for suppliers lookup fields

} else {
	$_POST['Select'] = $_SESSION['PO'.$identifier]->SupplierID;
	if($suppid !="")
	{
	$sql = "SELECT suppliers.vendor_name, suppliers.vendor_code,
			 suppliers.payterms,
			 suppliers.adrress1, 
			 suppliers.adrress2, 
			 suppliers.address3
			 FROM suppliers Where vendor_code='".$suppid."'";
   }else {
   
   $sql = "SELECT suppliers.vendor_name, suppliers.vendor_code,
			 suppliers.payterms,
			 suppliers.adrress1, 
			 suppliers.adrress2, 
			 suppliers.address3
				 FROM suppliers Where vendor_code='".$_GET['suppid']."'"; 
   }				 
	$ErrMsg = _('The supplier record of the supplier selected') . ': ' . $suppid . ' ' . 
		_('cannot be retrieved because');
	$DbgMsg = _('The SQL used to retrieve the supplier details and failed was');
	$result =DB_query($sql,$db,$ErrMsg,$DbgMsg);
	$myrow = DB_fetch_array($result);
	$SupplierName = $myrow['vendor_name'];
	//$suppname = $myrow['vendor_name'];
	$supplier_id = $myrow['vendor_code'];
    //$suppid   = $myrow[11];
	//$_POST['SupplierName'] = $myrow[0];
	$_POST['CurrCode'] = 	$myrow[1];
	$_POST['paymentterms']=	$myrow[2];
	$_POST['suppDelAdd1'] = $myrow[3];
	$_POST['suppDelAdd2'] = $myrow[4];
	$_POST['suppDelAdd3'] = $myrow[5];
	$_POST['suppDelAdd4'] = $myrow[6];
	$_POST['suppDelAdd5'] = $myrow[7];
	$_POST['suppDelAdd6'] = $myrow[8];
	$_POST['supptel'] = $myrow[9];
	$_POST['port'] = $myrow[10];



	$_SESSION['PO'.$identifier]->SupplierID = $_POST['Select'];
	$_SESSION['RequireSupplierSelection'] = 0;
	$_SESSION['PO'.$identifier]->SupplierName = $_POST['SupplierName'];
	$_SESSION['PO'.$identifier]->CurrCode     = $_POST['CurrCode'];
	$_SESSION['PO'.$identifier]->ExRate       = $_POST['ExRate'];
	$_SESSION['PO'.$identifier]->paymentterms = $_POST['paymentterms'];
	$_SESSION['PO'.$identifier]->suppDelAdd1  = $_POST['suppDelAdd1'];
	$_SESSION['PO'.$identifier]->suppDelAdd2  = $_POST['suppDelAdd2'];
	$_SESSION['PO'.$identifier]->suppDelAdd3  = $_POST['suppDelAdd3'];
	$_SESSION['PO'.$identifier]->suppDelAdd4  = $_POST['suppDelAdd4'];
	$_SESSION['PO'.$identifier]->suppDelAdd5  = $_POST['suppDelAdd5'];
	$_SESSION['PO'.$identifier]->suppDelAdd6  = $_POST['suppDelAdd6'];
	$_SESSION['PO'.$identifier]->supptel      = $_POST['supptel'];
	$_SESSION['PO'.$identifier]->port         = $_POST['port'];
	// end of added for suppliers lookup fields
}



	echo "<form name='form1' action='' method=post>";
	
	
	
	
	
	
// Be careful not made confused by orderno and realorderno
//	$orderno = previous_id("purchorders","orderno");
//    	$_SESSION['PO'.$identifier]->OrderNo2 = $orderno;	
	echo '<p class="page_title_text"><img src="'.$rootpath.'/css/'.$theme.'/images/supplier.png" title="' . 
			_('Purchase Order') . '" alt="">';
	echo 'Purchase Order';'</u> </b> - ' . _('All amounts stated in') . ' ' . 
			$_SESSION['PO'.$identifier]->CurrCode . '<br>';
			//$_SESSION['PO'.$identifier]->SupplierName;
			
	if ($_SESSION['ExistingOrder']) {
		echo  _(' Modify Purchase Order Number') . ' ' . $_SESSION['PO'.$identifier]->OrderNo . '<br>';	
	}
			
/* 2008-08-19 ToPu -- debugging purpose */
	if (isset($purch_item)) {
		prnMsg(_('Purchase Item(s) with this code') . ': ' .  $purch_item,'info');
  	 
		/**
		 * 2008-08-21 ToPu
		 * Now go ahead to PO_Items.php
		 * with NewItem=$purch_item
		 */
		/* a somewhat nice outfit for that link */
		echo "<div class='centre'>";
		echo '<br><table class="table_index"><tr><td class="menu_group_item">';

		/* the link */
		echo '<li><a href="'.$rootpath.'/PO_Items.php?' . SID . 'NewItem=' . $purch_item . "?identifier=".$identifier. '">' . 
			_('Enter Line Item to this purchase order') . '</a></li>';
		/**/
		echo "</td></tr></table></div><br>";
	}
	
	/*Set up form for entry of order header stuff */

	if (!isset($_POST['LookupDeliveryAddress']) and (!isset($_POST['StkLocation']) or $_POST['StkLocation']) 
		AND (isset($_SESSION['PO'.$identifier]->Location) AND $_SESSION['PO'.$identifier]->Location != '')) {
		/* The session variables are set but the form variables have 
	     * been lost --
	     * need to restore the form variables from the session */
	    $_POST['StkLocation']=$_SESSION['PO'.$identifier]->Location;
		$_POST['SupplierContact']=$_SESSION['PO'.$identifier]->SupplierContact;
	    $_POST['DelAdd1']=$_SESSION['PO'.$identifier]->DelAdd1;
	    $_POST['DelAdd2']=$_SESSION['PO'.$identifier]->DelAdd2;
	    $_POST['DelAdd3']=$_SESSION['PO'.$identifier]->DelAdd3;
	    $_POST['DelAdd4']=$_SESSION['PO'.$identifier]->DelAdd4;
	    $_POST['DelAdd5']=$_SESSION['PO'.$identifier]->DelAdd5;
	    $_POST['DelAdd6']=$_SESSION['PO'.$identifier]->DelAdd6;
	    $_POST['Initiator']=$_SESSION['PO'.$identifier]->Initiator;
	    $_POST['Requisition']=$_SESSION['PO'.$identifier]->RequisitionNo;
	    $_POST['version']=$_SESSION['PO'.$identifier]->version;
	    $_POST['deliverydate']=$_SESSION['PO'.$identifier]->deliverydate;
	    $_POST['revised']=$_SESSION['PO'.$identifier]->revised;
	    $_POST['ExRate']=$_SESSION['PO'.$identifier]->ExRate;
	    $_POST['Comments']=$_SESSION['PO'.$identifier]->Comments;
	    $_POST['deliveryby']=$_SESSION['PO'.$identifier]->deliveryby;
	}

// move apart by Hudson
	
	echo '<br><table border=1 colspan=1 width=80% align="center">
		<tr>              
			<td><font color=black size=4><strong>' . _('Order Initiation Details') . '</strong></font></td>                      		
              
			<td><font color=black size=4><b>' . _('Order Status') . '</b></font></td>                      		
		</tr>		<tr><td style="width:50%">';

	echo '<table>';
	echo '<tr><td>' . _('PO Date') . ':</td><td>';
	if ($_SESSION['ExistingOrder']!=0){ 
		echo ConvertSQLDate($_SESSION['PO'.$identifier]->Orig_OrderDate);
	} else {
		/* DefaultDateFormat defined in config.php */
		echo Date($_SESSION['DefaultDateFormat']);
	}
	echo '</td></tr>';

	$date = date($_SESSION['DefaultDateFormat']);
		   
	if (isset($_GET['ModifyOrderNumber']) && $_GET['ModifyOrderNumber'] != '') 
	{
		$_SESSION['PO'.$identifier]->version += 1;
		$_POST['version'] =  $_SESSION['PO'.$identifier]->version; 
	} elseif (isset($_SESSION['PO'.$identifier]->version) and $_SESSION['PO'.$identifier]->version != '') {
		$_POST['version'] =  $_SESSION['PO'.$identifier]->version; 
	} else {
		$_POST['version']='1';
	}
	if (!isset($_POST['deliverydate'])) {
		$_POST['deliverydate']= date($_SESSION['DefaultDateFormat']);
	}
	echo "<tr><td></td><td><input type='hidden' name='Comparative' size=30 
		maxlength=15 value='".$PO_Orderno. "' readonly></td></tr>"; //value='" "'
	
	/*echo '<tr><td>' . _('Version'). ' #' . ":</td><td><input type='hidden' name='version' size=16 maxlength=15 
		value='" . $_POST['version'] . "'>".$_POST['version']."</td></tr>";*/
		
	echo "<tr><td>"._('Comparison No.').":<input type='hidden' name='Comparative' size=30 
		maxlength=15 value='".$compnum."' readonly></td><td>".$compnum."</td></tr>";
		
		echo "<tr><td>"._('Comparison Date').":<input type='hidden' name='Comparative' size=30 
		maxlength=15 value='".$compdate."' readonly></td><td>".$compdate."</td></tr>";
		
	/*echo '<tr><td>' . _('Revised') . ":</td><td><input type='hidden' name='revised' size=11 maxlength=15 value=" . 
		$date . '>'.$date.'</td></tr>';*/

	echo '<tr><td>' . _('Delivery Date') . ":</td><td><input type='text' class=date alt='".$_SESSION['DefaultDateFormat'].
		"' name='deliverydate' size=11 value=" . $_POST['deliverydate'] . '>'."</td></tr>";

	if (!isset($_POST['Initiator'])) {
		$_POST['Initiator'] = $_SESSION['UserID'];
		$_POST['Requisition'] = '';
	}
	
		$REQ_SQL = "SELECT requisitionno from materialrequisitions WHERE Reqno='".$Reqno."' ";
		$RES = DB_query($REQ_SQL,$db);
	    $MYROW = DB_fetch_array($RES);
		$requisitionno = $MYROW['requisitionno'];
		//echo $requisitionno;
	
	echo '<tr><td>' . _('Initiated By') . ":</td>
			<td><input type='hidden' name='Initiator' size=11 maxlength=10 value=" . 
			$_POST['Initiator'] . ">".$_POST['Initiator']."</td></tr>";
			
			echo "<tr><td>"._('Requisition No.').":<input type='hidden' name='Requi' size=30 
		maxlength=15 value='".$requisitionno."' readonly></td><td>".$Reqno."</td></tr>";
		
		echo "<tr><td>"._('Requisition Date').":<input type='hidden' name='purdate' size=15 
		maxlength=15 value='".convertSQLDate($prdate)."' readonly></td><td>".convertSQLDate($prdate)."</td></tr>";
			
		/*echo "<tr><td>"._('Purchase At').":<input type='hidden' name='purchaseat' size=30
		maxlength=15 value='".$purchaseat."' readonly></td><td>".$purchaseat."</td></tr>";*/
		
	
		echo "<tr><td>".'Quotation No.'.":<input type='hidden' name='vendorqutno' size=30
		maxlength=15 value='". $vernder_quotation."' readonly></td><td>".$vernder_quotation."</td></tr>";
		
		echo "<tr><td>".'Quotation Date.'.":<input type='hidden' name='vendorqutdate' size=15
		maxlength=15 value='". convertSQLDate($date1)."' readonly></td><td>".convertSQLDate($date1)."</td></tr>";
	if (isset($_POST['AllowRePrint'])) {
		$sql='UPDATE purchorders SET allowprint=1 WHERE orderno='.$_SESSION['PO'.$identifier]->OrderNo;
		$result=DB_query($sql, $db);
	}

	if ($_SESSION['PO'.$identifier]->AllowPrintPO==0 AND $_POST['RePrint']!=1){
		echo '<tr><td>' . _('Allow Reprint') . ":</td><td><select name='RePrint' onChange='ReloadForm(form1.AllowRePrint)'><option selected value=0>" . 
			_('No') . "<option value=1>" . _('Yes') . '</select></td>';
		echo '<td><input type=submit name="AllowRePrint" value="Update"></td></tr>';
	} elseif ($Printed) {
		echo "<tr><td colspan=2><a target='_blank'  href='$rootpath/PO_PDFPurchOrder.php?" . 
			SID . "OrderNo=" . $_SESSION['ExistingOrder'] . "&identifier=".$identifier. "'>" . _('Reprint Now') . '</a></td></tr>';
	}

	echo '</table>';
	
	echo '<td style="width:50%"><table>';
	if($_SESSION['ExistingOrder']!=0 and $_SESSION['PO'.$identifier]->Stat==_('Printed')){
		echo '<tr><td><a href="' .$rootpath . "/GoodsReceived.php?" . SID . "&PONumber=" . 
			$_SESSION['PO'.$identifier]->OrderNo . "&identifier=".$identifier.'">'._('Receive this order').'</a></td></tr>';
	}
	echo '<td>' . _('Status') . ' :  </td><td><select name=Stat>';
	
	switch ($_SESSION['PO'.$identifier]->Stat) 
	{
		case _('Pending'):
			$StatusList=array(_('Pending'), _('Authorised'), _('Rejected'), _('Cancelled'));
			break;
		case _('Authorised'):
			$StatusList=array(_('Pending'), _('Authorised'), _('Cancelled'));
			break;
		case _('Rejected'):
			$StatusList=array(_('Pending'), _('Authorised'), _('Rejected'), _('Cancelled'));
			break;
		case _('Cancelled'):
			$StatusList=array(_('Pending'), _('Cancelled'));
			break;
		case _('Printed'):
			$StatusList=array(_('Pending'), _('Printed'), _('Cancelled'));
			break;
		case _('Completed'):
			$StatusList=array(_('Completed'));
			break;
		default:
			$StatusList=array(_('New Order')); /*, _('Pending'), _('Authorised'), _('Rejected'), _('Cancelled')*/
			break; 
	}

	foreach ($StatusList as $Status) {
		if ($_SESSION['PO'.$identifier]->Stat==$Status){
			echo '<option selected value='.$Status.'>' . $Status;
		} else {
			echo '<option value='.$Status.'>' . $Status;
		}
	}
	echo '</select></td></tr>';
	
	echo '<tr><td>' . ('Status Comment');
	echo ":</td><td><input type=text name='StatComments' size=50></td></tr><tr><td colspan=2><b>" . html_entity_decode($_SESSION['PO'.$identifier]->StatComments) .'</b></td></tr>';
	echo "<input type=hidden name='statcommentscomplete' value='".$_SESSION['PO'.$identifier]->StatComments."'>";
	
	/*echo '<tr><td><input type="submit" name=UpdateStat value="' . _("Status Update") .'"></td>';

	echo "<td><input type='submit' name='CancelOrder' value='" . _("Cancel and Delete Order") . "'></td></tr>";*/
	echo '</table></td>';

// end of move by Hudson

	echo '<table border=1 width=80% align="center">
		<tr>
		<td><font color=black size=4><b>' . _('Site Info') . '</b></font></td>
		<!--	<td><font color=blue size=4><b>' . _('Delivery To') . '</b></font></td> -->
			<td><font color=black size=4><b>' . _('Supplier Info') . '</b></font></td>
		</tr>
		<tr><td valign=top>';
	/*nested table level1 */
     $sql = "SELECT loccode, locationname FROM locations WHERE loccode ='".$_REQUEST['sitecode']."'";
	 $result=DB_query($sql, $db);
	  $myrow = DB_fetch_array($result);
	 echo '<table><tr><td>' . _('Site Name') . ':';
	  echo '<input type="hidden" name="StkLocation" size="" value="'.$myrow['locationname'].'" readonly/>'; 
		echo '</td><td>'.$myrow['locationname'].'</td>';
		echo '</tr>';
		
		echo '<tr><td>' . _('Site Code') . ':';
	  echo '<input type="hidden" name="Stkcode" size="" value="'.$myrow['loccode'].'" readonly/>'; 
		echo '</td><td>'.$myrow['loccode'].'</td>';
		echo '</tr>';

/* If this is the first time 
 * the form loaded set up defaults */

	if (!isset($_POST['StkLocation']) OR $_POST['StkLocation']==''){ 

		$_POST['StkLocation'] = $_SESSION['UserStockLocation'];

	 $sql = "SELECT * FROM locations  WHERE loccode ='" .$_REQUEST['sitecode']. "'";

		$LocnAddrResult = DB_query($sql,$db);
		if (DB_num_rows($LocnAddrResult)==1){
			$LocnRow = DB_fetch_row($LocnAddrResult);
			$_POST['DelAdd1'] = $LocnRow[11];
			$_POST['DelAdd2'] = $LocnRow[12];
			$_POST['DelAdd3'] = $LocnRow[13];
			$_POST['DelAdd4'] = $LocnRow[14];
			$_POST['DelAdd5'] = $LocnRow[15];
			$_POST['DelAdd6'] = $LocnRow[16];
			$_POST['Contact'] = $LocnRow[45];
			
			//echo $_POST['Contact'];  
			
			
			$_POST['phone1']  = $LocnRow[18];

			$_SESSION['PO'.$identifier]->Location= $_POST['StkLocation'];
			$_SESSION['PO'.$identifier]->Location= $_POST['Stkcode'];
			$_SESSION['PO'.$identifier]->SupplierContact= $_POST['SupplierContact'];
			$_SESSION['PO'.$identifier]->DelAdd1 = $_POST['DelAdd1'];
			$_SESSION['PO'.$identifier]->DelAdd2 = $_POST['DelAdd2'];
			$_SESSION['PO'.$identifier]->DelAdd3 = $_POST['DelAdd3'];
			$_SESSION['PO'.$identifier]->DelAdd4 = $_POST['DelAdd4'];
			$_SESSION['PO'.$identifier]->DelAdd5 = $_POST['DelAdd5']; 
			$_SESSION['PO'.$identifier]->DelAdd6 = $_POST['DelAdd6'];
			$_SESSION['PO'.$identifier]->contact = $_POST['Contact'];
			$_SESSION['PO'.$identifier]->phone1 = $_POST['phone1'];

		} else { 
			 ////////////The default location of the user is crook ///////////////
			prnMsg(_('The default stock location set up for this user is not a currently defined stock location') . 
				'. ' . _('Your system administrator needs to amend your user record'),'error');
		}


	} elseif (isset($_POST['LookupDeliveryAddress'])){

		 echo   $sql = "SELECT * FROM locations WHERE loccode='" . $_REQUEST['sitecode'] . "'";

		$LocnAddrResult = DB_query($sql,$db);
		if (DB_num_rows($LocnAddrResult)==1){
			$LocnRow = DB_fetch_row($LocnAddrResult);
			$_POST['DelAdd1'] = $LocnRow[11];
			$_POST['DelAdd2'] = $LocnRow[12];
			$_POST['DelAdd3'] = $LocnRow[13];
			$_POST['DelAdd4'] = $LocnRow[14];
			$_POST['DelAdd5'] = $LocnRow[15];
			$_POST['DelAdd6'] = $LocnRow[16];
			echo $_POST['Contact'] = $LocnRow['contact'];
			$_POST['phone1']  = $LocnRow[18];

			$_SESSION['PO'.$identifier]->Location= $_POST['StkLocation'];
			$_SESSION['PO'.$identifier]->Location= $_POST['Stkcode'];
			$_SESSION['PO'.$identifier]->DelAdd1 = $_POST['DelAdd1'];
			$_SESSION['PO'.$identifier]->DelAdd2 = $_POST['DelAdd2'];
			$_SESSION['PO'.$identifier]->DelAdd3 = $_POST['DelAdd3'];
			$_SESSION['PO'.$identifier]->DelAdd4 = $_POST['DelAdd4'];
			$_SESSION['PO'.$identifier]->DelAdd5 = $_POST['DelAdd5'];
			$_SESSION['PO'.$identifier]->DelAdd6 = $_POST['DelAdd6'];
			$_SESSION['PO'.$identifier]->contact = $_POST['Contact']; 
			$_SESSION['PO'.$identifier]->phone1  = $_POST['phone1'];
		}
	}
		$sit_tin = "Select tin_no,mobile from locations WHERE loccode='" . $_REQUEST['sitecode'] . "'";
		$site_res = DB_query($sit_tin,$db);
		$site_row = DB_fetch_array($site_res);

	/*echo '<tr><td>' . _('Delivery Contact') . ":</td>";
	echo "<td>".$_POST['Contact']."<input type='hidden' name=Contact size=41  value='" . $_POST['Contact'] . "' readonly></td>
		</tr>";*/
	echo '<tr><td>' . _('Address') . " 1 :</td>
		<td>".$_POST['DelAdd1']."<input type='hidden' name=DelAdd1 size=41 maxlength=40 value='" . $_POST['DelAdd1'] . "' readonly></td>
		</tr>";
	echo '<tr><td>' . _('Address') . " 2 :</td>
		<td>".$_POST['DelAdd2']."<input type='hidden' name=DelAdd2 size=41 maxlength=40 value='" . $_POST['DelAdd2'] . "' readonly></td>
		</tr>";
	echo '<tr><td>' . _('Address') . " 3 :</td>
		<td>".$_POST['DelAdd3']."<input type='hidden' name=DelAdd3 size=41 maxlength=40 value='" . $_POST['DelAdd3'] . "' readonly></td>
		</tr>";
	echo '<tr><td>' . _('Phone') . ":</td>
		<td>".$_POST['phone1']."<input type='hidden' name=tel size=31 maxlength=30 value='" . $_POST['phone1'] . "' readonly></td>
		</tr>";
		echo '<tr><td>' . _('Mobile') . ":</td>
		<td>".$site_row['mobile']."<input type='hidden' name=tel size=31 maxlength=30 value='" . $site_row['mobile'] . "' readonly></td>
		</tr>";
		
		echo '<tr><td>' . _('Tin No.') . ":</td>
		<td>".$site_row['tin_no']."<input type='hidden' name=tel size=31 maxlength=30 value='".$site_row['tin_no']."' readonly></td>
		</tr>";

	echo '<tr><td>' . _('Delivery By') . ':</td><td>';
	?>
	<select name="deliveryby">
	<option value="000">---Select delivery Mode---</option>
	<option value="Land" <?php echo ($_POST['deliveryby']=='Land'?'selected':'')?>>Road</option>
	<option value="Air" <?php echo ($_POST['deliveryby']=='Air'?'selected':'')?>>Air</option>
	<option value="Sea" <?php echo ($_POST['deliveryby']=='Sea'?'selected':'')?>>Sea</option>
	</select></tr></table>
	<?php
	  /* end of sub table */
	
	echo '</td><td>'; /*sub table nested */	  
	echo '<table><tr><td>' . _('Vendor Name') . " :
	<input type='hidden' name=Keywords id=Keywords value='" . $SupplierName. "' readonly>";
	echo '</td><td>'.$SupplierName.'</td></tr>';
	
	echo'<tr><td>' . _('Vendor Code') . " :
	<input type='hidden' name=Keywords id=Keywords value='" . $suppid. "' readonly>";
	echo '</td><td>'.$suppid.'</td></tr>';
	
///////// END of added <input type=submit action=RESET VALUE="' . _('Reset') ///////////////////////////
    
	//$sql = "SELECT contact FROM suppliercontacts Where supplierid='".$suppid."'";
	
	$sql = "select tin_no,mobile,phone1 from suppliers where vendor_code = '".$suppid."' ";
	$SuppCoResult = DB_query($sql,$db);
	$SuppCoRow=DB_fetch_array($SuppCoResult);
	echo '</td></tr>';
	
	/*echo '<tr><td>' . _('Supplier Contact') . ':</td>';
	echo '<td>'.$SuppCoRow['contact'].'<input type ="hidden" name = "SupplierContact" id="SupplierContact"  value = "'.$SuppCoRow['contact'].'" Readonly>'; 
	echo '</td></tr>';*/
	
	echo '<tr><td>' . _('Address') . " 1 :</td>
		</td><td>".$_POST['suppDelAdd1']."<input type='hidden' name=suppDelAdd1 size=41 maxlength=40 value='" . $_POST['suppDelAdd1'] . "' readonly></td>
		</tr>";
	echo '<tr><td>' . _('Address') . " 2 :</td>
		</td><td>".$_POST['suppDelAdd2']."<input type='hidden' name=suppDelAdd2 size=41 maxlength=40 value='" . $_POST['suppDelAdd2'] . "' readonly></td>
		</tr>";
	echo '<tr><td>' . _('Address') . " 3 :</td>
		</td><td>".$_POST['suppDelAdd3']."<input type='hidden' name=suppDelAdd3 size=41 maxlength=40 value='" . $_POST['suppDelAdd3'] . "' readonly></td>
		</tr>";
	echo '<tr><td>' . _('Phone') . ":
		</td><td>".$SuppCoRow['phone1']."<input type='hidden' name=supptel size=31 maxlength=30 value='" . $_POST['supptel'] . "' readonly></td>
		</tr>";
		
		echo '<tr><td>' . _('Mobile') . ":
		</td><td>".$SuppCoRow['mobile']."<input type='hidden' name=supptel size=31 maxlength=30 value='" . $SuppCoRow['mobile'] . "' readonly></td>
		</tr>";

		echo '<tr><td>' . _('Tin No.') . ":
		</td><td>".$SuppCoRow['tin_no']."<input type='hidden' name=supptel size=31 maxlength=30 value='" . $SuppCoRow['tin_no'] . "' readonly></td>
		</tr>";

	$result=DB_query('SELECT terms, termsindicator FROM paymentterms', $db);

	echo '<tr><td>' . _('Payment Terms') . ":</td><td><select name='PaymentTerms'>";
	echo '<option value="000">---Select Payment Terms---</option>';
	while ($myrow = DB_fetch_array($result)) {
		if ($myrow['termsindicator']==$_SESSION['PO'.$identifier]->paymentterms) {
			echo "<option selected value='". $myrow['termsindicator'] . "'>" . $myrow['terms'];
		} else {
			echo "<option value='". $myrow['termsindicator'] . "'>" . $myrow['terms'];
		} //end while loop
	}
	DB_data_seek($result, 0);
	echo '</select></td></tr>';
	
	$result=DB_query("SELECT loccode, locationname FROM locations WHERE loccode='" . $_POST['port'] ."'", $db);
	$myrow = DB_fetch_array($result);
	$_POST['port'] = $myrow['locationname'];

	/*echo '<tr><td>' . _('Delivery To') . ":
		</td><td><input type='text' name=port size=31 value='" . $_POST['port'] . "'></td>
		</tr>";*/

	
	echo '</td></tr></table>'; /*end of sub table */

	echo '</td></tr><tr><th colspan=4>' . _('Comments');

	$Default_Comments = '';

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

	echo ":</th></tr><tr><td colspan=4><textarea name='Comments' style='width:100%' rows=5>" . $comments . '</textarea>';

	echo '</table>';
    
	echo '</td></tr></table><br>'; /* end of main table */
	// discard change supplier submit buttom
	// kept enter line item but remove Delete button by Hudson 11/16,and added status field
	echo "<div class='centre'>";
	
	if($ModifyOrderNumber !='')
	{
  	echo "<input type=submit name='EnterLinesEdit' value='" . _('Submit') . "'>
		  <input type=hidden name='suppierid' value='" . $suppid ."'>
		  <input type=hidden name='final_qtation' value='" . $final_Quot ."'>
		  <input type=hidden name='ModifyOrderNumber' value='" .$ModifyOrderNumber."'>";
	}
	 else
	 {
	echo "<input type=submit name='EnterLines' value='" . _('Submit') . "'>
			<input type=hidden name='suppierid' value='" . $suppid . "'>
			<input type=hidden name='final_qtation' value='" .$final_Quot. "'>";
	 }
		
		"</div>";
	// Delete PO when necessrary

 /*end of if supplier selected */

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