<?php
namespace Nibiru\Module\Users\Plugins;
/**
 * Class    Acl
 * @project Lagerverwaltung
 * @desc    This is the ACL plugin for the users module. It checks if the user is logged in or not, and also loads the corresponding
 *          user role into the session.
 * @author  stephan - Maschinen Stockert Großhandels GmbH
 * @date    26.01.23
 * @time    11:38
 * @package Nibiru\Module\Users\Plugins
 */
use Nibiru\View;
use Nibiru\Factory\Db;
class Acl extends User
{
    /**
     * @desc Acl constructor.
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * @desc checks if the users is logged into the system, if yes nothing happens,
     *       if no it redirects to the login page.
     * @return void
     */
    public function init(): void
    {
        if(!$this->validate())
        {
            View::forwardTo('/users/login');
        }
        else
        {
            $this->loadUserRole();
        }
    }

    /**
     * @desc checks if the user is logged in, if yes it loads the corresponding user role into the session.
     * @return void
     * [auth] => Array
        (
            [session_id] => SESSION_ID
            [user_id] => USER_ID
            [login] => USER_LOGIN
            [role] => ACL_ROLE
        )
     */
    public function loadUserRole(): void
    {
        if(User::validate())
        {
            $userRole = User::getRoleByLoggedInUser();
            $_SESSION['auth']['role'] = $userRole['acl_role'];
        }
    }

    /**
     * @desc will load the acl roles from the database and return them as an array.
     * @return array
     * @throws \Exception
     */
    public function loadAclRoles(): array
    {
        $acl = Db::loadModel('WarehouseLoach\Acl');
        return $acl->loadTableAsArray();
    }
}