<?php
	
	class loginController extends mainController {
				
		function __construct() {
			parent::__construct();
			
			//To change for every Controller
			$this->viewDir = 'Login';
		}
		
		//Do not show the Disclaimer in this controller actions (see mainController)
		public function beforeRender($content=null) {
			return false;
		}
		
		public function index($args=null) {
			
			$jsRedirect = isset($args['jsRedirect']) ? $args['jsRedirect'] : '/';
			
			//Avoid to show the login form if the user is logged in
			if ($this->user->isLogged()) {
				return $this->redirect('login', 'indexLogged');
			}
						
			$this->view->appTitle = $this->config['settings']['app-title'];
			$this->view->languageList = $this->locale->getLanguageStringList();
			$this->view->token = $this->security->setCSRFToken();
			
			return $this->setJsonView('index', true, $jsRedirect);
			
		}
		
		public function indexLogged($args=null) {
			$this->view->appTitle = $this->config['settings']['app-title'];
			return $this->setJsonView('indexLogged');
		}
		
		public function access($args=null) {
						
			$data = $this->getPost('data');
			$hr = new HandleRequest();
						
			if ($data !== false) {
				
				$username = trim($data['username']);
				$passwd  = trim($data['password']);
				$token = $data['token'];
				//$keep_connected = $data['keep_connected'];
								
				//if ($this->security->compareCSRFToken($token)) {
				//$user = $this->db->where('status', 0, '<>')->where('username', $username, 'like')->getOne('users');
				
				$user = $this->user->getValidUserData($username);
				
				if (isset($user['id'])) {
					if ($user['password'] == md5($passwd)) {
						
						$user = $this->user->setUserMeta($user);
						
						$this->user->logout();
						
						//Log the user (create user's session)
						if ($this->user->login($user)) {
							
							//Associate user id to the current session
							$updateSession = $this->user->setUserIdSessionField();
							
							$this->logger->logUserAccess($user, 1, 'Login');
							
							$hr->setActivityLog($this->user->getUserId(), 'USR_LOGGED_IN', ['userId'=>$this->user->getUserId()]);
							
							return $this->setRawJsonResponse('ok', null);
						} else {
							$hr->setActivityLog(0, 'USR_LOGIN_FAILED', ['username'=>$username]);
							$this->logger->logUserAccess($user, 0, 'User session error', ['Username'=>$username]);
							return $this->setJsonError(_('An error occurred creating user session. Please try again in a few minutes.'));
						}
													
					} else {
						$hr->setActivityLog(0, 'USR_LOGIN_FAILED', ['username'=>$username]);
						$this->logger->logUserAccess(null, 0, 'Password', ['Username'=>$username]);
						return $this->setJsonError(_('The Password provided is not valid.'));
					}
				} else {
					$hr->setActivityLog(0, 'USR_LOGIN_FAILED', ['username'=>$username]);
					$this->logger->logUserAccess(null, 0, 'Username', ['Username'=>$username]);
					return $this->setJsonError(_('The Username provided is not valid.'));
				}
					
				/*} else {
					$this->logger->logUserAccess(null, 0, 'CSRFT', ['Username'=>$username]);
					return $this->setJsonError(_('The provided login information are not valid.'));
				}*/
				
			} else {
				$hr->setActivityLog(0, 'USR_LOGIN_FAILED', ['username'=>$username]);
				$this->logger->logUserAccess(null, 0, 'POST', ['Username'=>$username]);
				return $this->setJsonError(_('Login information data are empty.'));
			}
		}
		
		public function autoLogin() {
			$token = $this->getPost('autologinToken', null);
			$requestID = $this->getPost('requestId', null);
			$expireDays = $this->config['settings']['autologin-expire-days'];
			$hr = new HandleRequest();
			
			$userInfo = $this->db
				->where('autologin_token', $token)
				->where('DATEDIFF(NOW(), autologin_expires_at)', $expireDays, '<=')
				->getOne('users');
				
			if (is_array($userInfo) && !empty($userInfo)) {
				$user = $this->user->getValidUserData($userInfo['username']);
				
				if (is_array($user) && !empty($user)) {
					$user = $this->user->setUserMeta($user);
					
					$this->user->logout();
					
					if ($this->user->login($user)) {
						//Associate user id to the current session
						$updateSession = $this->user->setUserIdSessionField();
						
						$hr->setActivityLog($this->user->getUserId(), 'USR_AUTO_LOGGED_IN', ['userId'=>$this->user->getUserId()]);
						$this->logger->logUserAccess($user, 1, 'Login', ['Auto'=>true, 'RequestID'=>$requestID]);
						return $this->setRawJsonResponse('ok', null, ['RequestID'=>$requestID, 'ts'=>time()]);
					} else {
						
						$hr->setActivityLog(0, 'USR_AUTO_LOGIN_FAILED', ['username'=>$userInfo['username']]);
						$this->logger->logUserAccess($user, 0, 'Auto Login Error', ['Username'=>$username]);
						return $this->setRawJsonResponse('ok', null, []);
					}
					
				} else {
					$hr->setActivityLog(0, 'USR_AUTO_LOGIN_FAILED', ['username'=>'']);
					$this->logger->logUserAccess($user, 0, 'Auto Login Not Valid User', ['Username'=>$username, 'RequestID'=>$requestID]);
					return $this->setRawJsonResponse('ok', null, []);
				}
			} else {
				$hr->setActivityLog(0, 'USR_AUTO_LOGIN_FAILED', ['username'=>'']);
				$this->logger->logUserAccess($user, 0, 'Auto Login Not Valid User Info', ['Username'=>$username, 'RequestID'=>$requestID]);
				return $this->setRawJsonResponse('ok', null, []);
			}
						
		}
		
		public function permissionDenied() {
			//return $this->setJsonView('permissionDenied');
			return $this->setRawJsonResponse('err', _('Session expired or permission denied. Please try to log in again.'), [], ['button'=>'login', 'dialogType'=>'sessionExpired']);
		}
		
		public function changeLang() {
			$passedLng = $this->getPost('passedLng');
			
			if ($passedLng !== false) {
				$this->locale->setCurrentLanguage($passedLng);
			}
			
			return $this->setRawJsonResponse('ok', null);
		}
		
		public function logout() {
			$result = $this->user->logout();
			
			if ($result) {
				$status = 'ok';
				$msg = '';
			} else {
				$status = 'err';
				$msg = _('Logout failed. Please try again in a few minutes.');
			}
			
			return $this->setRawJsonResponse($status, $msg);
		}

	}