<?php
namespace library;

use models\IUser;

/**
 * Authorization class
 * @author Jérôme Brilland
 * @version 2.0
 * @copyright (c) 2019-2021, Jérôme Brilland
 * @license http://www.gnu.org/licenses/gpl.txt GNU General Public License
 */
class Authorization implements \IAuthorization {

    /**
     * @access protected
     */
    protected $user;

    /**
     * Class constructor
     * @param IUser $user
     * @access public
     */
    public function __construct( IUser $user ) {
        $this->user = $user;
    }

    /**
     * @param mixed $activity
     */
    public function authorize( $activity ) {
        if ( DEVELOPMENT_ENVIRONMENT ) {
            $logger = \IoC::resolve( 'logger' );
            $logger->write( sprintf( '[%s] [%s] [%s] %s',  date( 'Y-m-d H:i:s' ), __FILE__, 'debug', "Authorization::authorize( $activity )" ) );
        }
        if ( !$this->isAuthorized( $activity ) ) {
            if ( !$this->user->isAuthenticated() ) {
                if ( DEVELOPMENT_ENVIRONMENT ) {
                    \IoC::resolve( 'logger' )->write( sprintf( '[%s] [%s] [%s] %s',  date( 'Y-m-d H:i:s' ), __FILE__, 'debug', 'Not logged in' ) );
                }
                $_SESSION['return_to'] = $_SERVER['REQUEST_URI'];
                header( 'Location: ' . BASE_URL . 'login' );
                exit();
            } else {
                if ( DEVELOPMENT_ENVIRONMENT ) {
                    \IoC::resolve( 'logger' )->write( sprintf( '[%s] [%s] [%s] %s',  date( 'Y-m-d H:i:s' ), __FILE__, 'debug', '403 Forbidden' ) );
                }
                $_SESSION['return_to'] = parse_url( $_SERVER['REQUEST_URI'], PHP_URL_PATH );
                header( 'Location: ' . BASE_URL . 'error/403' );
                exit();
            }
        }
    }
    
    /**
     * @param mixed $activity
     * @return boolean True if the user is authorized, false otherwise
     */
    public function isAuthorized( $activity ) {
        if ( DEVELOPMENT_ENVIRONMENT ) {
            $logger = \IoC::resolve( 'logger' );
            $logger->write( sprintf( '[%s] [%s] [%s] %s',  date( 'Y-m-d H:i:s' ), __FILE__, 'debug', "Authorization::isAuthorized( $activity )" ) );
            $logger->write( sprintf( '[%s] [%s] [%s] %s',  date( 'Y-m-d H:i:s' ), __FILE__, 'debug', join( ', ', $this->user->getPermissions() ) ) );
        }
        return ( $this->user->hasPermission( $activity ) );
    }
}
