<?php namespace App\Modules\Utils\Acl;

use View, Session, Config, Auth, App;
use App\Modules\Backend\Usergroups\Models\UserGroup;
class Acl {

	protected $is_super_admin;
	protected $user;
	protected $group;
	protected $permissions = array();

	public function __construct()
	{
		$this->user 			= Auth::user();
		$this->is_super_admin 	= $this->user->usergroup == 0;
		if(!$this->is_super_admin)
		{
			$this->group = UserGroup::find($this->user->usergroup);
			$permissions = json_decode($this->group->permissions);
			foreach ($permissions as $permission) {
				$this->permissions[] = array(
											'module' => $permission->module,
											'action' => $permission->action
											);
			}
		}
	}

	public function canOrFail($module, $action)
	{
		if(!$this->can($module, $action))
			App::abort(403, trans('dashboard::message.error_403'));
		return true;
	}

	/**
	 * Determina su un usuario tiene autorización para ejecutar cierta acción en un modulo.
	 * @param  string $module 
	 * @param  string $action 
	 * @return boolean Puede o no puede.
	 */
	public function can($module, $action)
	{
		if($this->is_super_admin)
			return true;
		$permission = array(
							'module' => $module,
							'action' => $action
						);
		return in_array($permission, $this->permissions);
	}
}