<?php
$PageSecurity = 4;
include('includes/DefinePOClass.php');
include('includes/session.inc');
if (isset($_GET['orderno'])) {
	$title = _('Modify Purchase Order') . ' ' . $_GET['orderno'];
} else {
	$title = _('Purchase Order Entry');
}

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

/*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.
 */
 $orderno = $_REQUEST['orderno'];
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 */

	 $ModifyOrderNumbe= $_GET['ModifyOrderNumbe'];
	 $final_Quot      = $_GET['final_Quot'];
	 $sitecode        = $_GET['sitecode'];
	 $sitename        = $_GET['sitename'];
	 $suppid          = $_GET['suppid'];
	 $vendername      = $_GET['vendername'];
	 $RequisitionNo   = $_GET['requisitionno'];
	
	 //echo $RequisitionNo;
	 

    $sql="SELECT intostocklocation FROM materialrequisitions WHERE requisitionno='".$RequisitionNo."'";
	$result=DB_query($sql,$db);
	$myrow=DB_fetch_array($result);
	$purchaseat=$myrow['intostocklocation'];
	
  	$sql2="SELECT * FROM purchorders WHERE orderno='".$_GET['ModifyOrderNumbe']."'";
	$result2=DB_query($sql2,$db);
	$myrow2=DB_fetch_array($result2);
	$deliveryby=$myrow2['deliveryby'];
	$deliverycontact=$myrow2['contact'];
	$PO_Orderno=$myrow2['PO_Orderno'];
	$vendor_quotation_no=$myrow2['vendor_quotation_no'];

	$sql3 = "Select * from materialrequisitions where requisitionno = '". $RequisitionNo. "' ";
	$result3=DB_query($sql3,$db);
	$myrow3=DB_fetch_array($result3);
	$Reqno = $myrow3['Reqno'];

