<?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): __________________.                                                   |
// +---------------------------------------------------------------------------------------+

/**
* Close class
* @package TenderSystem
* @subpackage tender
* @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 tender_close extends procure_close {
	// set the paramaters
	var $email;
	var $tender;
	var $response;
	var $error;
	
	function tender_close() {
		// allow php5 to work
		$this->error = array();	
	}
	
	/**
	 * Close that does everything
	 * 
	 * @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 close($cfg,$conn) {
		// determine if there are any tenders to close
		$tender = $this->unclosed_tenders("tender",$cfg,$conn);
		// include the language file
		$this->set_default_language("tender",$cfg,$conn);
		if (!$tender) {
			$message['type'] = $this->default_lang['messagetype'];
			$message['subject'] = $this->default_lang['close'];
			$message['text'] = $this->default_lang['notenderstoclose'];
			$message['class'] = "success";
			$this->response['message'][] = $message;
			// no tenders to close
			return FALSE;	
		}
		// loop through every tender and close
		foreach ($tender as $value) {
			// process the tenders
			$this->process_quotes("tender",$value['id'],$cfg,$conn);
		}
		// response
		return TRUE;
	}
	
	/**
	 * Send report to agents and subscbriber
	 * 
	 * @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 send_response_report($cfg,$conn) {
		// send out emails
		if(count($this->tender['submitter']) > 0) {
			// loop through every supplier that responded
			foreach ($this->tender['submitter'] as $key => $value) {
				// check if the first only delivery quote
				$quote = end($value['quote']);
				if(count($value['quote']) == "1" && ($quote['itemclassification'] == "3" || $quote['itemclassification'] == "4")) {
					// don't send report and set status to open
					$update_quote['status'] = "2";
					$this->update_quote($quote['quote_id'],$update_quote,$cfg,$conn);
					continue;
				}
				// get the users details
				$submitter['id'] = $key;
				$new_user = new user;
				$this->tender['submitter'][$key] = $new_user->get_profile($submitter,$cfg,$conn);
				// include the language file
				$this->set_language("tender",$this->tender['submitter'][$key]['language'],$cfg,$conn);
				// loop through every quote and populate table rows
				foreach($value['quote'] as $key1 => $value1) {
					$tender_quote = $this->get_tender_quote($value1['quote_id'],$cfg,$conn);
					if($value1['classification'] == "1") {
						// calculate the total values
						$this->tender['submitter'][$key]['total'] += $value1['price'];
					}
					// set row values
					$row_item = $value1;
					$row_item['position'] = $tender_quote['quote_position'];
					// populate the rows
					$html = FALSE;
					require($cfg['file'].'modules/tender/templates/response_row.php');
					$this->tender['submitter'][$key]['row'].= $html;
				}
				// set the item header, total fields and user header
				$html_close = FALSE;
				$html_header = FALSE;
				$html_supplier = FALSE;
				$subject = FALSE;
				require($cfg['file'].'modules/tender/templates/response_header.php');
				$this->tender['submitter'][$key]['row'] = $html_header.$this->tender['submitter'][$key]['row'].$html_close;
				$this->user['row'].= $html_supplier."<td class=\"h2b\" colspan=\"8\">".$this->tender['submitter'][$key]['row']."</td></tr></table><br/>";
				if($cfg['tender']['close']['agent']) {
					// populate the supplier email
					require($cfg['file'].'modules/tender/templates/response_supplier.php');
					// set message paramaters
					$message['reference'] = $this->tender['rfq_number'];
					$message['classification'] = "report";
					$message['subject'] = $subject;
					$message['body'] = $html;
					$message['name'] = $this->tender['submitter'][$key]['name']." ".$this->tender['submitter'][$key]['surname'];
					$message['email'] = $this->tender['submitter'][$key]['email'];
					// send the email
					$new_message = new message;
					$message_id = $new_message->send_email_message($message,$this->tender['submitter'][$key]['id'],"0",$cfg,$conn);
					if (!$message_id) {
						// error handling
						$error_text = $this->default_lang['emailerror'];
						$error_text.= "Reason: ".$new_message->error_text;
						$this->response['errortext'].= $error_text."&#10;";
						// continue with next agent
						continue;
					}
				}
			}			
		}
		$this->set_language("tender",$this->user['language'],$cfg,$conn);
		// populate the user email
		require($cfg['file'].'modules/tender/templates/response_user.php');
		// set message paramaters
		$message['reference'] = $this->tender['rfq_number'];
		$message['classification'] = "report";
		$message['subject'] = $subject;
		$message['body'] = $html;
		$message['name'] = $this->user['name']." ".$this->user['surname'];
		$message['email'] = $this->user['email'];
		// send the email
		$new_message = new message;
		$message_id = $new_message->send_email_message($message,$this->user['id'],"0",$cfg,$conn);
		if (!$message_id) {
			// error handling
			$error_text = $this->default_lang['emailerror'];
			$error_text.= "Reason: ".$new_message->error_text;
			$this->response['errortext'].= $error_text."&#10;";
		}
	}
	
	/**
	 * 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' ";
		$sqlstr.= "AND (~tender_quote.classification = '1' OR  ~tender_quote.classification = '4') ";
		$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['quoteclass'] == "4") || $value['quoteclass'] == "1") {
				$this->tender['submitter'][$user]['quote'][] = $quote;
			}
			// update the quote
			if($quote['classification'] == "1") {
				$update['status'] = "4";	
				$count++;
			} else {
				$update['status'] = "0";
			}
			$update_quote = $this->update_quote($value['quote_id'],$update,$cfg,$conn);
		}
		// return tenders id 
		return $count;
	}
}
?>