<?php
// +---------------------------------------------------------------------------------------+
// | TenderSystem                                                                          |
// +---------------------------------------------------------------------------------------+
// | The contents of this file are subject to the TenderSystem Public License Version 1.1  |
// | ("License"); you may not use this file except in compliance with the License. You may |
// | obtain a copy of the License at http://www.tendersystem.com/tpl/                      |
// |                                                                                       |
// | Software distributed under the License is distributed on an "AS IS" basis, WITHOUT    |
// | WARRANTY OF ANY KIND, either express or implied. See the License for the specific     |
// | language governing rights and limitations under the License.                          |
// |                                                                                       |
// | All copies of the Covered Code must include the "Powered by TenderSystem" logo and    |
// | ValueCard copyright notice on every user interface screen and in every outgoing       |
// | email in the same form as they appear in the distribution.                            |
// |                                                                                       |
// | The Original Code is: TenderSystem                                                    |
// | The Initial Developer of the Original Code is ValueCard (Pty) Limited.                |
// | Portions created by ValueCard are Copyright (C) 2002 ValueCard (Pty) Limited.         |
// | All Rights Reserved.                                                                  |
// | Contributor(s): __________________.                                                   |
// +---------------------------------------------------------------------------------------+

/**
* Procure award class
* @package TenderSystem
* @subpackage procure
* @copyright Copyright &copy; 2002, ValueCard (Pty) Ltd
* @license http://www.tendersystem.com/tpl/ TenderSystem Public License
* @version 
*/

// Security - ensure that file never called directly
// not required if global variables are off or API is hosted on a non-public server
if (eregi(basename(__FILE__),$_SERVER['PHP_SELF'])) {
    die ("You can't access this file directly...");
}