//	echo $sql4 = "Select * from venderquotations where id = '". $final_Quot. "' ";Ekta


	$sql4 = "Select * from venderquotations where  vernder_quotation  = '". $_REQUEST['vendorid']. "' ";
 
	$result4=DB_query($sql4,$db);
	$myrow4=DB_fetch_array($result4);
	$vernder_quotation = $myrow4['vernder_quotation'];
	    $vender_payment_term   = $myrow4['payment_term'];
	  $vender_payment_mode = $myrow4['payment_mode'];


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['PO'.$identifier]->Initiator.'"';
	$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'].'"
			AND currabrev="'.$_SESSION['PO'.$identifier]->CurrCode.'"';

		$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;
			} 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;
			} 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;
			} 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;
			} 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){


				$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['EnterUpdateLines'])){
/*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]->payment_terms = $_POST['PaymentTerms'];
	
	/*
	  $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: ".$rootpath."/PO_Items_update.php?identifier=".$identifier."&suppid=".$suppierid. "&Update=".update. "&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');
}


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]->payment_terms = $_POST['PaymentTerms'];
	
	/*
	  $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: ".$rootpath."/PO_Items.php?identifier=".$identifier."&suppid=".$suppierid. "&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');
} /* end of if isset _POST'EnterLines' */

echo '<a href="'. $rootpath . '/index.php?' . SID . "identifier=".$identifier.'">'. _('Main Menu'). '</a>>>';
echo '<a href="'. $rootpath . '/PO_SelectOSPurchOrder.php?' . SID . "identifier=".$identifier.'">'. _('Back To Order List'). '</a><br>';

/*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){
			
			$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);

			$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);
	$SupplierName = $myrow[0];
		// 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');
		
	}
	
	// end of added for suppliers lookup fields

} else {
	$_POST['Select'] = $_SESSION['PO'.$identifier]->SupplierID;
	 $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') . ': ' . $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_row($result);
	// added for suppliers lookup fields
	$_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[12];

	$_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
}

// MADE THE SUPPILERS BECOME SELECT MENU NOT BY SEARCHING By Hudson @2008/6/30

// part of step 1
/* everything below here only do if a supplier is selected */


	echo "<form name='form1' action='" . $_SERVER['PHP_SELF'] . '?' . SID . "identifier=".$identifier. "' 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  _(' View Purchase Order Number-') . ' ' .$ModifyOrderNumbe . '<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%>
		<tr>              
			<td><font color=black size=4><b>' . _('Order Initiation Details') . '</b></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>';

	echo '<tr><td>' . _('PO Number') . ':</td>
	<td><input type="hidden" name="POnum" size="30" value="'.$PO_Orderno.'">'.$PO_Orderno.'</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>' . _('Version'). ' #' . ":</td><td><input type='hidden' name='version' size=16 maxlength=15 
		value='" . $_POST['version'] . "'>".$_POST['version']."</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>" . $_POST['deliverydate'] . "</td></tr>";

	if (!isset($_POST['Initiator'])) {
		$_POST['Initiator'] = $_SESSION['UserID'];
		$_POST['Requisition'] = '';
	}

	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.').":</td><td>" . $RequisitionNo . '</td></tr>';
		echo "<tr><td>"._('Purchase At').":</td><td>".$sitename."</td></tr>";
		echo "<tr><td>".'Vendor Quot. No.'.":</td><td>". $vendor_quotation_no."</td></tr>";

//	echo '<tr><td>' . _('Exchange Rate') . ":</td>
//			<td><input type=TEXT name='ExRate' size=16 maxlength=15 VALUE=" . $_POST['ExRate'] . '></td>
//	echo "<input type='hidden' name='ExRate' size=16 maxlength=15 value=" . $_POST['ExRate'] . "></td>";
//		</tr>';
	echo '<tr><td>' . _('Date Printed') . ':</td><td>';

	if (isset($_SESSION['PO'.$identifier]->DatePurchaseOrderPrinted) AND strlen($_SESSION['PO'.$identifier]->DatePurchaseOrderPrinted)>6){
		echo ConvertSQLDate($_SESSION['PO'.$identifier]->DatePurchaseOrderPrinted);
		$Printed = True;
	} else {
		$Printed = False;
		echo _('Not yet printed');
	}
	
	if (isset($_POST['AllowRePrint'])) {
		$sql='UPDATE purchorders SET allowprint=1 WHERE orderno='.$_SESSION['PO'.$identifier]->ModifyOrderNumbe;
		$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 . "ModifyOrderNumbe=" . $_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]->ModifyOrderNumbe . "&identifier=".$identifier.'">'._('Receive this order').'</a></td></tr>';
	}
	echo '<td>' . _('Status') . ' :  </td><td><select name=Stat>';
	
	switch ($_SESSION['PO'.$identifier]->Stat) {
		case '':
			$StatusList=array(_('New Order'));
			break;
		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%>
		<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 style="width:50%">';
	/*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 Code') . ':</td>';
	echo '<td>'.$myrow['loccode'].''; 
	echo '</td>';
	echo '</tr>';
	echo '<tr><td>' . _('Site Name') . ':</td>';
	echo '<td>'.$myrow['locationname'].'</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];
			$_POST['phone1']  = $LocnRow[18];

			$_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]->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'])){

		   $sql = "SELECT *	FROM locations 	WHERE loccode='" . $_POST['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];
			$_POST['phone1']  = $LocnRow[18];

			$_SESSION['PO'.$identifier]->Location= $_POST['StkLocation'];
			$_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'];
		}
	}


	echo '<tr><td>' . _('Delivery') . ":</td>
		<td>" . $deliverycontact . "</td>
		</tr>";
	echo '<tr><td>' . _('Address') . " 1 :</td>
		<td>" . $_POST['DelAdd1'] . "</td>
		</tr>";
	echo '<tr><td>' . _('Address') . " 2 :</td>
		<td>" . $_POST['DelAdd2'] . "</td>
		</tr>";
	echo '<tr><td>' . _('Address') . " 3 :</td>
		<td>" . $_POST['DelAdd3'] . "</td>
		</tr>";

	echo '<tr><td>' . _('Phone') . ":</td>
		<td>" . $_POST['phone1'] . "</td>
		</tr>";
		
		echo '<tr><td>' . _('Tin No.') . ":</td>
		<td></td>
		</tr>";

	echo '<tr><td>' . _('Delivery By') . ':</td><td>';
		echo $deliveryby;
		echo '</tr></table>'; 
	  /* end of sub table */
	
	echo '</td><td>'; /*sub table nested */	  
	echo '<table><tr><td>' . _('Vendor Code') . ':</td><td>
	      '. $suppid.'';
	echo '</td></tr>';
	
	echo '<tr><td>' . _('Vendor Name') . ':</td><td>
	      '. $vendername.'';
	echo '</td></tr>';

// END of added <input type=submit action=RESET VALUE="' . _('Reset') 

	echo '</td></tr><tr><td>' . _('Supplier Contact') . ':</td><td>';
 	   $sql = "select contact,tin_no from suppliers where vendor_code='".$suppid."'";
		$contact_res = DB_query($sql,$db);
		$contact_row = DB_fetch_array($contact_res);
	echo $contact_row['contact'].'<input name=SupplierContact type="hidden" id="SupplierContact" readonly="true" value="'.$contact_row['contact'].'">';	   
	echo '</td></tr>';
	echo '<tr><td>' . _('Address') . " 1 :</td>
		</td><td>" . $_POST['suppDelAdd1'] . "</td>
		</tr>";
	echo '<tr><td>' . _('Address') . " 2 :</td>
		</td><td>" . $_POST['suppDelAdd2'] . "</td>
		</tr>";
	
	echo '<tr><td>' . _('Phone') . ":
		</td><td>" . $_POST['supptel'] . "</td>
		</tr>";


 
 	$pro_result=DB_query("SELECT terms FROM paymentterms Where termsindicator='".$vender_payment_term."'", $db);
     $promyrow = DB_fetch_array($pro_result);
	echo '<tr><td>' . _('Payment Terms') . ":</td><td>";
	echo $promyrow['terms'];
	
	echo '<tr><td>' . _('Tin No.') . ":</td><td>";
	echo $contact_row['tin_no'];
	
	echo '</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>" . $promyrow['Delivery_to']. "</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;
	}

     $sql1 = "Select * from purchorders Where orderno='".$_REQUEST['ModifyOrderNumbe']."'";
     $result1=DB_query($sql1, $db);
	 $myrow = DB_fetch_array($result1);


	echo ":</th></tr><tr><td colspan=4 height=50>" . $myrow['comments'];

	echo '</table>';
   ?> 
   <br>
	<div align="center"><b><?php  echo '<p class="page_title_text"><img src="'.$rootpath.'/css/'.$theme.'/images/supplier.png" title="' . 
			_('Purchase Order') . '" alt="">'; ?>Item Detail View </b></div><br>
