<?php
/**
 * ISO project
 * 
 * @author  Lukas Havlicek
 * @version 1.0
 */

require_once 'Zend/Controller/Plugin/Abstract.php';
require_once 'Zend/Controller/Front.php';
require_once 'Zend/Controller/Request/Abstract.php';
require_once 'Zend/Controller/Action/HelperBroker.php';
require_once "Zend/Loader.php"; 

/**
 * 
 * Initializes configuration depndeing on the type of environment 
 * (test, development, production, etc.)
 *  
 * This can be used to configure environment variables, databases, 
 * layouts, routers, helpers and more
 *   
 */
class Initializer extends Zend_Controller_Plugin_Abstract
{
    /**
     * @var Zend_Config
     */
    protected static $_config;

    /**
     * @var string Current environment
     */
    protected $_env;

    /**
     * @var Zend_Controller_Front
     */
    protected $_front;
    
    /**
     * @var Zend_Db
     */
    protected $_db;

    /**
     * @var string Path to application root
     */
    protected $_root;

    /**
     * Constructor
     *
     * Initialize environment, root path, and configuration.
     * 
     * @param  string $env 
     * @param  string|null $root 
     * @return void
     */
    public function __construct($env, $root = null)
    {
        $this->_setEnv($env);
        if (null === $root) {
            $root = realpath(dirname(__FILE__) . '/../');
        }
        $this->_root = $root;
        
        $this->initPhpConfig();
        
        $this->_front = Zend_Controller_Front::getInstance();
        
        // set the test environment parameters
        if ($env == 'development') {
			// Enable all errors so we'll know when something goes wrong. 
			error_reporting(E_ALL | E_STRICT);  
			ini_set('display_startup_errors', 1);  
			ini_set('display_errors', 1); 

			$this->_front->throwExceptions(true);  
        }

		// Set up autoload.
		Zend_Loader::registerAutoload();
		
		//Set relative baseUrl of whole website
		Zend_Registry::set('baseUrl', '/iso');
    }

    /**
     * Initialize environment
     * 
     * @param  string $env 
     * @return void
     */
    protected function _setEnv($env) 
    {
		$this->_env = $env;    	
    }
    

    /**
     * Initialize php configuration
     * 
     * @return void
     */
    public function initPhpConfig()
    {
    	
    }
    
/**
     * Initialize application configuration
     * 
     * @return void
     */
    public function initConfig()
    {
    	Initializer::$_config = new Zend_Config_Ini($this->_root . '/application/config/config.ini', $this->_env);	
    }
    
    /**
     * Route startup
     * 
     * @return void
     */
    public function routeStartup(Zend_Controller_Request_Abstract $request)
    {
       	$this->initSessions();
    	$this->initConfig();
       	$this->initDb();
       	$this->initView();
        $this->initHelpers();
        $this->initPlugins();
        $this->initRoutes();
        $this->initControllers();
    }
    
    /**
     * Initialize sessions
     * 
     * @return void
     */
    public function initSessions()
    {
		Zend_Session::start();
    }
    
	/**
     * Checks if user is logged in
     * 
     * @return void
     */
    public function preDispatch(Zend_Controller_Request_Abstract $request)
    {
		$auth = Zend_Auth::getInstance()->setStorage(new Zend_Auth_Storage_Session('iso'));
		if (!$auth->hasIdentity() && $request->getModuleName() == 'default' && $request->getControllerName() == 'registration') {
			$request->setModuleName('default');
			$request->setControllerName('registration');
		} elseif (!$auth->hasIdentity() && $request->getModuleName() == 'default' && $request->getControllerName() == 'lost-password') {
			$request->setModuleName('default');
			$request->setControllerName('lost-password');
		} elseif ($request->getModuleName() == 'default' && $request->getControllerName() == 'language') {
			$request->setModuleName('default');
			$request->setControllerName('language');
			$request->setActionName('switch');
        } elseif (!$auth->hasIdentity()) {
			$request->setModuleName('default');
			$request->setControllerName('login');
			$request->setActionName('index');
    	} else {
    		
    		
    		
    		$identity = $auth->getIdentity();
    		$table = new Users();
    		$user = $table->fetchRow($table->select()->where('id_user = ?', $identity->id_user));
    		if ($user) {
    			Zend_Registry::set('user', $user);
    		} else {
    			Zend_Registry::set('user', $identity);
    		}
    		
    		if ('admin' == $request->getModuleName() && !$identity->super_admin) {
    			$request->setModuleName('default');
    			$request->setControllerName('index');
    			$request->setActionName('index');
    		}
    		
    		$this->initViewContent();
    	}
    	$this->initLanguages();
    }
    
    
    /**
     * Initialize data bases
     * 
     * @return void
     */
    public function initDb()
    {
    	// First, set up the Cache
		$frontendOptions = array(
		    'automatic_serialization'	=> true
		    );
		
		$backendOptions  = array(
		    'cache_dir'					=> './application/cache'
		    );
		
		$cache = Zend_Cache::factory('Core',
		                             'File',
		                             $frontendOptions,
		                             $backendOptions);
		
		
		// Next, set the cache to be used with all table objects
		$db = Zend_Db::factory(Initializer::$_config->database->adapter, Initializer::$_config->database->toArray());
		Zend_Db_Table_Abstract::setDefaultAdapter($db);
		Zend_Db_Table_Abstract::setDefaultMetadataCache($cache);
		$db->query('SET CHARACTER SET utf8');
		$this->_db = $db;
		Zend_Registry::set('db', $db);
		
		if ($this->_env == 'development') 
		{
			$profiler = new Zend_Db_Profiler_Firebug('All DB Queries');
			$profiler->setEnabled(true);
			$db->setProfiler($profiler);
		}
    }

