<?php
/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of LoginController
 *
 * @author eugene
 */
class LoginController extends RCMS_Core_BaseController
{
	/**
	 * Initialization of the controller
	 *
	 * Here we specify model and other usefull initialization of data
	 */

	public function init() {
		parent::init();
		$this->_model = new Default_Model_LoginModel();
	}

	public function indexAction() {
		$recovering = $this->getRequest()->getParam('recovering');
		if($recovering=="success"){
			$this->view->recoveringSuccessMessage = true;
		}
		if(isset($this->_session->isLogged) && (true === $this->_session->isLogged)) {
            $this->_redirect($this->view->websiteUrl);
		}
		$this->view->loginForm = new RCMS_Form_LoginForm();
		if($this->getRequest()->isPost()) {
			if($this->view->loginForm->isValid($this->getRequest()->getParams())) {

				$login = $this->getRequest()->getParam('login');
				$password = $this->getRequest()->getParam('password');
				$userData = $this->_model->selectUserIdByLoginPass($login, $password);
				if(!empty ($userData)) {
					$user = new RCMS_Object_User_User($userData->id);
					$user->setLastLogin(date("Y-m-d H:i:s", time()));
					$user->save();
					$this->_session->currentUser = serialize($user);
					$this->_session->isLogged = true;
					$this->_cache->clean('all');
					$this->_redirect($this->view->websiteUrl);
				}
				else {
					$this->view->invalidLogin = true;
					$this->view->invalidLoginPas = true;
				}
			}
			else {
				$this->view->invalidLogin = true;
				$this->view->errorElements = $this->view->loginForm->getMessages();
			}
		}
		//getting avialable languages
		$languages = array();
		$langsDir = unserialize(Zend_Registry::get('config'))->website->website->path . 'public/downloads';
		//var_dump($langsDir); die();
		$langList = RCMS_Tools_FilesystemTools::findFilesByExt($langsDir, RCMS_Object_Parser_LanguageParser::LANG_FILE_EXTENSION);
		if($langList) {
			foreach ($langList as $langItem) {
				$languages[] = str_replace('.lng', '', $langItem);
			}
		}
		$this->view->langs = $languages;
		//end working with languages
		
		$content = $this->_translator->processScreen($this->view->render($this->getViewScript()));
		$this->_helper->viewRenderer->setNoRender(true);
		echo $content;
	}

	public function logoutAction() {
		if(isset($this->_session->isLogged) && (true === $this->_session->isLogged)) {
			$this->_cache->clean('all');
			$this->_session->unsetAll();
		}
		$this->_redirect($this->view->websiteUrl);
	}

	public function setlangAction() {
		$this->_helper->getHelper('layout')->disableLayout();
        $this->_helper->viewRenderer->setNoRender(true);
		$langId = $this->getRequest()->getParam('langId');
		$this->_session->langId = $langId;
	}

	
}

