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

/**
* Rating class
* @package TenderSystem
* @subpackage rating
* @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 rating {
	
	function rating() {
		// allow php5 to work
		$this->error = array();	
	}
	
	function create_supplier_rating($supplier,$usersid,$rating,$user,$cfg,$conn) {
		if (!$supplier){
			// 1034 - Missing Supplier ID
			$this->error[] = "1034";
		}
		if (!$usersid){
			// 1038 Missing organisation id
			$this->error[] = "1038";
		}
		// errors 
		if(!empty($this->error)){
			return FALSE;
		}
		$new_database = new database;
		$table_name = "~supplier_rating";
		$rating['supplier'] = $supplier;
		$rating['user_id'] = $usersid;
		$rating['created_by'] = $user['id'];
		$rating['status'] = '1';
		$rating['first_rate'] = max(min($cfg['rating']['outof'],$rating['first_rate']),0);
		$rating['second_rate'] = max(min($cfg['rating']['outof'],$rating['second_rate']),0);
		$rating['third_rate'] = max(min($cfg['rating']['outof'],$rating['third_rate']),0);
		$rating['fourth_rate'] = max(min($cfg['rating']['outof'],$rating['fourth_rate']),0);
		$rating['fifth_rate'] = max(min($cfg['rating']['outof'],$rating['fifth_rate']),0);
		if(!$rating['rating_comment']) {
			$rating['rating_comment'] = "";
		}
		// no id 
		if(!$rating['id']) {
			// generate an id 
			$rating['id'] = $new_database->get_next_id($table_name,$cfg,$conn);
		}
		$new_database->setTime("created",$rating,"",$cfg);
		$new_database->parse_sql($table_name,$cfg);
		// create sql string 
		$conn->AutoExecute($table_name,$rating,"INSERT");
      	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 inserting into Database
			$this->error[] = "1064";
			// response
			return FALSE;
      	}
      	$this->calculate_supplier_rating($supplier,$cfg,$conn);
		// resturn the id
		return $rating['id'];
	}
	
	function calculate_supplier_rating($supplier,$cfg,$conn) {
		// sqlstr
		$sqlstr = "SELECT ~supplier_rating.first_rate, ~supplier_rating.second_rate, ~supplier_rating.third_rate, ";
		$sqlstr.= "~supplier_rating.fourth_rate, ~supplier_rating.fifth_rate ";
		$sqlstr.= "FROM ~organisation, ~supplier_rating ";
		$sqlstr.= "WHERE ~organisation.status = '1' ";
		$sqlstr.= "AND ~supplier_rating.supplier = ~organisation.id ";
		$sqlstr.= "AND ~supplier_rating.status = '1' ";
		$sqlstr.= "AND ~organisation.id = '".$supplier."'  ";
		$sqlstr.= "ORDER BY ~supplier_rating.id DESC ";
		$new_database = new database;
		$new_database->parse_sql($sqlstr,$cfg);
		$result = $conn->SelectLimit($sqlstr,$cfg['rating']['use']['votes'] ,0);
		if($result) {
			$all = $result->GetRows();
		}
		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;
		} elseif($cfg['rating']['min']['count'] > count($all)) {
			// response
			return TRUE;
		}
		foreach($all as $key => $value) {
			// calculate sums
			if($value['first_rate']) {
				$response['total_sum'] += $value['first_rate'];
				$response['total_count']++;
			}
			if($value['second_rate']) {
				$response['total_sum'] += $value['second_rate'];
				$response['total_count']++;
			}
			if($value['third_rate']) {
				$response['total_sum'] += $value['third_rate'];
				$response['total_count']++;
			}
			if($value['fourth_rate']) {
				$response['total_sum'] += $value['fourth_rate'];
				$response['total_count']++;
			}
			if($value['fifth_rate']) {
				$response['total_sum'] += $value['fifth_rate'];
				$response['total_count']++;
			}
		}
		$new_organisation = new organisation;
		$org['update']['supplier_rating'] = round($response['total_sum'] / $response['total_count'],2);
		$org['where'] = "status = '1' AND id = ".$supplier;
		if(!$new_organisation->update_organisation($org,$cfg,$conn)) {
			$this->error = array_merge($this->error,$new_organisation->error);
			return FALSE;	
		}
		return TRUE;
	}
	
	/**
	 * Search for company on panel
	 * 
	 * @param integer supplier Supplier Organisation ID
	 * @param mixed cfg The Config settings of tendersystem
	 * @param [ADOConnection] conn The connection to the database
	 *
	 * @param mixed A array with the suppliers or FALSE on error  
	 */
	function get_supplier_rating($supplier,$cfg,$conn) {
		// sqlstr
		$sqlstr = "SELECT ~organisation.supplier_rating ";
		$sqlstr.= "FROM ~organisation ";
		$sqlstr.= "WHERE ~organisation.status = '1' ";
		$sqlstr.= "AND ~organisation.id = '".$supplier."'  ";
		$new_database = new database;
		$new_database->parse_sql($sqlstr,$cfg);
		$row = $conn->GetRow($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();
			$new_error->log("SQL","critical",$error_text,$cfg);
			// error occurred while querying into database 
			$this->error[] = "1065";
			// response
			return FALSE;
		} 
		return $row;
	}
	
	/**
	 * Search for company on panel
	 * 
	 * @param integer supplier Supplier Organisation ID
	 * @param mixed cfg The Config settings of tendersystem
	 * @param [ADOConnection] conn The connection to the database
	 *
	 * @param mixed A array with the suppliers or FALSE on error  
	 */
	function get_supplier_panel_ratings($organisation,$cfg,$conn) {
		// sqlstr
		$sqlstr = "SELECT DISTINCT ~organisation.supplier_rating, ~organisation.id, ~organisation.supplier_rating ";
		$sqlstr.= "FROM ~organisation, ~organisation_supplier  ";
		$sqlstr.= "WHERE ~organisation.status = '1' ";
		$sqlstr.= "AND ~organisation_supplier.supplier = ~organisation.id ";
		$sqlstr.= "AND ~organisation_supplier.status = '1' ";
		$sqlstr.= "AND ~organisation_supplier.organisation = '".$organisation."'  ";
		$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();
			$new_error->log("SQL","critical",$error_text,$cfg);
			// error occurred while querying into database 
			$this->error[] = "1065";
			// response
			return FALSE;
		}
		// insert organisation name
		$new_org = new organisation;
		foreach($all as $key => $value) {
			$info = $new_org->get_info($value['id'],$cfg,$conn);
			$all[$key]['name'] = $info['name'];
		}
		return $all;
	}
	
	/**
	 * Search for company on panel
	 * 
	 * @param integer supplier Supplier Organisation ID
	 * @param mixed cfg The Config settings of tendersystem
	 * @param [ADOConnection] conn The connection to the database
	 *
	 * @param mixed A array with the suppliers or FALSE on error  
	 */
	function get_rating_info($supplier,$cfg,$conn) {
		// available ratings
		for($i = 1; $i <= $cfg['rating']['outof']; $i++) {
			$response['rating'][] = $i;
		}
		// sqlstr
		$sqlstr = "SELECT ~organisation.id, ";
		$sqlstr.= "~supplier_rating.first_rate, ~supplier_rating.second_rate, ~supplier_rating.third_rate, ";
		$sqlstr.= "~supplier_rating.fourth_rate, ~supplier_rating.fifth_rate, ~supplier_rating.rating_comment, ";
		$sqlstr.= "~supplier_rating.user_id AS usersid,  ~supplier_rating.created_date, ~supplier_rating.created_time ";
		$sqlstr.= "FROM ~organisation, ~supplier_rating ";
		$sqlstr.= "WHERE ~organisation.status = '1' ";
		$sqlstr.= "AND ~supplier_rating.supplier =  ~organisation.id ";
		$sqlstr.= "AND ~supplier_rating.status =  '1' ";
		$sqlstr.= "AND ~organisation.id = '".$supplier."'  ";
		$sqlstr.= "ORDER BY ~supplier_rating.id DESC ";
		$new_database = new database;
		$new_database->parse_sql($sqlstr,$cfg);
		$response['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();
			$new_error->log("SQL","critical",$error_text,$cfg);
			// error occurred while querying into database 
			$this->error[] = "1065";
			// response
			return FALSE;
		} elseif(empty($response['all'])) {
			return $response;
		} 
		// change time to proper format
		$new_database->convertTime($response['all'],$cfg);
		// insert subscriber name
		$new_users = new user;
		foreach($response['all'] as $key => $value) {
			$userinfo = $new_users->get_info($value['usersid'],$cfg,$conn);
			$response['all'][$key]['name'] = $userinfo['name'];
			$response['all'][$key]['surname'] = $userinfo['surname'];
			$response['all'][$key]['email'] = $userinfo['email'];
			$response['all'][$key]['phone_work'] = $userinfo['phone_work'];
			$response['all'][$key]['phone_prefix'] = $userinfo['phone_prefix'];
			// calculate sums
			if($value['first_rate']) {
				$response['first_sum'] += $value['first_rate'];
				$response['first_count']++;
			}
			if($value['second_rate']) {
				$response['second_sum'] += $value['second_rate'];
				$response['second_count']++;
			}
			if($value['third_rate']) {
				$response['third_sum'] += $value['third_rate'];
				$response['third_count']++;
			}
			if($value['fourth_rate']) {
				$response['fourth_sum'] += $value['fourth_rate'];
				$response['fourth_count']++;
			}
			if($value['fifth_rate']) {
				$response['fifth_sum'] += $value['fifth_rate'];
				$response['fifth_count']++;
			}
		}
		// calculate all averages
		foreach(array("first","second","third","fourth","five") as $value) {
			// calcuate
			if($response[$value.'_count']) {
				$response[$value.'_avg'] = round($response[$value.'_sum'] / $response[$value.'_count'],2);
			} else {
				$response[$value.'_avg'] = "0";
			}
		} 
		return $response;
	}
	
	/* email rating and comment to supplier *
	 * @param integer supplier Supplier Organisation ID
	 * @param integer user id for user submitting rating
	 * @param integer user id for user submitting rating on behalf of another user, null is none 	  
	 * @param array rating
	 * @param mixed cfg The Config settings of tendersystem	 	
	 * @param [ADOConnection] conn The connection to the database
	 * @param mixed message id on success or FALSE on error  
	 */
	function email_supplier($supplier,$userid,$onbehalf,$rating,$cfg,$conn) {
		$user_info = new user;
		$user_info = $user_info->get_info($userid,$cfg,$conn); 				
		require($cfg['file'].'modules/rating/language/'.$user_info['language'].'/rating.php');
		require_once($cfg['file'].'modules/rating/class/rating.class.php');
		$rating['first_rate'] = max(min($cfg['rating']['outof'],$rating['first_rate']),0);
		$rating['second_rate'] = max(min($cfg['rating']['outof'],$rating['second_rate']),0);		
		if(!$rating['first_rate'] || $rating['first_rate'] == "0.00") {
			$rating['first_rate'] = $lang['notrated'];
		} else {
			$rating['first_rate'] = $rating['first_rate']." ".$lang['outof']." ".$cfg['rating']['outof'];
		}
		if(!$rating['second_rate'] || $rating['second_rate'] == "0.00") {
			$rating['second_rate'] = $lang['notrated'];
		} else {
			$rating['second_rate'] = $rating['second_rate']." ".$lang['outof']." ".$cfg['rating']['outof'];
		}
		$new_rating_value = $this->get_supplier_rating($supplier,$cfg,$conn);
		if(!$new_rating_value['supplier_rating'] || $new_rating_value['supplier_rating'] == "0.00") {
			$new_rating_value = $lang['notrated'];
		} else {
			$new_rating_value = $new_rating_value['supplier_rating']." ".$lang['outof']." ".$cfg['rating']['outof'];
		}
		// set message paramaters
		$message['reference'] = $user_info['id'];
		$message['classification'] = "rating";
		require_once($cfg['file'].'modules/organisation/class/organisation.class.php');
		$new_organisation = new organisation;
		// get supplier organisation name
		$suppliername = $new_organisation->get_name($supplier,$cfg,$conn);
		// get subscriber organisation name
		$orgname = $new_organisation->get_name($user_info['organisation'],$cfg,$conn);
		require_once($cfg['file'].'modules/branch/class/branch.class.php');
		// get branch name
		$new_branch = new branch;
		$searchinfo['searchinfo']['branchid'] = $user_info['branch'];
		$branch_info =  $new_branch->search($searchinfo,$cfg,$conn);
		$branchname = $branch_info[0]['branchname'];
		if ($onbehalf) { 
			$onbehalf_user = new user;
			$onbehalf_user = $onbehalf_user->get_info($onbehalf,$cfg,$conn);
		}		
		require($cfg['file'].'modules/rating/template/rating_email.php');
		$message['subject'] = $subject;
		$message['body'] = $html;
		$params['searchinfo']['organisationid'] = $supplier;
		$params['searchinfo']['extrainfo'] = "1";				
		// instantiate object
		$new_user = new user;
		// get agents
		$agents = $new_user->search($params,$cfg,$conn);
		// require message class
		require_once($cfg['file'].'modules/generic/class/message.class.php');
		foreach($agents as $agent_info)	{
			$message['name'] = $agent_info['name']." ".$agent_info['surname'];
			$message['email'] = $agent_info['email'];
			if ($agent_info['preference'] == 'm'  || $agent_info['preference'] == 'n') {
				// send the email
				$new_message = new message;
				$id = $new_message->send_email_message($message,$agent_info['usersid'],$user_info['id'],$cfg,$conn);
				if(!$id) {
					$this->email_error[] = $new_message->error_text;
					return FALSE;
				}
			}
		}
	}		
}
?>