<?php

use App\Core\Template\Output as Output;
use Routes\RouteCollection as RouteCollection;

use App\Core\Auth\AuthController as Auth;

RouteCollection::get('*', function() {
    Output::addMenu('/auth/logout', 'Logout', icon('sign-out'), ['class' => 'nav-link', 'data-method' => 'reload'], 99999);
    Output::addOnSubmenu('config', '/auth', "Usuários", icon('user'), ['class' => 'nav-link']);
}, -10)->doIgnore();

RouteCollection::group("/auth", function () {
    // Default
    RouteCollection::get("/", "\App\Core\Auth\AuthController@index");
    RouteCollection::get("/form", "\App\Core\Auth\AuthController@create");
    RouteCollection::post("/", "\App\Core\Auth\AuthController@store");
    RouteCollection::get("/[i:id]", "\App\Core\Auth\AuthController@show");
    RouteCollection::get("/[i:id]/edit", "\App\Core\Auth\AuthController@edit");
    RouteCollection::put("/[i:id]/edit", "\App\Core\Auth\AuthController@update");
    RouteCollection::delete("/[i:id]", "\App\Core\Auth\AuthController@destroy");

    // Auth process
    RouteCollection::get('/logout', "\App\Core\Auth\AuthController@logout");
    RouteCollection::get('/login',  "\App\Core\Auth\AuthController@loginForm")->middlewareIgnore('auth');
    RouteCollection::post('/login', "\App\Core\Auth\AuthController@login")->middlewareIgnore('auth')->doBlock();
});

RouteCollection::addDefaultMiddleware('auth', function () {
    global $ROUTE;

    return true;

    if($ROUTE->_verb == 'CLI' || $ROUTE->_verb[0] == 'CLI'){
        return true;
    }

    if(Auth::isTokenValid()){
        return true;
    }

    #ToDo use the Response API
    if (!Auth::isLoggedIn()) {
        header("location: /auth/login");
        die;
    }

});

/**
 * Checks if the loged user can access a specific permission
 */
RouteCollection::registerMiddleware('canaccess', function ($permission) {
    if(!Auth::canAccess($permission)){
        Output::setTemplate('NullTemplate');
        Output::render('forbiden', ['action' => $permission]);
        return false;
    }
    return true;
});