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

			if (file_exists($file)) {
				require_once($file);

				$this->data[$result['code']] = new $class($locator);
			}
		}
  	}
  	 function fetchAccount() {
  	 	$module_data = array();
		$module_data['header']= $this->data['header']->fetch();
		$module_data['account']=$this->data['account']->fetch(); 
		$module_data['footer']=$this->data['footer']->fetch();
//		print_r($module_data);exit;
		return $module_data;
  	}
  	
	function fetchTemplate($template) {  		

		$module_data = array();
		
		if (!empty($template)){ // fetch specify template
		
				if (isset($this->data[$template])){
					$module = $this->data[$template]->fetch();
					if( $module){
						$module_data[$template] = $module;
					}
				}
			
		}

		return $module_data;
  	} 	

  	
  	function fetchPublic() {
		return $this->fetchTemplates(array('header','footer'));
  	}
  	
  	function fetchTemplates($templates = array()) {  		

		$module_data = array();
		
		if (!empty($templates)){ // fetch specify templates
			foreach ($templates as $key) {
				if (isset($this->data[$key])){
					$module = $this->data[$key]->fetch();
					if( $module){
						$module_data[$key] = $module;
					}
				}
			}
		}
		return $module_data;
  	}  	
    	
 	function fetch() {
		$module_data = array();
		
		foreach (array_keys($this->data) as $key) {
			$module = $this->data[$key]->fetch();
			
			if ($module) {
				$module_data[$key] = $module;
			}
		}

		return $module_data;
  	}  	
  

	function runTemplateInsert($key, $args = array()) {
		if (method_exists($this->data[$key], 'insert')) {
			$this->data[$key]->insert($args);
		}
	}
}
?>