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

/**
* Award tender
* @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...");
}

// instantiate the xml object
$new_xml = new xml;
// administrator is requesting tender on behalf of user
$required[0]['classification'] = "3";
$required[0]['permission'] = "all";
// subscriber
$required[1]['classification'] = "2";
$required[1]['permission'] = "all";
// Security - determine if user authorised to perform transaction
$authorised = $new_security->permission_authentication($type,$permission,$user,$cfg);
// unauthorised user
if (!$authorised) {
	// instantiate the error class
	$new_error = new error;
	// proses the reponse error
	$xml = $new_error->response_xml($new_security->error,$user,$cfg);
} elseif (!$cfg['tender']['enable']) {
	// e54 - Tender module is disabled
	$xml = $new_xml->xml_generator("tender","error","e54",$xml_params,$user,$cfg);
} else {
	// load required files
	require($cfg['file'].'modules/procure/config.inc.php');
	require($cfg['file'].'modules/tender/config.inc.php');
	if($cfg['procure']['client']['phone_prefix']) {
		$xml_params['enablephone_prefix'] = '1';
	} else {
		$xml_params['enablephone_prefix'] = '0';
	}
	require($cfg['file'].'modules/procure/class/procure.class.php');
	require($cfg['file'].'modules/procure/class/procure_award.class.php');
	require($cfg['file'].'modules/tender/class/tender_award.class.php');
	require($cfg['file'].'modules/generic/class/message.class.php');
	require($cfg['file'].'modules/external/class/smtp/htmlMimeMail.php');
	if ($user['classification'] != "3") {
		// set that normal user requesting tender
		$params['usersid'] = $user['id'];
	}
	$xml_params['tenderexcess'] = $cfg['tender']['excess'];
	$xml_params['tendersalvage'] = $cfg['tender']['salvage'];
	// instantiate object
	$new_users = new user;
	$new_org = new organisation;
	$new_award = new tender_award;
	// tender_items to be submitted
	if(is_array($params['tender_item'])) {
		if(!is_array($params['noinstall'])) {
			$params['noinstall'] = array();
		}
		if(!is_array($params['nodeliver'])) {
			$params['nodeliver'] = array();
		}
		foreach($params['tender_item'] as $tenderitem => $tenderquote) {	
			// get item information	
			$item = $new_award->get_tender_item($tenderitem,$cfg,$conn);
			// get tender information
			$tender = $new_award->get_tender($item['tender'],$cfg,$conn);
			if($tender['status'] != "4" || $item['status'] != "4") {
				continue;
			} elseif($tenderquote == "cash") {
				// cash settlement
				$xml_params['cashtender_item'][$item['id']] = $item;
				$xml_params['tender'][$tender['id']] = $tender;
			} elseif ($tenderquote == "nontender") {
				// non tender supplier
				$xml_params['nontender_item'][$item['id']] = $item;
				$xml_params['tender'][$tender['id']] = $tender;
			} elseif ($tenderquote == "invalidate") {
				// invalidate tender
				$xml_params['invalidatetender_item'][$item['id']] = $item;
				$xml_params['tender'][$tender['id']] = $tender;
			} else {
				// add tender_quote
				$new_award->add_award_tender($xml_params,$params,$tender,$tenderquote,$cfg,$conn);
				// check if administrator
				if($user['classification'] == "3") {
					// get the user organisation id
					$on_behalf['id'] = $xml_params['awardtender'][$tender['id']]['user_id'];
					$new_user = new user;
					$on_behalf = $new_user->get_profile($on_behalf,$cfg,$conn);
					$info['searchinfo']['classification'] = "2";
					$info['searchinfo']['organisationid'] = $on_behalf['organisationid'];
					$info['searchinfo']['extrainfo'] = TRUE;
					// get subscribers this tender can be awarded on behalf of
					$award_tender_users = $new_users->search($info,$cfg,$conn);
					// limit xml to name, surname, and id
					for($m = 0; $m < count($award_tender_users); $m++) {
						$xml_params['awardtender'][$item['tender']]['users'][$m]['usersid'] = $award_tender_users[$m]['usersid'];
						$xml_params['awardtender'][$item['tender']]['users'][$m]['name'] = $award_tender_users[$m]['name']; 	
						$xml_params['awardtender'][$item['tender']]['users'][$m]['surname'] = $award_tender_users[$m]['surname'];
					}					
					
				} else {
					// set the awarder
					$xml_params['usersid'] = $user['id'];
				}
				if ($cfg['tender']['award']['awardtoself']) {
					$xml_params['awardtoself'] = "1";					

					// set for no tender excess
					$xml_params['tenderexcess'] = '0';
				}	
			}
		}
		// join errors
		if(!empty($new_users->error)) {
			$errors = array_merge($errors,$new_users->error);
		} 
		if(!empty($new_award->error)) {
			$errors = array_merge($errors,$new_award->error);
		}
		if(!empty($new_org->error)) {
			$errors = array_merge($errors,$new_org->error);
		} 	
		$xml = $new_xml->xml_generator("tender","award",$errors,$xml_params,$user,$cfg);
	} 
	// sumbiting tender_items
	elseif($params['award_item'] || $params['cashtender_item'] || $params['nontender_item'] || $params['invalidatetender_item']) {
		// update client information
		if ($cfg['tender']['award']['awardtoself']) {
			if(is_array($params['usersid'])) {
				foreach($params['usersid'] as $key => $value) {
					// get user info
					$new_user_info = new user;
					if ($user['classification'] == "3") {
						$users_id = $value;	
					} else {
						$users_id = $user['id'];
					}					 
					$user_info = $new_user_info->get_profile($users_id,$cfg,$conn);		
					$update_client['id_number'] = $user_info['id'] ;
					$update_client['surname'] = $user_info['surname'];
					$update_client['phone_prefix'] = $user_info['phone_prefix'];
					$update_client['phone_work'] = $user_info['phone_work'];
					$update_client['phone_fax'] = $user_info['phone_fax'];
					$update_client['phone_mobile'] = $user_info['phone_mobile'];
					$update_client['email'] = $user_info['email'];
					$update_client['tender'] = $key; 
					$update_client['status'] = "1";
					$update_client['created_by'] = $user['id'];					
					// get address
					$branch = new branch;
					$branch_info = $branch->get_profile($user_info['branchid'],$cfg,$conn);
					$update_client["address"] = $branch_info['alt_address_street']."\r\n".$branch_info['alt_address_city']."\r\n".$branch_info['alt_address_state'];
					
					// create client information
					$new_award->create_tender_client($update_client,$cfg,$conn);
				}
			}		
		} elseif(is_array($params['title'])) {
			foreach($params['title'] as $key => $value) {
				$update_client['tender'] = $key; 
				$update_client['status'] = "1";
				$update_client['created_by'] = $user['id'];
				$client_info = array("title","id_number","surname","phone_prefix","phone_work","phone_fax","phone_mobile","email","address");
				foreach($client_info as $c_value) {
					if($params[$c_value][$key]) {
						$update_client[$c_value] = $params[$c_value][$key];
					} else {
						unset($update_client[$c_value]);	
					}
				}
				if(!$update_client['title'] || !$update_client['surname']) {
					// 1058 - Missing Client Information
					$errors[] = "1058";
					$bad = TRUE;
					break;	
				}
				// create client information
				$new_award->create_tender_client($update_client,$cfg,$conn);
			}
		}
		if($bad) {
			// error
			$xml = $new_xml->xml_generator("tender","error",$errors,$xml_params,$user,$cfg);
		} else {
			// award tenders
			if(is_array($params['award_item'])) {
				// award items
				$lock_tender = $new_award->do_award_item($xml_params,$params,$user,"tender",$cfg,$conn);
			}
			// invalidate tender items
			if(is_array($params['invalidatetender_item'])) {
				foreach($params['invalidatetender_item'] as $tender_item_id => $tender_id) {
					$item = $new_award->do_complete_item($tender_item_id,$user['id'],$params['invalidate'],array(),array(),"4",$cfg,$conn);
					if($item) {
						$lock_tender[] = $item['tender'];
					}
					$xml_params['invalidatetender_item'][] = $item;
				}
			}
			// cash tender items
			if(is_array($params['cashtender_item'])) {
				foreach($params['cashtender_item'] as $tender_item_id => $tender_id) {
					$item = $new_award->do_complete_item($tender_item_id,$user['id'],$params['cash'],$params['cashamount'],array(),"3",$cfg,$conn);
					if($item) {
						$lock_tender[] = $item['tender'];
					}
					$xml_params['cashtender_item'][] = $item;
				}
			}
			// non tender supplier items
			if(is_array($params['nontender_item'])) {
				foreach($params['nontender_item'] as $tender_item_id => $tender_id) {
					$item = $new_award->do_complete_item($tender_item_id,$user['id'],$params['nontender'],$params['nontenderamount'],$params['nontendername'],"2",$cfg,$conn);
					if($item) {
						$lock_tender[] = $item['tender'];
					}
					$xml_params['nontender_item'][] = $item;
				}
			}
			// check for completed tenders
			$new_award->check_tender_complete($xml_params,$lock_tender,$cfg,$conn);
			// join errors
			if(!empty($new_award->error)) {
				$errors = array_merge($errors,$new_award->error);
			}
			// join errors
			if(!empty($new_message->error)) {
				$errors = array_merge($errors,$new_message->error);
			}
			// join errors
			if(!empty($new_users->error)) {
				$errors = array_merge($errors,$new_users->error);
			}
						
			// determine if any other tenders must be awarded
			require_once($cfg['file'].'modules/procure/class/procure_update.class.php');
			require_once($cfg['file'].'modules/tender/class/tender_update.class.php');
			// determine if requested by administrator
			if ($user['classification'] == "3" && $params['usersid']) {
				/*
				 * @todo rewrite this section in the future
				 */
				foreach ($params['usersid'] as $key => $value) {
					$display['id'] = $value;
					continue;
				}
				// get the users information
				$new_user = new user;
				$subscriber_information = $new_user->get_profile($display['id'],$cfg,$conn);
				$xml_params['subscriber_organisation_id'] = $subscriber_information['organisationid'];
				$display['classification'] = "2";
				$display['permission'] = "1";
			} else {
				$display = $user;
			}
			if ($display) {
				$xml_params['localdisplay'] = $cfg['local']['display'];
				$new_update = new tender_update;
				$xml_params['opentenders'] = $new_update->get_tender_for_subscriber("tender",NULL,"4",$display,$cfg,$conn);
			}
			
			
			$xml = $new_xml->xml_generator( "tender", "awarded",$errors,$xml_params,$user,$cfg);
		}
	} else {
		$xml = $new_xml->xml_generator( "generic", "error",$errors,$xml_params,$user,$cfg);
	}
}
?>