<?php 	
	echo "<div class='centre'>";
function getTaxInformation($suppid, $final_Quot, $ModifyOrderNumbe){
   global $db;

  $sql="select taxauthorities.taxid, taxauthorities.description, taxgrouptaxes.*,suppliers.supplierid from suppliers
INNER JOIN taxgroups on taxgroups.taxgroupid = suppliers.taxgroupid
INNER JOIN taxgrouptaxes on taxgrouptaxes.taxgroupid = taxgroups.taxgroupid
INNER JOIN taxauthorities on taxauthorities.taxid = taxgrouptaxes.taxauthid
where suppliers.supplierid='".$suppid."' ";
	  $result =DB_query($sql,$db);
	  $i=0;
	while($myrow = DB_fetch_row($result))
	{
	   $TaxID[$i] = $myrow[0];
		$TaxDesc[$i] = $myrow[1];
		$TaxGroupId[$i] = $myrow[2];
		$CalculationOrder[$i] = $myrow[4];
        $SSql = "select * from purchordertax Where orderno ='".$ModifyOrderNumbe."' AND taxgroupid='".$TaxID[$i]."'";
		 $Seleresult =DB_query($SSql,$db);
		 $myselectrow = DB_fetch_row($Seleresult);
		
		echo '<tr><td align="right" style="text-align:right;"  colspan="5">'.$TaxDesc[$i].'</td><td>
		
		'.$TaxID[$i].'%=
		'.$myselectrow[3].'';
		echo '</td><td colspan="6">&nbsp;</td></tr>';
		$i++;
	}
	return $suplierData;
}
/////////////////////////////new display////////////////////////////////////
				
				$PO_SQL = "Select orderno from purchorders where PO_Orderno = '".$PO_Orderno."' ";
				$RESULT = DB_query($PO_SQL, $db);
				$MYROW = DB_fetch_array($RESULT);
				$orderno = $MYROW['orderno'];
				$orderno;
				 
				 echo'<table width="90%" border="2">
				<tr>
				<th>'."Item Code ".'</th>
				<th>'."Item Description".'</th>
				<th>'."Make".'</th>
				<th>'."Color".'</th>
				<th>'."Grade".'</th>
				<th>'."Quantity".'</th>
				<th>'."Rate".'</th>
				<th>'."Discount".'</th>
				<th>'."SubTotal".'</th>
				<th>'."Tax Value".'</th>
				<th>'."Total Tax Amount".'</th>
				<th>'."Total Amount With Taxes".'</th>
				<th>'."Lead Time".'</th>
				<th>'."Pre Delevery Ins.".'</th>
				<th>'."Specification".'</th>
				<th>'."Quantum".'</th></tr>';
				
				$sql="SELECT quatity, 
							itemcode, 
							itemdescription, 
							Rate, 
							Discount, 
							Sub_total,
							Lead_Time, 
							Pre_Delevery_Ins, 
							Specification, 
							Quantum, 
							Total_Charges_Cost, 
							grand_total_amount,
							subtotal_amount,
							Tax_value,
							Tax_amount,
							Amount_with_tax,
							make,
							color,
				   	        grade
							from purchorderdetails where orderno = '".$orderno."' "; 
				 
				 $result=DB_query($sql, $db);
					   $i=1;
  while($myrow=DB_fetch_array($result))
     {
		echo '<tr> ';
	   
	   echo '<td>'.$myrow['itemcode'].'<input type="hidden" name="ProductID['.$i.']" size="10" value="'.$myrow['itemcode'].'"readonly></td>';
	   
	   echo '<td>'.$myrow['itemdescription'].'<input type="hidden" name="ProductDes['.$i.']" size="45" value="'.$myrow['itemdescription'].'" readonly></td>';

	   
	 echo '<td>'.$myrow['make'].'<input type="hidden" name="make['.$i.']" size="45" value="'.$myrow['make'].'" readonly></td>';
	  
	 echo '<td>'.$myrow['color'].'<input type="hidden" name="color['.$i.']" size="45" value="'.$myrow['color'].'" readonly></td>';
	  
	 echo '<td>'.$myrow['grade'].'<input type="hidden" name="grade['.$i.']" size="45" value="'.$myrow['grade'].'" readonly></td>';
	  
	  echo '<td><input type="hidden" name="quantity['.$i.']" size="5" value="'.$myrow['quatity'].'" id="Quantity_'.$i.'" readonly>'.$myrow['quatity'].'</td>';
	   
	   echo '<td>'.$myrow['Rate'].'<input type="hidden" name="Rate['.$i.']" id="Rate_'.$i.'"  value="'.$myrow['Rate'].'" size="4" readonly/></td>';
	   
	   if($myrow['discount_type']=="PercentAmt")
	     {echo '<td>'.$myrow['Discount'].'<input type="hidden" name="Discount['.$i.']" id="Discount_'.$i.'" value="'.$myrow['Discount'].'" onblur="DiscountAmount(this.value,'.$i.')" size="8" readonly /></td>';}
	   else {echo '<td>'.$myrow['Discount'].'<input type="hidden" name="Discount['.$i.']" id="Discount_'.$i.'" value="'.$myrow['Discount'].'" onblur="DiscountAmount(this.value,'.$i.')" size="8" readonly /></td>';}	 
	   
	   	   echo '<td>'.$myrow['Sub_total'].'<input type="hidden" id="NetRate_'.$i.'" name="NetRate['.$i.']" value="'.$myrow['Sub_total'].'" size="8" readonly/></td>';

		 
		 
		 echo '<td>'.$myrow['Tax_value'].'<input type="hidden" name="taxvalue['.$i.']" value="'.$myrow['Tax_value'].'" size="8" readonly />
	   </td>';
	   
	   
	   echo '<td>'.$myrow['Tax_amount'].'<input type="hidden" name="total_tax_amoun['.$i.']" value="'.$myrow['Tax_amount'].'" size="8" readonly />
	   </td>';
	   
	   
	   echo '<td>'.$myrow['Amount_with_tax'].'<input type="hidden" name="total_amount_with_taxes['.$i.']" value="'.$myrow['Amount_with_tax'].'" size="8" readonly />
	   </td>';
		
		echo '<td>'.$myrow['Lead_Time'].'<input type="hidden" name="LeadTime['.$i.']" value="'.$myrow['Lead_Time'].'" size="8" readonly/></td>';
	   echo '<td>'.$myrow['Pre_Delevery_Ins'].'<input type="hidden" name="PreIns['.$i.']" value="'.$myrow['Pre_Delevery_Ins'].'" size="8" readonly /></td>';
	   echo '<td>'.$myrow['Specification'].'<input type="hidden" name="Specification['.$i.']" value="'.$myrow['Specification'].'" size="15" readonly /></td>';
	   echo '<td>'.$myrow['Quantum'].'<input type="hidden" name="Quantum['.$i.']" value="'.$myrow['Quantum'].'" size="10" readonly /></td>';
	   $i++;
}   

	echo "<input type='hidden' name='PO_count' value='".$i."'>";

	 $SQL="SELECT quatity, 
			itemcode, 
			itemdescription, 
			Rate, 
			Discount, 
			Sub_total,
			Lead_Time, 
			Pre_Delevery_Ins, 
			Specification, 
			Quantum, 
			Total_Charges_Cost, 
			grand_total_amount,
			subtotal_amount
			from purchorderdetails where orderno = '".$orderno."' "; 
				 
				 $RESULT=DB_query($SQL, $db);
				 $MYROW=DB_fetch_array($RESULT);
				 $MYROW['subtotal_amount'];
			
	echo  '<tr><td align="right" style="text-align:right;" colspan=5><B>'."Material Cost With Taxes".'</B></td><td>'.$MYROW['subtotal_amount'].'<input type="hidden" colspan=5 name="TWT" id="TWT"  value="'.$MYROW['subtotal_amount'].'" size="8" readonly></td>