    /**
     * Initialize action helpers
     * 
     * @return void
     */
    public function initHelpers()
    {
    	// register the default action helpers
    	//Zend_Controller_Action_HelperBroker::addPath('./application/helpers', 'Zend_Controller_Action_Helper');
    }
    
    /**
     * Initialize view 
     * 
     * @return void
     */
    public function initView()
    {
		// Bootstrap layouts
		Zend_Layout::startMvc(array(
		    'layoutPath' => $this->_root .  '/application/layouts',
		    'layout' => 'main'
		));
		
		$view = Zend_Layout::getMvcInstance()->getView();
		$view->doctype('XHTML11');
		$view->addHelperPath('./library/Malf/View/Helper', 'Malf_View_Helper_');
		
		Zend_Registry::set('view', $view);
    }
    
    public function initViewContent()
    {
    	$view = Zend_Registry::get('view');
    	
    	$isLoggedAdmin = false;
		
		$user = Zend_Registry::get('user');
		if ($user->super_admin == 1) {
			$isLoggedAdmin = true;
		}
		
		Zend_Registry::set('isLoggedAdmin', $isLoggedAdmin);
		
		$view->isLoggedAdmin = $isLoggedAdmin;
		
		Zend_Registry::set('view', $view);
		
		
    }
    
    /**
     * Initialize plugins 
     * 
     * @return void
     */
    public function initPlugins()
    {
    	if ($this->_env == 'development')
    	{
    		require_once 'Debug.php';
    		$this->_front->registerPlugin(new Debug());
    	}
    }
    
    /**
     * Initialize routes
     * 
     * @return void
     */
    public function initRoutes()
    {
    
    }

    /**
     * Initialize Controller paths 
     * 
     * @return void
     */
    public function initControllers()
    {
    	$this->_front->addControllerDirectory($this->_root . '/application/default/controllers', 'default');
    	$this->_front->addControllerDirectory($this->_root . '/application/admin/controllers', 'admin');
    }
    
/**
     * Initialize languages 
     * 
     * @return void
     */
    public function initLanguages()
    {
    	$locale = new Zend_Locale();
    	
    	$auth = Zend_Auth::getInstance()->setStorage(new Zend_Auth_Storage_Session('iso'));
		if ($auth->hasIdentity()) {
			$identity = $auth->getIdentity();
			$table = new Users();
    		$user = $table->fetchRow($table->select()->where('id_user = ?', $identity->id_user));
    		if ($user && $user->lang) {
    			$locale = new Zend_Locale($user->lang);
    		}
    	}
    	
    	$language = new Zend_Session_Namespace('language');
    	if (isset($language->lang) && ($language->lang  == 'cs' || $language->lang == 'en'))
    	{
    		$locale = new Zend_Locale($language->lang);
    	}
    	
    	
		Zend_Registry::set('Zend_Locale', $locale);
		
		$defaultlanguage = 'cs';
		
    	$translate = new Zend_Translate('gettext', $this->_root . '/application/languages/en.mo', 'en');
		$translate->addTranslation($this->_root . '/application/languages/cs.mo', 'cs');
		
		if (!$translate->isAvailable($locale->getLanguage())) {
		    // when user requests a not available language reroute to default
		    $translate->setLocale($defaultlanguage);
		} else {
			$translate->setLocale($locale);
		}
		
		Zend_Registry::set('Zend_Translate', $translate);
    }
}
?>
