<?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 close 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_close extends procure {
	
	function procure_close() {
		// allow php5 to work
		$this->error = array();	
	}
	
		/**
	 * look for tenders that need to be closed
	 * 
	 * @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 unclosed_tenders($class,$cfg,$conn) {
		// set the time
		$timestamp = ts_time($cfg);
		// query db to find out if closing date has been reached
		$sqlstr = "SELECT id, user_id ";
		$sqlstr.= "FROM ~tender ";
		$sqlstr.= "WHERE  status = '2' ";
		$sqlstr.= "AND  classification = '".$class."' ";
		$sqlstr.= "AND ( close_date < '".date("Y-m-d",$timestamp)."' ";
		$sqlstr.= "     OR ( close_date = '".date("Y-m-d",$timestamp)."' ";
		$sqlstr.= "     AND  close_time <= '".date("H:i:s",$timestamp)."'))";
		$new_database = new database;
		$new_database->parse_sql($sqlstr,$cfg);
		// execute the query
 		$all = $conn->GetAll($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();
			$new_error->log("SQL","critical",$error_text,$cfg);
			// set the response error
			$this->error[] = "1065";
			// response
			return FALSE;
		}
		return $all;
	}
	
	/**
	 * get items
	 * 
	 * @param integer value The Tender 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 get_closing_items($value,$cfg,$conn) {
		// get all the items associated with the tender
		$sqlstr = "SELECT ~tender.id, ~tender.classification AS tender_type, ~tender.user_id, ";
		$sqlstr.= "~tender.rfq_number, ~tender.rfq_reference, ~tender.transport, ~tender.created_date, ";
		$sqlstr.= "~tender.created_time, ";
		$sqlstr.= "~tender_item.id AS item_id, ~tender_item.quote AS item_quote, ~tender_item.budget AS item_budget,";
		$sqlstr.= "~tender_item.classification, ";
		$sqlstr.= "~area.name AS area_name, ~area_state.name AS state_name ";
		$sqlstr.= "FROM ~tender, ~tender_item, ~category_sub, ~category, ~area, ~area_state ";
		$sqlstr.= "WHERE ~tender.id = '".$value."' ";
		$sqlstr.= "AND ~tender.status = '2' ";
		$sqlstr.= "AND ~tender.id = ~tender_item.tender ";
		$sqlstr.= "AND ~tender_item.status = '2' ";
		$sqlstr.= "AND ~tender_item.category_sub = ~category_sub.id ";;
		$sqlstr.= "AND ~category_sub.category = ~category.id ";
		$sqlstr.= "AND ~tender.area = ~area.id ";
		$sqlstr.= "AND ~area.state = ~area_state.id ";
		$sqlstr.= "ORDER BY ~tender_item.classification ASC, ~tender_item.id ASC ";
		$new_database = new database;
		$new_database->parse_sql($sqlstr,$cfg);
		// execute the query
 		$all = $conn->GetAll($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);
			// set the response error
			$this->error[] = "1065";
			// response
			return FALSE;
       	} elseif (!$all) {
			// log the error
			$new_error = new error;
			$error_text = "No items could be found while closing tender:".$value;
			$new_error->log("SQL","critical",$error_text,$cfg);
			// response
			return FALSE;
       	} else {
			// set the counter
			$i = 0;
			// loop through array
			foreach($all as $value) {
				// set the tender information
				if ($i == 0) {
					// set stata and area name
					$response['id'] = $value;
					$response['classification'] = $value['tender_type'];
					$response['user']['id'] = $value['user_id'];
					$response['rfq_number'] = $value['rfq_number'];
					$response['rfq_reference'] = $value['rfq_reference'];
					$response['transport'] = $value['transport'];
					$response['created_date'] = $value['created_date'];
					$response['created_time'] = $value['created_time'];
					$response['area'] = $value['area_name'];
					$response['state'] = $value['state_name'];
				}
				// set the item id
				$response['item'][$i]['id'] = $value['item_id'];
				$response['item'][$i]['quote'] = $value['item_quote'];
				$response['item'][$i]['budget'] = $value['item_budget'];
				$response['item'][$i]['classification'] = $value['classification'];
				// increment
				$i++;
			}
			// return tenders id 
			return $response;
		}
	}
	
	function set_language($module,$language,$cfg,$conn) {
		// include the language file
		$lang = array();
		require($cfg['file'].'modules/procure/language/'.$language.'/close.php');
		if($module) {
			require($cfg['file'].'modules/'.$module.'/language/'.$language.'/close.php');
		}
		// set the language
		$this->lang = $lang;
	}
	
	function set_default_language($module,$cfg,$conn) {
		// include the language file
		$lang = array();
		require($cfg['file'].'modules/procure/language/'.$cfg['language'].'/close.php');
		if($module) {
			require($cfg['file'].'modules/'.$module.'/language/'.$cfg['language'].'/close.php');
		}
		// set the language
		$this->default_lang = $lang;
	}
	
	/**
	 * get all the quotes associated with a item
	 * 
	 * @param integer item_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 get_quotes($item_id,$cfg,$conn) {
		// get all the items associated with the tender
		$sqlstr = "SELECT DISTINCT ~tender_quote.id AS quote_id, ~tender_quote.tender_item, ~tender_quote.user_id, ";
		$sqlstr.= "~tender_quote.attachment, ~tender_quote.brand, ~tender_quote.model, ";
		$sqlstr.= "~tender_quote.description, ~tender_quote.stock, ~tender_quote.valid_until, ";
		$sqlstr.= "~tender_quote.price, ~tender_quote.status, ~tender_quote.classification AS quoteclass,";
		$sqlstr.= "~tender_quote.quote_position, ";
		$sqlstr.= "~tender_item.classification, ";
		$sqlstr.= "~attachment.authentication, ~attachment.name ";
		$sqlstr.= "FROM ~tender_quote LEFT JOIN ~attachment ON ~tender_quote.attachment = ~attachment.id, ";
		$sqlstr.= "~tender_item ";
		$sqlstr.= "WHERE ~tender_quote.tender_item = '".$item_id."' ";
		$sqlstr.= "AND (~tender_quote.status = '2' OR ~tender_quote.status = '1') ";
		$sqlstr.= "AND ~tender_quote.tender_item = ~tender_item.id ";
		$sqlstr.= "ORDER BY ~tender_quote.price ASC, ~tender_quote.user_id ASC ";
		$new_database = new database;
		$new_database->parse_sql($sqlstr,$cfg);
		// execute the query
 		$all = $conn->GetAll($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();
			$new_error->log("SQL","critical",$error_text,$cfg);
			// set the response error
			$this->error[] = "1065";
			// response
			return FALSE;
       	}
       	$count = 0;
		// loop through array
		foreach($all as $key => $value) {
			// set the user
			$user = $value['user_id'];
			// set values
			$quote['id'] = $item_id;
			$quote['status'] = $value['status'];
			$quote['itemclassification'] = $value['classification'];
			$quote['quote_id'] = $value['quote_id'];
			$quote['classification'] = $value['quoteclass'];
			$quote['attachment'] = $value['attachment'];
			$quote['brand'] = $value['brand'];
			$quote['model'] = $value['model'];
			$quote['description'] = $value['description'];
			$quote['stock'] = $value['stock'];
			$quote['valid'] = ceil((strtotime($value['valid_until']) - ts_time($cfg)) / 86400);
			$quote['position'] = $value['quote_position'];
			$quote['price'] = $value['price'];
			$quote['authentication'] = $value['authentication'];
			$quote['name'] = $value['name'];
			if(($cfg['tender']['report']['noquotes'] && $value['status'] == "1") || $value['status'] == "2") {
				$this->tender['submitter'][$user]['quote'][] = $quote;
			}
			// update the quote
			if($quote['status'] == "2") {
				$update['status'] = "4";
				$update_quote = $this->update_quote($value['quote_id'],$update,$cfg,$conn);
				$count++;
			}
		}
		// return tenders id 
		return $count;
	}
	
	/**
	 * update quote
	 * 
	 * @param integer quote_id The Tender quote ID
	 * @param array update Update information 
	 * @param mixed cfg The Config settings of tendersystem
	 * @param [ADOConnection] conn The connection to the database
	 *
	 * @param mixed TRUE on success or FALSE on error  
	 */
	function update_quote($quote_id,$update,$cfg,$conn) {
		// if tender status 
		$where.= " id = '".$quote_id."'";
		// response
		return $this->update_tender_quote($update,$where,$cfg,$conn);
	}
	
	/**
	 * set quote 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 process_quotes($type,$tender_id,$cfg,$conn) {
		// get the items
		$this->tender = $this->get_closing_items($tender_id,$cfg,$conn);
		if(!$this->tender) {
			// set error
			$info['status'] = "0";
			$message['type'] = $this->default_lang['messagetype'];
			$message['subject'] = $this->default_lang['close'];
			$message['text'] = $this->default_lang['failclosetender']." ".$tender_id." (".$this->default_lang['noitemfound'].")";
			$message['class'] = "error";
			$this->response['message'][] = $message;
			$where = "id = ".$tender_id;
			$update_tender = $this->update_tender($info,$where,$cfg,$conn);
			return FALSE;
		}
		// get the user information
		$new_user = new user;
		$this->user = $new_user->get_profile($this->tender['user']['id'],$cfg,$conn);
		if(!$this->user) {
			// set error
			$info['status'] = "0";
			require($cfg['file'].'modules/generic/language/'.$cfg['language'].'/error.php');
			$info['error'] = $lang['336'];
			$where = "id = ".$tender_id;
			$update_tender = $this->update_tender($info,$where,$cfg,$conn);
			return FALSE;
		}
		// include the language file
		$this->set_language($type,$this->user['language'],$cfg,$conn);
		// set that tender being processed
		$info['status'] = "3";
		$where = "id = ".$tender_id;
		if(!$this->update_tender($info,$where,$cfg,$conn)) {
			// error in close class
			$this->error = "321";
			return;
		}
		// loop through every item and set to processing
		foreach($this->tender['item'] as $key => $value) {
			// set the status to processing
			$update['status'] = "3";
			$where = "id = ".$value['id'];
			if(!$this->update_tender_item($update,$where,$cfg,$conn)) {
				// error in close class
				$this->error = "321";
				return;
			}
		}
		$item_count = 0;
		// loop through every item and get lowest quote price
		foreach($this->tender['item'] as $key => $value) {
			// remove duplicates
			$this->remove_duplicates($value['id'],$cfg,$conn);
			// get the quotes and set them
			$quote_count = $this->get_quotes($value['id'],$cfg,$conn);
			if(!$quote_count) {
				// no quotes
				$this->tender['item'][$key]['status'] = "0";
				require($cfg['file'].'modules/generic/language/'.$cfg['language'].'/error.php');
				// No quotes
				$this->tender['item'][$key]['error'] = $lang['344'];
			} else {
				// count items
				if($this->tender['item'][$key]['classification'] == "1") {
					$item_count++;
				}
			}
		}
		// loop through every item and set to closed
		foreach($this->tender['item'] as $key => $value) {
			if($value['status'] == "0") {
				// delete tender item
				if(!$this->delete_tender_item($value['id'],$value['error'],$cfg,$conn)) {
					// error in close class
					$this->error = "321";
					return;
				}
			} else {
				// close tender item
				if(!$this->close_tender_item($value['id'],$cfg,$conn)) {
					// error in close class
					$this->error = "321";
					return;
				}
				// calculate position of quotes
				$this->calculate_position($value['id'],$cfg,$conn);
			}
		}
		// send reports
		$send_reports = $this->send_response_report($cfg,$conn);
		// Check for quote that can be labeled completed
		$this->complete_tender_quotes($tender_id,$cfg,$conn);
		// set that processed
		if($item_count > 0) {
			$info['status'] = "4";
			$message['type'] = $this->default_lang['messagetype'];
			$message['subject'] = $this->default_lang['close'];
			$message['text'] = $this->default_lang['succcesclosetender']." ".$tender_id." (".$item_count." ".$this->default_lang['items'].")";
			$message['class'] = "success";
			$this->response['message'][] = $message; 
		} else {
			$message['type'] = $this->default_lang['messagetype'];
			$message['subject'] = $this->default_lang['close'];
			$message['text'] = $this->default_lang['failclosetender']." ".$tender_id." (".$lang['344'].")";
			$message['class'] = "error";
			$this->response['message'][] = $message;
			$info['status'] = "0";
			// No quotes
			$info['error'] = $lang['344'];			
		}
		$where = " id = ".$tender_id;
		$update_tender = $this->update_tender($info,$where,$cfg,$conn);
	}
	
	// empty function that can be overided
	function send_response_report($cfg,$conn) {
		
	}
	
	// empty function that can be overided
	function complete_tender_quotes($tender_id,$cfg,$conn) {
		
	}
}
?>