<?php
namespace controllers;

use services\authorization\SessionService;
/**
 * Session controller class
 * @author Jérôme Brilland
 * @version 2.1
 * @copyright (c) 2012-2022, Jérôme Brilland
 * @license http://www.gnu.org/licenses/gpl.txt GNU General Public License
 */
class SessionController extends \ActionController {
	
	/**
	 * Executes index action
	 */
	public function doIndex() {
		$this->doLoginForm();
	}
	
	/**
	 * Displays a Username and Password login form
	 */
	public function doLoginForm() {
        $i18n = \IoC::resolve( 'i18n' );
        $this->title = $i18n->__( 'log_in' );
	}
	
	/**
	 * Login and sets session variables
	 */
	public function doLogin() {
	    $i18n = \IoC::resolve( 'i18n' );
		$session = new SessionService();
		if ( $session->login( $this->request->getParameters()->getAlnum( 'username' ), $this->request->getParameters()->getString( 'password' ) ) ) {
		    $returnTo = ( !empty( $_SESSION['return_to'] ) ) ? $_SESSION['return_to'] : BASE_URL;
			$this->flash['success'] = $i18n->__( 'successfully_logged_in' );
			$this->redirect( $returnTo );
		} else {
		    $this->flash['error'] = $i18n->__( 'login_failed' );
		    $this->doLoginForm();
            $this->render( 'loginform.html' );
		}
	}
	
	/**
	 * Logout current user
	 * Logout is done by destroying the current user session.
	 */
	public function doLogout() {
	    $i18n = \IoC::resolve( 'i18n' );
		$session = new SessionService();
		$session->logout();
		$this->flash['notice'] = $i18n->__( 'successfully_logged_out' );
		$this->redirect( BASE_URL );
	}
	
}

