<?php
namespace services\authorization;

use \models\User;

/**
 * Session service
 * @author Jérôme Brilland
 * @version 2.0
 */
class SessionService {

    /**
     * Checks if a user is logged in
     * @return boolean true if a user is logged in, false otherwise
     * @access public
     */
    public function isLoggedIn() {
        return ( !empty( $_SESSION['user_id'] ) );
    }

    /**
     * Perform a login request
     * @param string username Username
     * @param string password Password
     * @return boolean true if the login was successful, false otherwise 
     * @access public
     */
    public function login( $username, $password ) {
        \IoC::resolve( 'eventmediator' )->trigger( 'before_login', $username );
        $user = User::findByUsername( $username );
        if ( !empty( $user ) && $user->authenticate( $password ) ) {
            $_SESSION['user_id'] = $user->user_id;
            $user->last_login = date( 'Y-m-d H:i:s' );
            $user->last_ip = $_SERVER['REMOTE_ADDR'];
            $user->save();
            \IoC::resolve( 'eventmediator' )->trigger( 'after_login', $user );
            return true;
        } else {
            \IoC::resolve( 'eventmediator' )->trigger( 'login_failed', [$username, $user] );
            return false;
        }
    }

    /**
     * Logs out the current logged-in user
     * @access public
     */
    public function logout() {
        \IoC::resolve( 'eventmediator' )->trigger( 'before_logout', $username );
        $_SESSION = array();
        if ( isset( $_COOKIE[session_name()] ) ) {
            setcookie( session_name(), '', time() - 42000, '/' );
        }
        session_destroy();
        \IoC::resolve( 'eventmediator' )->trigger( 'after_logout', $username );
    }
    
}