</tr>';  

echo '</table>';
echo '<br/>';
echo '<br/>';
echo '<br/>';
echo ' <table width="60%" border="2">
					<tr>
					  <th><strong>'."Description".'</strong></th>
					  <th><strong>'."Inclusive".'</strong></th>
					  <th><strong>'."As Per Actual".'</strong></th>
					 <th><strong>'."Amount".'</strong></th>
					 <th><strong>'."Percentage Amount".'</strong></th>
					</tr>';

$SQL = "select ch_name, Inclusive, As_Per_Actual, charges, charges_Amount from po_charge where Orderno='".$orderno."'   ";
$finalresult = DB_query($SQL, $db);
			
			$CR=1;
			while($finalresultrow = DB_fetch_array($finalresult))
			{
				if($finalresultrow['Inclusive'] == 'NO')
				{
				  echo '<tr>
				  <th>'.$finalresultrow['ch_name'].'</th>
				  <td>'.$finalresultrow['Inclusive'].'</td>
				  <td>'.$finalresultrow['As_Per_Actual'].'</td>
				  <td>'.$finalresultrow['charges'].'</td>
				  <td>'.$finalresultrow['charges_Amount'].'</td>
				  </tr>';
				}
			$CR++;
			}
	
	$Sql="SELECT Total_Charges_Cost, 
				grand_total_amount
				from purchorderdetails where orderno = '".$orderno."' ";
				
				$Result=DB_query($Sql, $db);
				$Myrow=DB_fetch_array($Result);
		echo '<tr>
			      <th>'."Total Charges Cost".'</th>
				  <td colspan="3">'.$Myrow['Total_Charges_Cost'].'<input type="hidden" name="totalcharge" value="'.$Myrow['Total_Charges_Cost'].'" size="10" readonly /><td>
				  </tr>
				  <tr>
				  <th>'."Grand Total".'</th>
				  <td colspan="4">'.$Myrow['grand_total_amount'].'
				 <input type="hidden" name="grand_total_amount" value="'.$Myrow['grand_total_amount'].'" size="10" readonly /></td>
				  </tr>';
			echo '</table>';		
		
	
	// Delete PO when necessrary

 /*end of if supplier selected */
