<?php

class Eppe_Backend_Controller_Action extends Eppe_Controller_Action {

	/**
	 * @var Rtn_Ajax_Response
	 */
	protected $ajaxResponse;
	protected $isAjax = false;

	protected $_authStorage = 'Backend';
	
	public function init() {
		$this->_setAuthStorage();
		$this->_refreshSession();
		$this->_helper->layout->setLayout('/admin/layout');
		$this->_initFlashMessages();

		if ($this->_request->isXmlHttpRequest() || $this->looksLikeAjaxOrIframe()) {
			$this->isAjax = true;
			$this->ajaxResponse = new Rtn_Ajax_Response();
			$this->_disableView();
			$this->_resolveAllowed();
		}
		else {
			$this->_resolveAllowed();
			$this->_initMainMenu();
			$this->_initHeadStyles();
			$this->_initHeadScripts();
		}

		parent::init();
	}

	protected function _setAuthStorage() {
		Eppe_Auth::getInstance()->setStorage(new Eppe_Auth_Storage_Backend());
	}

	protected function _resolveAllowed() {
		if ($this->_request->isXmlHttpRequest()) {
			$proceed = true;

			try {
				if ($proceed && !Eppe_Acl::checkAllowed($this->_request,$this->_authStorage)) {
					$proceed = false;
				}
			}
			catch (Rtn_Exception_Acl $e) {
				$proceed = false;
			}

			if (!$proceed) {
				//TODO: Dobrze byłoby rozróżniać timeout(wylogowanie) od braku uprawnień
				if(APPLICATION_ENV == 'production'){
					$this->ajaxResponse->evalJS = 'window.location = "/";';
				}
				else{
					$this->ajaxResponse->evalJS = 'alert("brak uprawnień"); window.location = "/";';
				}
			}
		}
		else {
			if (!Eppe_Acl::checkAllowed($this->_request,$this->_authStorage)) {
				if(APPLICATION_ENV == 'production'){
					$this->_redirect('/');
				}
				else{
					throw new Rtn_Exception_Acl('Brak uprawnień');
				}
			}
		}
	}

	protected function _refreshSession() {
		if (Eppe_Auth::_()->hasIdentity()) {
			$namespace = new Zend_Session_Namespace('Zend_Auth_Admin');
			$namespace->setExpirationSeconds(3600 * 3);
		}
	}

	protected function _initMainMenu() {
		$nav = new Zend_Navigation();
		foreach (Eppe_Module_ModuleAbstract::getEnabledModulesInstances() as $module) {
			if (!empty($module->config->hasMenu)) {
				$nav->addPages($module->menu->getNavigation());
			}
		}

		$this->view->navigation($nav);
	}

	protected function _initHeadStyles() {
		Head_Libraries::getBackendCssLibs();
	}

	protected function _initHeadScripts() {
		Head_Libraries::getBackendJsLibs();
	}

	protected function _redirectIndex() {
		$module = $this->_request->getModuleName();
		$action = 'index';

		$this->_redirect($this->view->url(array('module' => $module, 'controller' => 'admin_index', 'action' => $action), null, true));
	}

}
