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

/**
* @package TenderSystem
* @subpackage report
* @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;
// set the required type and permission required
$required['classification'] = array("2","3");
$required['permission'] = "all";
// Security - determine if user authorised to perform transaction
$authorised = $new_security->permission_authentication($required,$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(is_array($params['error'])) {
	// generate xml 
	$xml = $new_xml->xml_generator("report","company",$params['error'],"",$user,$cfg);
} else {
	require($cfg['file'].'modules/area/class/area.class.php');
	require($cfg['file'].'modules/report/class/report.class.php');
	require($cfg['file'].'modules/generic/class/file.class.php');
	/**
	 * @todo Rewrite reports to move more of the code into the class
	 */
	// instantiate objects
	$new_branch = new branch;
	$new_area = new area;
	$new_users = new user;
	$new_file = new file;
	$xml_params['daysago3'] = date("Y-m-d",ts_time($cfg) - 259200);
	$xml_params['today'] = date("Y-m-d");
	if(!$params['organisationid']) {
		$params['organisationid'] = $user['organisation'];
	}
	$xml_params['organisationid'] = $params['organisationid'];
	if($cfg['report']['ajax']['status']) {
		$xml_params['reportajaxstatus'] = "1";
	}
	if($params['reportinfo']) {
		// permission checks
		if($user['classification'] == "2") {
			if($user['permission'] == "1") {
				$params['reportinfo']['usersid'] = $user['id'];
			} elseif($user['permission'] == "2") {
				$params['reportinfo']['branchid'] = $user['branch'];	
			} else {
				$params['reportinfo']['organisationid'] = $user['organisation'];
			}
		} else {
			$params['reportinfo']['organisationid'] = $params['organisationid'];
		}
		$info['searchinfo'] = $params['reportinfo'];
		$xml_params['reportinfo'][0] = $params['reportinfo'];
			
		if($params['reportinfo']['group'] == "branch") {
			$xml_params['branch'] = $new_branch->search($info,$cfg,$conn);
		} elseif($params['reportinfo']['group'] == "users") {
			$info['searchinfo']['extrainfo'] = "1";
			$xml_params['users'] = $new_users->search($info,$cfg,$conn);
		}
		// check for start_date
		if(!$params['reportinfo']['startdate']) {
			// make one year ago
			$params['reportinfo']['startdate'] = date("Y-m-d",ts_time($cfg) - 31536000);
		}
		// check for end date
		if(!$params['reportinfo']['enddate']) {
			// make today
			$params['reportinfo']['enddate'] = date("Y-m-d",ts_time($cfg));
		}
		// set
		list($year,$month,$day) = sscanf(str_replace(array("-"," "),"",$params['reportinfo']['startdate']),'%4s%2s%2s');
		$xml_params['startdate'] = date($cfg['date']['format'],mktime("0","0","0",$month,$day,$year));
		list($year,$month,$day) = sscanf(str_replace(array("-"," "),"",$params['reportinfo']['enddate']),'%4s%2s%2s');
		$xml_params['enddate'] = date($cfg['date']['format'],mktime("0","0","0",$month,$day,$year));
		// audit trail report
		if($params['reportinfo']['reporttype'] == "audit") {
			// instantiate object
			$new_report = new report;
			$xml_params['tender'] = $new_report->search_audit($info,$cfg,$conn);
			$timestamp = date($cfg['date']['format'],ts_time($cfg));
			for($i = 0; $i < count($xml_params['tender']); $i++) {
				// check create time
				if($xml_params['tender'][$i]['created_date'] == $timestamp) {
					$xml_params['tender'][$i]['created_on'] = $xml_params['tender'][$i]['created_time'];
				} else {
					$xml_params['tender'][$i]['created_on'] = $xml_params['tender'][$i]['created_date']." " .$xml_params['tender'][$i]['created_time'];
				}
 			}
 			// find dynamicaly added report
			$new_file->link_api_find("report","company",$xml_params,$user,$cfg,$conn);
			// generate xml
			$xml = $new_xml->xml_generator("report","audit",$new_report->error,$xml_params,$user,$cfg);
		} elseif($params['reportinfo']['reporttype'] == "bordereaux") {
			// instantiate object
 			$new_report = new report;
 			$xml_params['tender_quote'] = $new_report->search_bordereaux($info,$cfg,$conn);
 			if(!empty($xml_params['tender_quote'])) {
				$tender_count = 0;
				foreach($xml_params['tender_quote'] as $key => $value) {
					// if first sum for agent
					if(!$xml_params['agent_sum'][$value['agentid']]['id']) {
						$userinfo = $new_users->get_info($value['agentid'],$cfg,$conn);
						$xml_params['agent_sum'][$value['agentid']]['id'] = $value['agentid'];
						$xml_params['agent_sum'][$value['agentid']]['name'] = $userinfo['name'];
						$xml_params['agent_sum'][$value['agentid']]['surname'] = $userinfo['surname'];
						$xml_params['agent_sum'][$value['agentid']]['invoice'] = 0;
						$xml_params['agent_sum'][$value['agentid']]['payment']= 0;
						$xml_params['agent_sum'][$value['agentid']]['paid']= 0;
					}
					// agent calculations
					$xml_params['agent_sum'][$value['agentid']]['awarded']+= $value['price'];
					if (!$value['invoice_user']) {
						$xml_params['agent_sum'][$value['agentid']]['invoice']+= $value['price'];
					} elseif (!$value['payment_user']) {
						$xml_params['agent_sum'][$value['agentid']]['payment']+= $value['price'];
					} else {
						$xml_params['agent_sum'][$value['agentid']]['paid']+= $value['price'];
					}
					// first time for tender
					if(!$tender_counter[$value['tenderid']][$value['agentid']][$value['complete_order']]) {
						$num = $tender_counter[$value['tenderid']][$value['agentid']][$value['complete_order']] = ++$tender_count;
						$xml_params['tender_sum'][$num]['id'] = $value['tenderid'];
						$xml_params['tender_sum'][$num]['agentid'] = $value['agentid'];
						$xml_params['tender_sum'][$num]['purchase_order'] = $value['purchase_order'];
						$xml_params['tender_sum'][$num]['rfq_number'] = $value['rfq_number'];
						$xml_params['tender_sum'][$num]['total'] = 0;
						$xml_params['tender_sum'][$num]['payable']-=$xml_params['tender_sum'][$num]['excess'] =  $value['client_excess'];
					} else {
						$num = $tender_counter[$value['tenderid']][$value['agentid']][$value['purchase_order']];
					}
					// tender calculations
					$xml_params['tender_sum'][$num]['payable']+=$xml_params['tender_sum'][$num]['total']+= $value['price'];
				}
				foreach($xml_params['agent_sum'] as $key => $value) {
					$xml_params['total_sum'][0]['awarded']+= $value['awarded'];
					$xml_params['total_sum'][0]['invoice']+= $value['invoice'];
					$xml_params['total_sum'][0]['payment']+= $value['payment'];
					$xml_params['total_sum'][0]['paid']+= $value['paid'];
				}
 			}
 			// find dynamicaly added report
			$new_file->link_api_find("report","company",$xml_params,$user,$cfg,$conn);
			// generate xml
			$xml = $new_xml->xml_generator("report","bordereaux",$new_report->error,$xml_params,$user,$cfg);
		}
		// close tenders, comma separted
		elseif($params['reportinfo']['reporttype'] == "close" && $params['reportinfo']['reportformat'] != "online") {
			// instantiate object
			$new_report = new report;
			$info['searchinfo'] = $params['reportinfo'];
			require($cfg['file'].'modules/external/class/adodb/toexport.inc.php');
			$tender = $new_report->search_close($info,$cfg,$conn);
			$xml_params['data'] = serialize($tender);
			//	generate xml
			$xml = $new_xml->xml_generator( "report", "close",$new_report->error,$xml_params,$user,$cfg);
		}
		// close tenders
		elseif($params['reportinfo']['reporttype'] == "close") {
			// instantiate object
			$new_report = new report;
			$info['searchinfo'] = $params['reportinfo'];
			$xml_params['tender'] = $new_report->search_close($info,$cfg,$conn);
			for($i = 0; $i < count($xml_params['tender']); $i++) {
				$branchid = $xml_params['tender'][$i]['branchid'];
				$usersid = $xml_params['tender'][$i]['usersid'];
				$timestamp = ts_time($cfg);
				// round of std_dev
				$xml_params['tender'][$i]['std_dev'] = sprintf("%.2f",$xml_params['tender'][$i]['std_dev']);
				// check quote
				if($xml_params['tender'][$i]['quote'] <= 0) {
					$xml_params['tender'][$i]['quote'] = "N/Q";
					$xml_params['tender'][$i]['saving'] = "N/Q";
					$xml_params['tender'][$i]['saving_percent'] = "N/Q";
					// total noquote price
					$xml_params['all'][0]['noquoteprice'] += $xml_params['tender'][$i]['bestprice'];
					$xml_params['branch_calc'][$branchid]['noquoteprice'] += $xml_params['tender'][$i]['bestprice'];
					$xml_params['users_calc'][$usersid]['noquoteprice'] += $xml_params['tender'][$i]['bestprice'];
				} elseif($xml_params['tender'][$i]['quote'] < $xml_params['tender'][$i]['bestprice']) {
					$xml_params['tender'][$i]['saving'] = "0";
					$xml_params['tender'][$i]['saving_percent'] = "0";
					// total noquote price
					$xml_params['all'][0]['noquoteprice'] += $xml_params['tender'][$i]['bestprice'];
					$xml_params['branch_calc'][$branchid]['noquoteprice'] += $xml_params['tender'][$i]['bestprice'];
					$xml_params['users_calc'][$usersid]['noquoteprice'] += $xml_params['tender'][$i]['bestprice'];
				} else {
					$xml_params['all'][0]['quote']+= $xml_params['tender'][$i]['quote'];
					$xml_params['branch_calc'][$branchid]['quote']+= $xml_params['tender'][$i]['quote'];
					$xml_params['users_calc'][$usersid]['quote']+= $xml_params['tender'][$i]['quote'];
					$xml_params['all'][0]['saving']+= $xml_params['tender'][$i]['saving'];
					$xml_params['branch_calc'][$branchid]['saving']+= $xml_params['tender'][$i]['saving'];
					$xml_params['users_calc'][$usersid]['saving']+= $xml_params['tender'][$i]['saving'];
					$xml_params['tender'][$i]['saving_percent'] = round($xml_params['tender'][$i]['saving']/$xml_params['tender'][$i]['quote'] * 100,2);
				}
				$xml_params['all'][0]['bestprice']+= $xml_params['tender'][$i]['bestprice'];
				$xml_params['branch_calc'][$branchid]['bestprice']+= $xml_params['tender'][$i]['bestprice'];
				$xml_params['users_calc'][$usersid]['bestprice']+= $xml_params['tender'][$i]['bestprice'];
				
				$xml_params['all'][0]['transaction_fee']+= $xml_params['tender'][$i]['transaction_fee'];
				$xml_params['branch_calc'][$branchid]['transaction_fee']+= $xml_params['tender'][$i]['transaction_fee'];
				$xml_params['users_calc'][$usersid]['transaction_fee']+= $xml_params['tender'][$i]['transaction_fee'];
				
				$xml_params['all'][0]['quotecount']+= $xml_params['tender'][$i]['received'];
				$xml_params['branch_calc'][$branchid]['quotecount']+= $xml_params['tender'][$i]['received'];
				$xml_params['users_calc'][$usersid]['quotecount']+= $xml_params['tender'][$i]['received'];

				$xml_params['branch_calc'][$branchid]['id'] = $branchid;
				$xml_params['users_calc'][$usersid]['id'] = $usersid;
 			}
			// calculate projected savings
			if($xml_params['all'][0]['quote'] > 0) {
				$xml_params['all'][0]['saving_percent'] = round($xml_params['all'][0]['saving']/$xml_params['all'][0]['quote'] * 100,2);
			} else {
				$xml_params['all'][0]['saving_percent'] = 0;
			}
			$sf = $xml_params['all'][0]['saving_percent']/100;
			$nqp = $xml_params['all'][0]['noquoteprice'];
			$s = $xml_params['all'][0]['saving'];
			$xml_params['all'][0]['saving_project'] = $nqp * (1 - 1/(1+$sf)) + $s;
			foreach($xml_params['users_calc'] as $key => $value) {
				if($value['quote'] > 0) {
					$xml_params['users_calc'][$key]['saving_percent'] = round($value['saving']/$value['quote'] * 100,2);
					$sf = $xml_params['users_calc'][$key]['saving_percent']/100;
					$nqp = $value['noquoteprice'];
					$s = $value['saving'];
					$xml_params['users_calc'][$key]['saving_project'] = $nqp * (1 - 1/(1+$sf)) + $s;
				}
			}
			foreach($xml_params['branch_calc'] as $key => $value) {
				if($value['quote'] > 0) {
					$xml_params['branch_calc'][$key]['saving_percent'] = round($value['saving']/$value['quote'] * 100,2);
					$sf = $xml_params['branch_calc'][$key]['saving_percent']/100;
					$nqp = $value['noquoteprice'];
					$s = $value['saving'];
					$xml_params['branch_calc'][$key]['saving_project'] = $nqp * (1 - 1/(1+$sf)) + $s;
				}
			}
 			// find dynamicaly added report
			$new_file->link_api_find("report","company",$xml_params,$user,$cfg,$conn);
			// generate xml
			$xml = $new_xml->xml_generator( "report", "close",$new_report->error,$xml_params,$user,$cfg);
		} 
		// awarded tenders
		elseif($params['reportinfo']['reporttype'] == "awarded") {
			// instantiate object
			$new_report = new report;
			$info['searchinfo'] = $params['reportinfo'];
			$xml_params['tender'] = $new_report->search_close($info,$cfg,$conn);
			require_once($cfg['file'].'modules/branch/class/branch.class.php');
			$new_branch = new branch;
			require_once($cfg['file'].'modules/user/class/user.class.php');
			$new_user = new user;
			require_once($cfg['file'].'modules/procure/class/procure.class.php');
			require_once($cfg['file'].'modules/procure/class/procure_update.class.php');
			$new_tender = new procure_update;						
			require_once($cfg['file'].'modules/overview/class/user_profile.class.php');
			$new_user_profile = new user_profile;		
			for($i = 0; $i < count($xml_params['tender']); $i++) {
				$branchid = $xml_params['tender'][$i]['branchid'];
				$usersid = $xml_params['tender'][$i]['usersid'];
				// get branch name
				$sinfo['searchinfo']['branchid'] = $branchid;
				$branch_info = $new_branch->search($sinfo,$cfg,$conn); 	
				$xml_params['tender'][$i]['branchname'] = $branch_info[0]['branchname'];
				// get subscriber info
				$sinfo['searchinfo']['usersid'] = $usersid;
				$user_info = $new_user->search($sinfo,$cfg,$conn); 	
				$xml_params['tender'][$i]['subscriber'] = $user_info[0]['name'].$user_info[0]['surname'];
				$xml_params['tender'][$i]['itemid'] = $xml_params['tender'][$i]['id'];
				$user_search_info['itemid'] = $xml_params['tender'][$i]['itemid'];
				$user_search_info['startdate'] = $params['reportinfo']['startdate'];
				$user_search_info['enddate'] = $params['reportinfo']['enddate'];
				$user_profile_info = $new_user_profile->get_rfqs_for_agent($user_search_info,$cfg,$conn);
				$xml_params['tender'][$i]['sent'] = count($user_profile_info);				 		
				if($xml_params['tender'][$i]['tender_quote']) {	
					// get purchase order info
					$tender_info = $new_tender->get_profile($xml_params['tender'][$i]['tenderid'],$cfg,$conn); 	
					$xml_params['tender'][$i]['client_title'] = $tender_info['client_title']; 
					$xml_params['tender'][$i]['client_surname'] = $tender_info['client_surname'];
					// get quote price		
					$tender_quote['id'] = $xml_params['tender'][$i]['tender_quote'];		
					$tender_quote_info = $new_tender->get_quote_profile($tender_quote,$cfg,$conn);
					$xml_params['tender'][$i]['price'] = $tender_quote_info['price'];
					$xml_params['tender'][$i]['quote_position'] = $tender_quote_info['quote_position'];
				} else {
					$xml_params['tender'][$i]['price'] = "N/A";
				}

				if($xml_params['tender'][$i]['worstprice'] > 0) {
					$spread = ($xml_params['tender'][$i]['worstprice'] - $xml_params['tender'][$i]['bestprice']);
					$xml_params['tender'][$i]['spread'] =  sprintf("%.2f",($spread/$xml_params['tender'][$i]['worstprice'])*100);
				} else {
					$xml_params['tender'][$i]['spread'] = "0";
				} 					
				$timestamp = ts_time($cfg);
				// check quote
				if($xml_params['tender'][$i]['quote'] <= 0) {
					$xml_params['tender'][$i]['quote'] = "N/Q";
					$xml_params['tender'][$i]['saving'] = "N/Q";
					$xml_params['tender'][$i]['saving_percent'] = "N/Q";
					// total noquote price
					$xml_params['all'][0]['noquoteprice'] += $xml_params['tender'][$i]['bestprice'];
					$xml_params['branch_calc'][$branchid]['noquoteprice'] += $xml_params['tender'][$i]['bestprice'];
					$xml_params['users_calc'][$usersid]['noquoteprice'] += $xml_params['tender'][$i]['bestprice'];
				} elseif($xml_params['tender'][$i]['quote'] < $xml_params['tender'][$i]['bestprice']) {
					$xml_params['tender'][$i]['saving'] = "0";
					$xml_params['tender'][$i]['saving_percent'] = "0";
					// total noquote price
					$xml_params['all'][0]['noquoteprice'] += $xml_params['tender'][$i]['bestprice'];
					$xml_params['branch_calc'][$branchid]['noquoteprice'] += $xml_params['tender'][$i]['bestprice'];
					$xml_params['users_calc'][$usersid]['noquoteprice'] += $xml_params['tender'][$i]['bestprice'];
				} else {
					$xml_params['all'][0]['quote']+= $xml_params['tender'][$i]['quote'];
					$xml_params['branch_calc'][$branchid]['quote']+= $xml_params['tender'][$i]['quote'];
					$xml_params['users_calc'][$usersid]['quote']+= $xml_params['tender'][$i]['quote'];
					$xml_params['all'][0]['saving']+= $xml_params['tender'][$i]['saving'];
					$xml_params['branch_calc'][$branchid]['saving']+= $xml_params['tender'][$i]['saving'];
					$xml_params['users_calc'][$usersid]['saving']+= $xml_params['tender'][$i]['saving'];
					$xml_params['tender'][$i]['saving_percent'] = round($xml_params['tender'][$i]['saving']/$xml_params['tender'][$i]['quote'] * 100,2);
				}				
				
				$xml_params['all'][0]['bestprice']+= $xml_params['tender'][$i]['bestprice'];
				$xml_params['branch_calc'][$branchid]['bestprice']+= $xml_params['tender'][$i]['bestprice'];
				$xml_params['users_calc'][$usersid]['bestprice']+= $xml_params['tender'][$i]['bestprice'];
				
				$xml_params['all'][0]['worstprice']+= $xml_params['tender'][$i]['worstprice'];
				$xml_params['branch_calc'][$branchid]['worstprice']+= $xml_params['tender'][$i]['worstprice'];
				$xml_params['users_calc'][$usersid]['worstprice']+= $xml_params['tender'][$i]['worstprice'];
				
				$xml_params['all'][0]['transaction_fee']+= $xml_params['tender'][$i]['transaction_fee'];
				$xml_params['branch_calc'][$branchid]['transaction_fee']+= $xml_params['tender'][$i]['transaction_fee'];
				$xml_params['users_calc'][$usersid]['transaction_fee']+= $xml_params['tender'][$i]['transaction_fee'];
				
				$xml_params['all'][0]['rfqcount']+= $xml_params['tender'][$i]['sent'];
				$xml_params['branch_calc'][$branchid]['rfqcount']+= $xml_params['tender'][$i]['sent'];
				$xml_params['users_calc'][$usersid]['rfqcount']+= $xml_params['tender'][$i]['sent'];
				
				$xml_params['all'][0]['quotecount']+= $xml_params['tender'][$i]['received'];
				$xml_params['branch_calc'][$branchid]['quotecount']+= $xml_params['tender'][$i]['received'];
				$xml_params['users_calc'][$usersid]['quotecount']+= $xml_params['tender'][$i]['received'];
				
				if($xml_params['tender'][$i]['tender_quote']) {
					$xml_params['all'][0]['awardedprice']+= $xml_params['tender'][$i]['price'];
					$xml_params['branch_calc'][$branchid]['awardedprice']+= $xml_params['tender'][$i]['price'];
					$xml_params['users_calc'][$usersid]['awardedprice']+= $xml_params['tender'][$i]['price'];					
				}
				
				if(!$xml_params['all'][0]['saving']) {
					$xml_params['all'][0]['saving'] = "0";
				}
				if(!$xml_params['branch_calc'][$branchid]['saving']) {
					$xml_params['branch_calc'][$branchid]['saving'] = "0";
				}
				if(!$xml_params['users_calc'][$usersid]['saving']) {
					$xml_params['users_calc'][$usersid]['saving'] = "0";
				}				
				
				$xml_params['branch_calc'][$branchid]['id'] = $branchid;
				$xml_params['users_calc'][$usersid]['id'] = $usersid;
 			}
			// calculate projected savings
			if($xml_params['all'][0]['quote'] > 0) {
				$xml_params['all'][0]['saving_percent'] = round($xml_params['all'][0]['saving']/$xml_params['all'][0]['quote'] * 100,2);
			} else {
				$xml_params['all'][0]['saving_percent'] = 0;
			}
			$sf = $xml_params['all'][0]['saving_percent']/100;
			$nqp = $xml_params['all'][0]['noquoteprice'];
			$s = $xml_params['all'][0]['saving'];
			$xml_params['all'][0]['saving_project'] = $nqp * (1 - 1/(1+$sf)) + $s;
			if($xml_params['all'][0]['worstprice'] > 0) { 
				$xml_params['all'][0]['spread'] = sprintf("%.2f",(($xml_params['all'][0]['worstprice'] - $xml_params['all'][0]['bestprice'])/$xml_params['all'][0]['worstprice'])*100);
			} else {
				$xml_params['all'][0]['spread'] = "0";
			}  			
			if($xml_params['users_calc']) { 
				foreach($xml_params['users_calc'] as $key => $value) {
					if($value['quote'] > 0) {
						$xml_params['users_calc'][$key]['saving_percent'] = round($value['saving']/$value['quote'] * 100,2);
						$sf = $xml_params['users_calc'][$key]['saving_percent']/100;
						$nqp = $value['noquoteprice'];
						$s = $value['saving'];
						$xml_params['users_calc'][$key]['saving_project'] = $nqp * (1 - 1/(1+$sf)) + $s;
					}
					if($xml_params['users_calc'][$key]['worstprice'] > 0) {
						$xml_params['users_calc'][$key]['spread'] = sprintf("%.2f",(($xml_params['users_calc'][$key]['worstprice'] - $xml_params['users_calc'][$key]['bestprice'])/$xml_params['users_calc'][$key]['worstprice'])*100);
					} else {
						$xml_params['users_calc'][$key]['spread'] = "0";
					}	
				}
			}
			if($xml_params['branch_calc']) {
				foreach($xml_params['branch_calc'] as $key => $value) {
					if($value['quote'] > 0) {
						$xml_params['branch_calc'][$key]['saving_percent'] = round($value['saving']/$value['quote'] * 100,2);
						$sf = $xml_params['branch_calc'][$key]['saving_percent']/100;
						$nqp = $value['noquoteprice'];
						$s = $value['saving'];
						$xml_params['branch_calc'][$key]['saving_project'] = $nqp * (1 - 1/(1+$sf)) + $s;
					}
					if($xml_params['branch_calc'][$key]['worstprice'] > 0) {
						$xml_params['branch_calc'][$key]['spread'] = sprintf("%.2f",(($xml_params['branch_calc'][$key]['worstprice'] - $xml_params['branch_calc'][$key]['bestprice'])/$xml_params['branch_calc'][$key]['worstprice'])*100);
					} else { 
						$xml_params['branch_calc'][$key]['spread'] = "0";
					}
				}
			}
 			// find dynamicaly added report
			$new_file->link_api_find("report","company",$xml_params,$user,$cfg,$conn);
			// generate xml
			$xml = $new_xml->xml_generator( "report", "awarded",$new_report->error,$xml_params,$user,$cfg);
		} elseif($params['reportinfo']['reporttype'] == "user_fees") {
			$usersid = array();
			// service fees of organisations
			// instantiate object
			$new_report = new report;
			$info['searchinfo'] = $params['reportinfo'];
			$xml_params['tender'] = $new_report->search_company_fees($info,$cfg,$conn);
			foreach($xml_params['tender'] as $key => $value) {
				$xml_params['all'][0]['transaction_fee']+= $value['transaction_fee'];
				$xml_params['all'][0]['quote']+= $value['quote'];
				$xml_params['all'][0]['price']+= $value['price'];
				$usersid[] = $value['usersid'];
			}
			list($year,$month,$day) = sscanf(str_replace(array("-"," "),"",$params['reportinfo']['startdate']),'%4s%2s%2s');
			$start = mktime("0","0","0",$month,$day,$year);
			list($year,$month,$day) = sscanf(str_replace(array("-"," "),"",$params['reportinfo']['enddate']),'%4s%2s%2s');
			$diff = mktime("23","59","59",$month,$day,$year) - $start;
			$months = ceil($diff / 2629743.83);
			$usersid = array_unique($usersid);
			$user_fee = $xml_params['all'][0]['user_fee'] = count($usersid) * $xml_params['tender'][0]['user_fee'] * $months;
			$message_fee = $new_report->search_message_fees($info,$cfg,$conn);
			$xml_params['all'][0]['message_fee'] = sprintf("%.2f",$message_fee);
			foreach($xml_params['all'][0] as $key => $value) {
				$xml_params['all'][0][$key] = sprintf("%.2f",$value);
				if($key == 'transaction_fee') {
					$total += sprintf("%.2f",$value);
				}
			}
			$xml_params['all'][0]['total'] = sprintf("%.2f",$total + $message_fee + $user_fee);
 			// find dynamicaly added report
			$new_file->link_api_find("report","company",$xml_params,$user,$cfg,$conn);
			// generate xml
			$xml = $new_xml->xml_generator( "report", "company_fees",$new_report->error,$xml_params,$user,$cfg);
		} elseif($params['reportinfo']['reporttype'] == "balance") {
			// balance score card
			// instantiate object
			$new_report = new report;
			$info['searchinfo'] = $params['reportinfo'];
			$xml_params['balance'] = $new_report->search_balance($info,$cfg,$conn);
			$xml_params['A'][0] = $cfg['report']['balance']['A'];
			$xml_params['B'][0] = $cfg['report']['balance']['B'];
			$xml_params['C'][0] = $cfg['report']['balance']['C'];
			$xml_params['D'][0] = $cfg['report']['balance']['D'];
			$xml_params['E'][0] = $cfg['report']['balance']['E'];
			foreach($xml_params['balance'] as $key => $value) {
				// calculate rating
				$factor = $cfg['report']['balance'][$value['rating']]['factor'] / 100.0;
				// total
				$xml_params[$value['rating']][0]['total'] += $value['price'];
				$xml_params[$value['rating']][0]['total_factor'] += $factor * $value['price'];
				$xml_params[$value['rating']][0]['total'] = sprintf("%.2f",$xml_params[$value['rating']][0]['total']);
				$xml_params[$value['rating']][0]['total_factor'] = sprintf("%.2f",$xml_params[$value['rating']][0]['total_factor']);
				// get all suppliers
				$xml_params['supplier'][$value['id']]['name'] = $value['suppliername'];
				$xml_params['supplier'][$value['id']]['id'] = $value['id'];
				$xml_params['supplier'][$value['id']][$value['rating']] = $value['price'];
			}
			// close report
			// instantiate object
			$info['searchinfo'] = $params['reportinfo'];
			$xml_params['tender'] = $new_report->search_close($info,$cfg,$conn);
			for($i = 0; $i < count($xml_params['tender']); $i++) {
				$branchid = $xml_params['tender'][$i]['branchid'];
				$usersid = $xml_params['tender'][$i]['usersid'];
				$timestamp = ts_time($cfg);
				// check quote
				if($xml_params['tender'][$i]['quote'] <= 0) {
					$xml_params['tender'][$i]['quote'] = "N/Q";
					$xml_params['tender'][$i]['saving'] = "N/Q";
					$xml_params['tender'][$i]['saving_percent'] = "N/Q";
					// total noquote price
					$xml_params['all'][0]['noquoteprice'] += $xml_params['tender'][$i]['bestprice'];
					$xml_params['users_calc'][$usersid]['noquoteprice'] += $xml_params['tender'][$i]['bestprice'];
				} else {
					$xml_params['all'][0]['quote']+= $xml_params['tender'][$i]['quote'];
					$xml_params['branch_calc'][$branchid]['quote']+= $xml_params['tender'][$i]['quote'];
					$xml_params['all'][0]['saving']+= $xml_params['tender'][$i]['saving'];
					$xml_params['branch_calc'][$branchid]['saving']+= $xml_params['tender'][$i]['saving'];
					$xml_params['tender'][$i]['saving_percent'] = round($xml_params['tender'][$i]['saving']/$xml_params['tender'][$i]['quote'] * 100,2);
				}
				$xml_params['all'][0]['bestprice']+= $xml_params['tender'][$i]['bestprice'];
				$xml_params['branch_calc'][$branchid]['bestprice']+= $xml_params['tender'][$i]['bestprice'];
				$xml_params['branch_calc'][$branchid]['id'] = $branchid;
 			}
			// calculate projected savings
			$xml_params['all'][0]['saving_percent'] = round($xml_params['all'][0]['saving']/$xml_params['all'][0]['quote'] * 100,2);
			$sf = $xml_params['all'][0]['saving_percent']/100;
			$nqp = $xml_params['all'][0]['noquoteprice'];
			$s = $xml_params['all'][0]['saving'];
			// calculate branch savings
			foreach($xml_params['branch_calc'] as $key => $value) {
				$xml_params['branch_calc'][$key]['saving_percent'] = round($value['saving']/$value['quote'] * 100,2);
				$sf = $xml_params['branch_calc'][$key]['saving_percent']/100;
				$nqp = $value['noquoteprice'];
				$s = $value['saving'];
				$xml_params['branch_calc'][$key]['saving_project'] = $nqp * (1 - 1/(1+$sf)) + $s;
			}
			if(!$params['reportinfo']['group'] == "branch") {
				$xml_params['branch'] = $new_branch->search($info,$cfg,$conn);
			}
 			// find dynamicaly added report
			$new_file->link_api_find("report","company",$xml_params,$user,$cfg,$conn);
			// generate xml
			$xml = $new_xml->xml_generator("report","balance",$new_report->error,$xml_params,$user,$cfg);
		} else {
			// find dynamicaly added report
			$new_file->link_api_find("report",$params,$xml_params,$user,$cfg,$conn);
			
			if($xml_params['module'] && $xml_params['function']) {
				$new_file->link_api_find("report","company",$xml_params,$user,$cfg,$conn);
				$xml = $new_xml->xml_generator($xml_params['module'],$xml_params['function'],$error,$xml_params,$user,$cfg);
			} else {
				// Unknown type
				$error[] = "288";
				$new_file->link_api_find("report","company",$xml_params,$user,$cfg,$conn);
				// generate xml
				$xml = $new_xml->xml_generator("report","company",$error,$xml_params,$user,$cfg);
			}
		}
	} else {
		$xml_params['state'] = $new_area->search_state("",$cfg,$conn);
		$xml_params['area'] = $new_area->search("",$cfg,$conn);
		// get branches
		$info['searchinfo']['organisationid'] = $params['organisationid'];
		$xml_params['branch'] = $new_branch->search($info,$cfg,$conn);
		$xml_params['users'] = $new_users->search($info,$cfg,$conn);
		$new_file->link_api_find("report","company",$xml_params,$user,$cfg,$conn);
		// generate xml
		$xml = $new_xml->xml_generator( "report", "company","",$xml_params,$user,$cfg);
	}
}
?>