echo '</td></tr></table><br>';
echo '</form>';
include('includes/footer.inc');
?>


<script type="text/javascript">
var TotalPercent=0;
var TotalAmount=0;
var finalAmount=0;
function ChargeCalculater(Amt,Amtid)
  {
     var AsPerActual=document.getElementById(Amtid).value;
	 var ActualType=document.getElementById("AsPerActual_"+Amtid).value;
	 if(document.getElementById(Amtid).value !='')
	 {
	 if(ActualType=='PercentAmt')
	   {
	     var Total= document.getElementById("Total").value;
		 var charge= parseFloat(Total) * parseFloat(AsPerActual)/100;
		 TotalPercent= parseFloat(TotalPercent) + parseFloat(charge);
		 document.getElementById("actual_"+Amtid).value= charge;
	   }
	 else
	   {
	     document.getElementById("actual_"+Amtid).value=AsPerActual; 
		 TotalAmount=parseFloat(TotalAmount) + parseFloat(AsPerActual);
	   }
	    finalAmount= parseFloat(TotalAmount) + parseFloat(TotalPercent);
		//alert(finalAmount);
		//document.getElementById("TotalCharge").value=parseFloat(finalAmount);
		
		if(isNaN(finalAmount))
		{
			 var TotalCharge =document.getElementById("TotalCharge").value;
			 var AsPerActual=document.getElementById(Amtid).value;
			
			if(AsPerActual !='')
			{	
			 var finalAmountTotal2= parseFloat(AsPerActual) + parseFloat(TotalCharge);
			  document.getElementById("TotalCharge").value=finalAmountTotal2;
			}
			else
			{
			   document.getElementById("TotalCharge").value=TotalCharge;
			}
		}
		else
		{
		  document.getElementById("TotalCharge").value=parseFloat(finalAmount);
		}
		
	}
		
	return true;
  }

