<?php
class Calculate {
	var $data = array();
  
  	function __construct(&$locator) {
		$this->database =& $locator->get('database');
	
    	$results = $this->database->getRows("select * from extension where type = 'calculate'");
	
		foreach ($results as $result) {
			$file  = DIR_EXTENSION . $result['directory'] . '/' . $result['filename'];
			$class = 'Calculate' . str_replace('_', '', $result['code']);
			
			if (file_exists($file)) {
				require_once($file);

				$this->data[$result['code']] = new $class($locator);
			}
		}
  	}
	
	
	function getTotalUsd() {
		
		$totals=$this->getTotals();
		
		// ���һ��Ԫ�ص�valueֵ (�=�ֵ), text=S$124(�±�ֵ), value=100.00113686837(�=�ֵ), ������ֵ: 100.00
		$value=end(array_slice(end($totals), -2, 1));	
		$total_USD=number_format($value, 2,'.','');
/*		echo "<script>alert('total_USD=$total_USD');</script>"; */
		return $total_USD;
	}
		
	
	// S$175
	function getTotalText() {
		
		$totals=$this->getTotals();		
		
		return end( array_slice( end($totals), -3, 1 ) );	
	}
	
  	function getTotals() {
		$sort_order = array();
		
/*		print_r(array_keys($this->data)); echo "<br />";
		
		// array_keys��������ļ���, �ü����һ���µ�����,��������,��0,1,2..�������Ϊ����һ���µ���ʱ���� 
		// array_keys($this->data): Array ( [0] => total [1] => subtotal [2] => shipping [3] => coupon [4] => discount ) 
		// Ŀ��: Array ( [0] => subtotal [1] => discount [2] => shipping [3] => coupon [4] => total ) 
		foreach (array_keys($this->data) as $key) {
			$sort_order[$this->data[$key]->getSortOrder()] = $key;
			echo "sort=".$this->data[$key]->getSortOrder()." => ".$key."<br />";
		
		}*/
		$sort_order[0]='subtotal';		
		$sort_order[1]='discount';
		$sort_order[2]='shipping';	
		$sort_order[3]='coupon';
		$sort_order[4]='total';	
		
		// ������ʱ���鰴�ռ�������
		ksort($sort_order);
//		print_r($sort_order); exit;
		
		$total_data = array();
		
		$i = 0;
		
		foreach ($sort_order as $key) {
	  		$results = $this->data[$key]->calculate();
/*			var_dump($results); echo "<br />"; */
	  	  	// ���û��ʹ���Ż݄��Ļ�, $results����Ϊ��, �������ά����$total_data
	  		foreach ($results as $result) {
	    		$total_data[] = array(
		  			'title'      => $result['title'],
		  			'text'       => $result['text'],
		  			'value'      => round($result['value'],2),
					'sort_order' => $i
	    		); 
				
				$i++;
	  		}
		}
//		print_r($total_data); exit;
		return $total_data;
  	}
}
?>