Class procure_award extends procure {
	// set paramaters
	var $award;
	var $tender;
	var $error;
	var $client;
	
	function procure_award() {
		// allow to work on php5
		$this->error = array();	
	}
	
	/**
	 * Set tender quote status to 5
	 * 
	 * @param integer id Tender quote ID
	 * @param mixed cfg The Config settings of tendersystem
	 * @param [ADOConnection] conn The connection to the database
	 *
	 * @param mixed tender_information or FALSE on error  
	 */
	function lock_tender_quote($id,$cfg,$conn) {
		// Check if main parameters exist 
		if (!$id){
			// missing tender id
			$this->error[] = "259";
		}
		// errors 
		if(!empty($this->error)){
			// Error in Tender Class
			$this->error[] = "317";
			return FALSE;
		}
		// the table name
		$table_name = "~tender_quote";
		$where = " id = ".$id." ";
		$where.= " AND status = 4 ";
		$update['status'] = "5";
		$new_database = new database;
		$new_database->parse_sql($table_name,$cfg);
		// execute
		$conn->AutoExecute($table_name,$update,"UPDATE",$where);
	    if ($conn->ErrorMsg()) {
	    	// instantiate the error class and log
			$new_error = new error;
			$error_text = "SQL error in file ".__file__." on line ".__line__." Error:".$conn->ErrorMsg();
			$new_error->log("SQL","critical",$error_text,$cfg);
			// error occurred while updating information on database
			$this->error[] = "1066";
			// response
			return FALSE;
      	}
      	return TRUE;
	}

	/**
	 * Set tender item status to 5
	 * 
	 * @param integer id Tender Item ID
	 * @param mixed cfg The Config settings of tendersystem
	 * @param [ADOConnection] conn The connection to the database
	 *
	 * @param mixed tender_information or FALSE on error  
	 */
	function lock_tender_item($id,$cfg,$conn) {
		// Check if main parameters exist 
		if (!$id){
			// missing tender id
			$this->error[] = "259";
		}
		// errors 
		if(!empty($this->error)){
			// Error in Tender Class
			$this->error[] = "317";
			return FALSE;
		}
		// the table name
		$table_name = "~tender_item";
		$where = " id = ".$id." ";
		$where.= " AND status = 4 ";
		$update['status'] = "5";
		$new_database = new database;
		$new_database->parse_sql($table_name,$cfg);
		// execute
		$conn->AutoExecute($table_name,$update,"UPDATE",$where);
	    if ($conn->ErrorMsg()) {
	    	// instantiate the error class and log
			$new_error = new error;
			$error_text = "SQL error in file ".__file__." on line ".__line__." Error:".$conn->ErrorMsg();
			$new_error->log("SQL","critical",$error_text,$cfg);
			// error occurred while updating information on database
			$this->error[] = "1066";
			// response
			return FALSE;
      	}
      	return TRUE;
	}

	/**
	 * Set tender item status to 4
	 * 
	 * @param array params search information
	 * @param mixed cfg The Config settings of tendersystem
	 * @param [ADOConnection] conn The connection to the database
	 *
	 * @param mixed tender_information or FALSE on error  
	 */
	function unlock_tender_item($tenderid,$cfg,$conn) {
		// Check if main parameters exist 
		if (!$tenderid){
			// missing tender id
			$this->error[] = "259";
		}
		// errors 
		if(!empty($this->error)){
			// Error in Tender Class
			$this->error[] = "317";
			return FALSE;
		}
		// the table name
		$table_name = "~tender_item";
		if(is_array($tenderid)) {
			$first = TRUE;
			foreach($tenderid as $value) {
				if($first) {
					$where = "( id = ".$value." ";
					$first = FALSE;
				} else {
					$where.= " OR id = ".$value." ";
				}
			}
			$where.= ") AND status = '5' ";
		} else {
			$where = " id = ".$tenderid." ";
			$where.= " AND status = '5' ";
		}
		$update['status'] = "4";
		$new_database = new database;
		$new_database->parse_sql($table_name,$cfg);
		// execute
		$conn->AutoExecute($table_name,$update,"UPDATE",$where);
	    if ($conn->ErrorMsg()) {
	    	// instantiate the error class and log
			$new_error = new error;
			$error_text = "SQL error in file ".__file__." on line ".__line__." Error:".$conn->ErrorMsg();
			$new_error->log("SQL","critical",$error_text,$cfg);
			// error occurred while updating information on database
			$this->error[] = "1066";
			// response
			return FALSE;
      	}
      	return TRUE;
	}


	/**
	 * Set tender quote status to 4
	 * 
	 * @param array params search information
	 * @param mixed cfg The Config settings of tendersystem
	 * @param [ADOConnection] conn The connection to the database
	 *
	 * @param mixed tender_information or FALSE on error  
	 */
	function unlock_tender_quote($tenderid,$cfg,$conn) {
		// Check if main parameters exist 
		if (!$tenderid){
			// missing tender id
			$this->error[] = "259";
		}
		// errors 
		if(!empty($this->error)){
			// Error in Tender Class
			$this->error[] = "317";
			return FALSE;
		}
		// the table name
		$table_name = "~tender_quote";
		if(is_array($tenderid)) {
			$first = TRUE;
			foreach($tenderid as $value) {
				if($first) {
					$where = "(id = ".$value." ";
					$first = FALSE;
				} else {
					$where.= " OR id = ".$value." ";
				}
			}
			$where.= ") AND status = '5' ";
		} else {
			$where = " id = ".$tenderid." ";
			$where.= " AND status = '5' ";
		}
		$update['status'] = "4";
		$new_database = new database;
		$new_database->parse_sql($table_name,$cfg);
		// execute
		$conn->AutoExecute($table_name,$update,"UPDATE",$where);
	    if ($conn->ErrorMsg()) {
	    	// instantiate the error class and log
			$new_error = new error;
			$error_text = "SQL error in file ".__file__." on line ".__line__." Error:".$conn->ErrorMsg();
			$new_error->log("SQL","critical",$error_text,$cfg);
			// error occurred while updating information on database
			$this->error[] = "1066";
			// response
			return FALSE;
      	}
      	return TRUE;
	}
	
	function set_language($module,$language,$cfg,$conn) {
		// include the language file
		$lang = array();
		require($cfg['file'].'modules/procure/language/'.$language.'/award.php');
		if($module) {
			require($cfg['file'].'modules/'.$module.'/language/'.$language.'/award.php');
		}
		// set the language
		$this->lang = $lang;
	}
	
	
	function do_award_item(&$xml_params,&$params,$user,$module,$cfg,$conn) {
		// create objects
		$new_users = new user;
		$new_org = new organisation;
		$new_message = new message;
		// loop through all tender_quotes needed to be awarded
		foreach($params['award_item'] as $tender_quote_id => $tender_id) {
			// getting quote information from id
			$tender_quote[$tender_quote_id] = $this->get_tender_quote($tender_quote_id,$cfg,$conn);
			// check if succesfully
			if($tender_quote[$tender_quote_id]) {
				// lock  the quotes
				if(!$this->lock_tender_quote($tender_quote_id,$cfg,$conn)) {
					// Could not lock quotes
					$this->error[] = "326";
					// remove from list
					unset($tender_quote[$tender_quote_id]);
					// move on to next quote
					continue;
				}
				// quote is locked
				$tender_quote[$tender_quote_id]['status'] = "5";
				// tender_quotes to lock ie awarding
				$lock_tender_quote[$tender_quote_id] = $tender_quote_id;
				// get tender_item id
				$item_id = $tender_quote[$tender_quote_id]['tender_item'];
			} else {
				// error
				$xml_params['error_tender_quote'][] = $tender_quote_id;
				// remove from list
				unset($tender_quote[$tender_quote_id]);
				// move on to next quote
				continue;
			}
			// adding the item
			$tender_item[$item_id] = $this->get_tender_item($item_id,$cfg,$conn);
			// check if succesfully
			if($tender_item[$item_id] && $tender_item[$item_id]['status'] = "4") {
				// lock items
				if(!$this->lock_tender_item($item_id,$cfg,$conn)) {
					// Could not lock items
					$this->error[] = "324";
					// remove from list
					unset($tender_item[$item_id]);
					// move on to next quote
					continue;
				}
				// item now locked
				$tender_item[$item_id]['status'] = "5";
				// add to locked items
				$lock_tender_item[$item_id] = $item_id;
				// get tender id
				$tender_id = $tender_item[$item_id]['tender'];
				
			} else {
				// error
				$xml_params['error_tender_item'][] = $item_id;
				// remove from list
				unset($tender_item[$quote['tender_item']]);
				// move on to next quote
				continue;
			}
			// adding the tender
			if($tender[$tender_id]) {
				continue;	
			}
			$tender[$tender_id] = $this->get_tender($tender_id,$cfg,$conn);
			// check if succesfully
			if($tender[$tender_id] && $tender[$tender_id]['status'] == "4") {
				// lock tender
				if(!$this->lock_tender($tender_id,$cfg,$conn)) {
					// Could not lock tenders
					$this->error[] = "323";
					// remove from list
					unset($tender[$tender_id]);
					// move on to next quote
					continue;
				}
				// add to locked tenders
				$lock_tender[$tender_id] = $tender_id;
				$tender[$tender_id]['status'] = "5";
			} else {
				// error
				$xml_params['error_tender'][] = $tender_id;
				// remove from list
				unset($tender[$tender_id]);
			}
		}
		// check award tenders
		if(!$tender || !is_array($tender)) {
			// no tenders to award
			$this->error[] = "322";
			$bad_tender = TRUE;
		}
		// check award items
		if(!$tender_item || !is_array($tender_item)) {
			// no items to award
			$this->error[] = "325";
			$bad_tender = TRUE;
		}
		// check quotes
		if(!$tender_quote || !is_array($tender_quote)) {
			// no quotes to award
			$this->error[] = "327";
			$bad_tender = TRUE;
		}
		if(!$bad_tender) {
			// info for purchase order
			$po_info = $this->get_purchase_order_info($lock_tender_quote,$cfg,$conn);
			$this->tender_quote = $tender_quote;
			$this->tender_item = $tender_item;
			// loop thourgh infor of phurchase order
			foreach($po_info as $value) {
				if($params['usersid']) {
					if($user['classification'] == 3 && is_array($params['usersid'])) {
						$id = $params['usersid'][$value['tenderid']];
					} else {
						$id = $params['usersid'];
					} 
				} else {
					$id = $tender[$value['tenderid']]['user_id']; 
				}
				$this->agent = $new_users->get_profile($value['agentid'],$cfg,$conn);
				$this->set_language($module,$this->agent['language'],$cfg,$conn);
				$this->awarder = $new_users->get_profile($id,$cfg,$conn);
				$this->tender = $tender[$value['tenderid']];
				// client information
				$this->client['cc'] = $params['ccpoclient'][$value['tenderid']];
				$this->client['message'] = $params['message'][$value['tenderid']];
				$this->client['preference'] = $params['preference'][$value['tenderid']];
				// check if there is too much excess for this specific supplier
				if($params['excess'][$value['tenderid']] > $value['price'] ) {
					$this->excess = $value['price'];
					$params['excess'][$value['tenderid']] -= $value['price'];
				} else {
					$this->excess = $params['excess'][$value['tenderid']];
					$params['excess'][$value['tenderid']] = 0;
				}
				
				// check if there is an assessment fee for this specific supplier
				if($params['assessment_fee'][$value['tenderid']][$value['agentid']]) {
					$this->assessment_fee = min($value['price'],$params['assessment_fee'][$value['tenderid']][$value['agentid']]);
				} else {
					$this->assessment_fee = FALSE;
				}
				
				// check for collect salvage option
				if($cfg['tender']['salvage']) {
					$this->collectsalvage = $params['collectsalvage'][$value['tenderid']];
				}
				if(!$this->agent) {
					// Missing agent id
					$this->error[] = "301";
					continue;
				} elseif(!$this->awarder) {
					// Missing subscriber id
					$this->error[] = "302";
					continue;
				}
				$comment = $params['comment'][$value['tenderid']];
				$reason = $params['reason'][$value['tenderid']];
				if($purchase_order = $this->award_tender($comment,$reason,$user,$cfg,$conn)) {
					unset($purchase_order['agent']);
					$purchase_order['agent'][0] = $this->agent;
					$purchase_order['subscriber'][0] = $this->awarder;
					$response = $purchase_order;
					// award tender_items
					$timestamp = ts_time($cfg);
					$insert['purchase_order'] = $purchase_order['id'];
					$insert['user_id'] = $this->awarder['id'];
					$insert['created_by'] = $user['id'];
					$insert['reason'] = $reason;
					$insert['status'] = "1";
					if(is_array($purchase_order['tender_item'])) {
						foreach($purchase_order['tender_item'] as $value1) {
							$insert['tender_quote'] = $value1['id'];
							$insert['tender_item'] = $value1['tender_item'];
							$insert['rating'] = $this->agent['rating'];
							// insert tender complete info
							if($this->create_tender_item_complete($insert,$cfg,$conn)) {
								// change status of quotes
								$this->complete_quote($value1['id'],$cfg,$conn);
								$this->tender_quote[$value1['id']]['status'] = "6";
								// change status of tender item
								$this->complete_item($value1['tender_item'],$cfg,$conn);
								$this->tender_item[$value1['tender_item']]['status'] = "6";
							}
						}
					}
					// add purchase_order to params
					$xml_params['purchase_order'][] = $purchase_order;
					// check if a new transport item must be created and updated remaining quotes
					$new_item = $this->check_transport($value['tenderid'],$user['id'],$cfg,$conn);
					if(is_array($new_item)) {
						// add new transport item
						$tender_item[$new_item['id']] = $new_item;
						// add to locked tenders
						$lock_tender_item[$new_item['id']] =  $new_item['id'];
						// update each quote
						foreach($tender_quote as $key1 => $value1) {
							// check if the quote belongs to this tender
							if($tender_item[$value1['tender_item']]['tender'] == $value['tenderid']) {
								// check if delivery or install quote
								if($tender_item[$value1['tender_item']]['classification'] == "3"
									|| $tender_item[$value1['tender_item']]['classification'] == "4") {
									// check if the quote must still be award
									if($value1['status'] == "5") {
										// update tender_item id to the transport item
										$tender_quote[$key1]['tender_item'] = $new_item['id'];
									}
								}
							}
						}
					}	
				}
			}
		}
		// update items and quotes
		$tenderquote = $this->tender_quote;
		$tender_item = $this->tender_item;
		// unlock all tender quote and items that have not been processed
		if($lock_tender_item) {
			$this->unlock_tender_item($lock_tender_item,$cfg,$conn);
			unset($lock_tender_item);
		}
		if($lock_tender_quote) {
			$this->unlock_tender_quote($lock_tender_quote,$cfg,$conn);
			unset($lock_tender_quote);
		}
		return $lock_tender;
	}
	
	function add_award_tender(&$xml_params,&$params,$tender,$tenderquoteid,$cfg,$conn) {
		$new_users = new user;
		$new_branch = new branch;
		$new_org = new organisation;
		// get user info
		$user_info = $new_users->get_info($tender['user_id'],$cfg,$conn);
		// get quote information
		$quote = $this->get_tender_quote($tenderquoteid,$cfg,$conn);
		// get agent information
		$agent_info = $new_users->get_info($quote['user_id'],$cfg,$conn);
		$agent_branch = $new_branch->get_info($agent_info['branch'],$cfg,$conn);
		$agent_info['branchcomment'] = $agent_branch['branch_comment'];
		// get supplier information
		$supplier_info = $new_org->get_info($agent_info['organisation'],$cfg,$conn);
		// check if tender as be added already
		if(!$xml_params['awardtender'][$tender['id']]) {
			// add the tender to params
			$xml_params['awardtender'][$tender['id']] = $tender;
		}
		// add to tender sum
		$xml_params['awardtender'][$tender['id']]['sum'] = sprintf("%.2f",$xml_params['awardtender'][$tender['id']]['sum'] + $quote['price']);	
		// check if supplier as be added already
		if(!$xml_params['awardtender'][$tender['id']]['supplier'][$supplier_info['id']]) {
			// add the supplier to params
			$xml_params['awardtender'][$tender['id']]['supplier'][$supplier_info['id']] = $supplier_info;
		}
		// add to supplier sum
		$xml_params['awardtender'][$tender['id']]['supplier'][$supplier_info['id']]['sum'] = sprintf("%.2f",$xml_params['awardtender'][$tender['id']]['supplier'][$supplier_info['id']]['sum'] + $quote['price']);	
		// check if agent as be added already
		if(!$xml_params['awardtender'][$tender['id']]['supplier'][$supplier_info['id']]['agent'][$agent_info['id']]) {
			// add the agent
			$xml_params['awardtender'][$tender['id']]['supplier'][$supplier_info['id']]['agent'][$agent_info['id']] = $agent_info;
		}
		// add to agent sum
		$xml_params['awardtender'][$tender['id']]['supplier'][$supplier_info['id']]['agent'][$agent_info['id']]['sum'] = sprintf("%.2f",$xml_params['awardtender'][$tender['id']]['supplier'][$supplier_info['id']]['agent'][$agent_info['id']]['sum'] + $quote['price']);
		// add the quote
		$xml_params['awardtender'][$tender['id']]['supplier'][$supplier_info['id']]['agent'][$agent_info['id']]['quote'][$quote['id']] = $quote;
		unset($quote);
		// check if it needs a delivery fee
		if($tender['transport'] == "d") {
			$quote = $this->get_transport($tender['id'],$agent_info['id'],"3",$user['id'],$cfg,$conn);	
		}
		// check if it needs a delivery fee
		if($tender['transport'] == "i") {
			$quote = $this->get_transport($tender['id'],$agent_info['id'],"4",$user['id'],$cfg,$conn);	
		}
		// check if transport fee has already been added
		if(!in_array($quote['id'],$params['nodeliver']) && !in_array($quote['id'],$params['noinstall'])) {
			// check if transport fee needs to be added
			if($quote && !$xml_params['awardtender'][$tender['id']]['supplier'][$supplier_info['id']]['agent'][$agent_info['id']]['quote'][$quote['id']]) {
				// add the quote
				$xml_params['awardtender'][$tender['id']]['supplier'][$supplier_info['id']]['agent'][$agent_info['id']]['quote'][$quote['id']] = $quote;
				// add to tender total
				$xml_params['awardtender'][$tender['id']]['sum'] += $quote['price'];
				$tmp = $xml_params['awardtender'][$tender['id']]['sum'];
				$tmp = sprintf("%.2f",$tmp);
				$xml_params['awardtender'][$tender['id']]['sum'] = $tmp;
				// add to supplier total
				$xml_params['awardtender'][$tender['id']]['supplier'][$supplier_info['id']]['sum'] += $quote['price'];
				$tmp = $xml_params['awardtender'][$tender['id']]['supplier'][$supplier_info['id']]['sum'];
				$tmp = sprintf("%.2f",$tmp);
				$xml_params['awardtender'][$tender['id']]['supplier'][$supplier_info['id']]['sum'] = $tmp;
				// add to agent total
				$xml_params['awardtender'][$tender['id']]['supplier'][$supplier_info['id']]['agent'][$agent_info['id']]['sum'] += $quote['price'];
				$tmp = $xml_params['awardtender'][$tender['id']]['supplier'][$supplier_info['id']]['agent'][$agent_info['id']]['sum'];
				$tmp = sprintf("%.2f",$tmp);
				$xml_params['awardtender'][$tender['id']]['supplier'][$supplier_info['id']]['agent'][$agent_info['id']]['sum'] = $tmp;
			}
		}		
	}
	
	/**
	 * Get purchase orders information
	 * 
	 * @param array params search information
	 * @param mixed cfg The Config settings of tendersystem
	 * @param [ADOConnection] conn The connection to the database
	 *
	 * @param mixed tender_information or FALSE on error  
	 */
	function get_purchase_order_info($tenderquote_id,$cfg,$conn) {
		$sqlstr = "SELECT ~tender.id AS tenderid, ";
		$sqlstr.= "agent.id AS agentid, ";
		$sqlstr.= "company.transaction_fee, company.transaction_min, company.sms_fee, ";
		$sqlstr.= "SUM(~tender_quote.price) AS price ";
		$sqlstr.= "FROM ~tender, ~tender_item, ~tender_quote, ";
		$sqlstr.= "~users subscriber, ~organisation company, ~users agent, ";
		$sqlstr.= "~organisation supplier ";
		$sqlstr.= "WHERE ~tender.status = 5 ";
		$sqlstr.= "AND ~tender_item.tender = ~tender.id ";
		$sqlstr.= "AND ~tender_item.status = 5 ";
		$sqlstr.= "AND ~tender_quote.tender_item = ~tender_item.id ";
		$sqlstr.= "AND ~tender_quote.status = 5 ";
		$sqlstr.= "AND subscriber.id = ~tender.user_id ";
		$sqlstr.= "AND company.id = subscriber.organisation ";
		$sqlstr.= "AND company.status = '1' ";
		$sqlstr.= "AND agent.id = ~tender_quote.user_id ";
		$sqlstr.= "AND supplier.id = agent.organisation ";
		$sqlstr.= "AND supplier.status = '1' ";
		$first = TRUE;
		foreach($tenderquote_id as $value) {
			if($first) {
				$sqlstr.= "AND (~tender_quote.id = ".$value." ";
				$first = FALSE;
			} else {
				$sqlstr.= " OR ~tender_quote.id = ".$value." ";
			}
		}
		$sqlstr.= ")";
		$sqlstr.= "GROUP BY ~tender.id, agent.id, ";
		$sqlstr.= "company.transaction_fee, company.transaction_min, company.sms_fee ";
		$new_database = new database;
		$new_database->parse_sql($sqlstr,$cfg);
		$all = $conn->GetAll($sqlstr,"",TRUE);
		if($conn->ErrorMsg()) {
			// instantiate the error class and log
			$new_error = new error;
			$error_text = "SQL error in file ".__file__." on line ".__line__." Error:".$conn->ErrorMsg()." SQL:".$sqlstr;
			$new_error->log("SQL","critical",$error_text,$cfg);
			// error occurred while querying into database 
			$this->error[] = "1065";
			// response
			return FALSE;
		}
		return $all;
	}
	
	/**
	 * Invalidate / cash settlement / Non-Tender Supplier
	 * 
	 * @param integer tender_item_id Tender item id
	 * @param mixed cfg The Config settings of tendersystem
	 * @param [ADOConnection] conn The connection to the database
	 *
	 * @param boolean TRUE on succes and FALSE on failure
	 */
	function do_complete_item($tender_item_id,$usersid,$reason,$cash,$nontender,$status,$cfg,$conn) {
		// get tender_item
		$tender_item = $this->get_tender_item($tender_item_id,$cfg,$conn);
		// check if succesfully
		if(!$tender_item || $tender_item['status'] != "4") {
			// move on to next item
			return FALSE;
		}
		// lock tender
		if(!$this->lock_tender($tender_item['tender'],$cfg,$conn)) {
			// Could not lock tender
			$this->errors[] = "323";
			// move on to next item
			return FALSE;
		}
		// lock items
		if(!$this->lock_tender_item($tender_item_id,$cfg,$conn)) {
			// Could not lock items
			$this->errors[] = "324";
			// move on to next item
			return FALSE;
		}
		// check if succesfully
		if(!$tender_item) {
			// error
			return FALSE;
		}
		$insert['user_id'] = $usersid;
		$insert['created_by'] = $usersid;
		$insert['reason'] = $reason[$tender_item['tender']];
		$insert['cash'] = $cash[$tender_item_id];
		$insert['nontender'] = $nontender[$tender_item_id];
		$insert['status'] = $status;
		$insert['tender_item'] = $tender_item['id'];
		// insert tender complete info
		if($this->create_tender_item_complete($insert,$cfg,$conn)) {
			// change status of tender item
			$this->complete_item($tender_item['id'],$cfg,$conn);
			return $tender_item + $insert;
		}
		return FALSE;
	}
	
	/**
	 * check if a new transport item must be created and update remaining quotes
	 * 
	 * @param integer id Tender ID
	 * @param integer user Creator User's ID
	 * @param mixed cfg The Config settings of tendersystem
	 * @param [ADOConnection] conn The connection to the database
	 *
	 * @param mixed array of tenders or FALSE on error  
	 */
	function check_transport($id,$usersid,$cfg,$conn) {
		$time = date("Y-m-d",ts_time($cfg));
		$this->tender = $id;
		$sqlstr = "SELECT ~tender_item.id, ~tender_item.tender, ~tender_item.classification, ";
		$sqlstr.= "~tender_item.category_sub, ~tender_item.brand, ~tender_item.model, ";
		$sqlstr.= "~tender_item.description, ~tender_item.quote, ~tender_item.budget, ";
		$sqlstr.= "~tender_item.status ";
		// FROM
		$sqlstr.= "FROM ~tender, ~tender_item ";
		// WHERE
		$sqlstr.= "WHERE (~tender.status = 4 OR  ~tender.status = 5) ";
		$sqlstr.= "AND (~tender_item.status = 5 OR ~tender_item.status = 6) ";
		$sqlstr.= "AND ~tender.id = ~tender_item.tender ";
		$sqlstr.= "AND (~tender_item.classification = 3 OR ~tender_item.classification = 4) ";
		$sqlstr.= "AND ~tender.id = ".$id." ";
		// ORDER BY
		$sqlstr.= "ORDER BY ~tender_item.status ASC, ~tender_item.id DESC ";
		$new_database = new database;
		$new_database->parse_sql($sqlstr,$cfg);	
		$row = $conn->GetRow($sqlstr);
		if($conn->ErrorMsg()) {
			// instantiate the error class and log
			$new_error = new error;
			$error_text = "SQL error in file ".__file__." on line ".__line__." Error:".$conn->ErrorMsg()." SQL:".$sqlstr;
			$new_error->log("SQL","critical",$error_text,$cfg);
			// error occurred while querying into database 
			$this->error[] = "1065";
			// response
			return FALSE;
		}
		// if already awarded
		if($row['status'] == "6") {
			// check if there are still items to be award
			$sqlstr = "SELECT ~tender_item.id, ~tender_item.status ";
			// FROM
			$sqlstr.= "FROM ~tender, ~tender_item ";
			// WHERE
			$sqlstr.= "WHERE (~tender.status = 4 OR  ~tender.status = 5) ";
			$sqlstr.= "AND (~tender_item.status = 4 OR ~tender_item.status = 5) ";
			$sqlstr.= "AND ~tender.id = ~tender_item.tender ";
			$sqlstr.= "AND ~tender_item.classification = 1 ";
			$sqlstr.= "AND ~tender.id = ".$id." ";
			$new_database = new database;
			$new_database->parse_sql($sqlstr,$cfg);	
			$one = $conn->GetRow($sqlstr);
			if($conn->ErrorMsg()) {
				// instantiate the error class and log
				$new_error = new error;
				$error_text = "SQL error in file ".__file__." on line ".__line__." Error:".$conn->ErrorMsg()." SQL:".$sqlstr;
				$new_error->log("SQL","critical",$error_text,$cfg);
				// error occurred while querying into database 
				$this->error[] = "1065";
				// response
				return FALSE;
			}
			if($one) {
				// create a new one
				$item = $row;
				$item['status'] = "5";
				$item['created_by'] = $usersid;
				$item['id'] = $this->create_tender_item($item,$cfg,$conn);
				if(!$item['id']) {		
					// error in award class
					$this->error[] = "317";
					// A SQL error
					return FALSE;
				}
				// update quotes
				$update['tender_item'] = $item['id'];
				$where = " tender_item = ".$row['id']." AND (status = 5 or status = 4) ";
				if(!$this->update_tender_quote($update,$where,$cfg,$conn)) {
					// error in award class
					$this->error[] = "317";
					// A SQL error
					return FALSE;
				}
				return $item;
			}
		}
		// response
		return TRUE;
	}
	
	/**
	 * Set tender item status to 6
	 * 
	 * @param integer item Tender Item id
	 * @param mixed cfg The Config settings of tendersystem
	 * @param [ADOConnection] conn The connection to the database
	 *
	 * @param boolean TRUE on succes and FALSE on failure
	 */
	function complete_item($item,$cfg,$conn) {
		return $this->complete_tender_item($item,$cfg,$conn);
	}
	
	/**
	 * Set tender quote status to 6
	 * 
	 * @param integer quote Tender quote id
	 * @param mixed cfg The Config settings of tendersystem
	 * @param [ADOConnection] conn The connection to the database
	 *
	 * @param boolean TRUE on succes and FALSE on failure
	 */
	function complete_quote($quote,$cfg,$conn) {
		return $this->complete_tender_quote($quote,$cfg,$conn);
	}
}
?>