<?php

namespace App\Core\Auth;

use ORM\DBInstance;
use \App\Core\Template\Output as Output;

use Singleton;
use RR\Response;
use \App\Core\Auth\Classes\Auth as Auth;
use App\Core\Auth\Classes\AuthenticatedUser;
use App\Core\Auth\Classes\Token;
use \App\Core\Auth\Classes\User as User;

class AuthController
{

    private static $user;
    private static $permissions;

    /**
     * Index
     * Show the main Auth list
     */
    function index()
    {
        Output::render('index', ['list' => User::findAll()]);
    }

    /**
     * Create
     *
     * Render the main Auth formulary
     */
    function create(User $auth)
    {
        Output::render('form', $auth);
    }

    /**
     * Store
     *
     * Store the param on the database
     * @param User $auth
     */
    function store(User $auth)
    {
        $auth->charge($_POST);

        if (request('password') == '') {
            unset($auth->password);
        } else {
            $auth->password = md5(request('password'));
        }

        $auth->save();
        $auth->appendGroups(request('groups'));

        Response::json($auth)->send();
    }

    /**
     * Show
     *
     * Render one register
     *
     * @param Auth $auth
     */
    function show(Auth $auth)
    {
    }

    /**
     * Edit
     *
     * Render the formular for a database Auth
     *
     * @param Auth $auth
     */
    function edit(User $auth)
    {
        Output::render('form', $auth);
    }

    /**
     * Update
     * Store the changes of the param on the database
     *
     * @param User $auth
     */
    function update(User $auth)
    {
        $auth->charge($_POST);

        if (request('password') == '') {
            unset($auth->password);
        } else {
            $auth->password = md5(request('password'));
        }

        $auth->save();
        $auth->appendGroups(request('groups'));

        Response::json($auth)->send();
    }

    /**
     * Destroy
     * If the object has soft delete.
     *
     * @param Auth $auth
     */
    function destroy(Auth $auth)
    {
    }

    /**
     * Purge
     * Remove object even with soft delete.
     *
     * @param Auth $auth
     */
    function purge(Auth $auth)
    {
    }

    function login()
    {
        if ($user = User::findOne(['username' => ['=', $_POST['login']], 'password' => ['=', md5($_POST['password'])]])) {
            AuthController::executeLogin($user);
        } else {
            Output::setTemplate('NullTemplate');
            Output::render('login', ['errors' => ['name' => 'Não há usuário com essa senha']]);
        }
    }

    /**
     * Prints the system login form
     */
    function loginForm()
    {
        if (self::isLoggedIn()) {
            Response::redirect('/');
        } else {
            Output::setTemplate('NullTemplate');
            Output::render('login');
        }
    }

    /**
     * Just check if the user is set on the _SESSION variable
     *
     * @return bool
     */
    public static function isLoggedIn()
    {
        if ($_SESSION['user']) {
            AuthenticatedUser::load();
        } else {
            return false;
        }

        return true;
    }

    /**
     * Check if the token passed on the wstoken param is valid
     * by valid.
     * - Exist
     * - Not Expired
     * - Has the permission
     *
     * @return bool
     */
    public static function isTokenValid()
    {
        if ($token = Token::findOne(['token' => ['=', request('wstoken')]])) {
            AuthenticatedUser::load($token->user());
        } else {
            return false;
        }
        return true;
    }

    /**
     * Given a permission. Check if the loged user can execute it
     *
     * @param String $permission
     */
    public static function canAccess($permission)
    {

        if (AuthenticatedUser::permissions() == null) {
            return false;
        }

        if (in_array('sys:admin', AuthenticatedUser::permissions())) {
            return true;
        }

        if (in_array($permission, AuthenticatedUser::permissions())) {
            return true;
        }

        return false;
    }

    /**
     * In case the login form is valid. Persist user data on SESSION
     * so the login system words onwards
     *
     * TODO - Cache wantsPage
     *
     * @param User $user
     */
    function executeLogin(User $user)
    {
        $_SESSION['user']['user'] = $user->id;
        $_SESSION['user']['permission'] = $user->permissions();
        header("location: /");
    }

    /**
     * Execute the system logout
     */
    function logout()
    {
        session_destroy();
        header("location: /auth/login");
    }
}