function FinalGrandTotal(A)
   {
      var GTWC=document.getElementById("TWT").value;
	  var FinalGT= parseFloat(GTWC) + parseFloat(A);
		if(isNaN(FinalGT))
		{
		  document.getElementById("GrandTotal").value=parseFloat(0);
		}
		else
		{
		  document.getElementById("GrandTotal").value=parseFloat(FinalGT);
		 }
		  
   }
function ChargeAmount(CA,ID)
 {
   if (CA=='NO')
     {
	   //alert(CA);
	   document.getElementById(ID).readOnly=true;
	   document.getElementById("actual_"+ID).disabled=true;
	   document.getElementById("AsPerActual_"+ID).disabled=true;
	 }
	else if (CA!='NO')
	 {
	    document.getElementById(ID).readOnly=false;
	    document.getElementById("AsPerActual_"+ID).disabled=false; 
		document.getElementById("actual_"+ID).disabled=false;
	 }    
  // alert(ID);
 }
var Total=0;
function DiscountAmount(DA,i)
{
	
	var discount_percent = document.getElementById("PerAmo_"+i).value;
	var rate = document.getElementById("Rate_"+i).value;
	var discount = document.getElementById("Discount_"+i).value;
	var quantity = document.getElementById("Quantity_"+i).value;
	var totalPrice = quantity*rate;
	if(discount_percent=='PercentAmt')
	{
		var percent = totalPrice * discount/100;
		var subTotal = totalPrice - percent;
	}
	else if(discount_percent=='Amount')
	{
		var percent = discount;
		var subTotal = totalPrice-percent;
	}
	document.getElementById("NetRate_"+i).value = subTotal;
	Total=parseFloat(Total) + parseFloat(subTotal);
	document.getElementById("Total").value=Total;
	return true;
}	

//alert(Total);
var GrandTax=0;
var GrandTotal=0;	
function TaxAmount(Tax,Name)
  {
    
	var Total=document.getElementById("Total").value;
	document.getElementById("tax_"+Name).value = Total*Tax/100;
	GrandTax=GrandTax + Total*Tax/100;
    GrandTotal = parseFloat(Total) + parseFloat(GrandTax);
	document.getElementById("TWT").value=GrandTotal;
	//alert(GrandTotal);
  }

function fillUpValueFromVendor(v){
var v = v;
return true;
}
</script>