<?php

namespace App\Providers;

use Illuminate\Support\Facades\Gate;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
use App\Acl\Resource;
use App\Models\User;

class AuthServiceProvider extends ServiceProvider
{
    /**
     * The policy mappings for the application.
     *
     * @var array
     */
    protected $policies = [
        'App\Models\Website\Website' => 'App\Policies\WebsitePolicy',
    ];

    /**
     * Register any authentication / authorization services.
     *
     * @return void
     */
    public function boot()
    {
//        $this->registerAuthResources();
        $this->registerPolicies();

        //
    }

    protected function registerAuthResources()
    {
        Gate::before(function (User $user, $ability) {
            if ($user->isSystemAdmin()) {
                return true;
            }
        });
        
        Resource::setResources(config('acl_old'));

        foreach (Resource::getResources() as $resource) {

            Gate::define($resource->getResourcePrivilege(), function (User $user) use ($resource) {
                return optional($user->role)->hasPrivilege($resource->getResourcePrivilege()) ? true : false;
            });

            foreach ($resource->getActionsPrivileges() as $actionPrivilege) {
                Gate::define($actionPrivilege, function (User $user) use ($resource, $actionPrivilege) {
                    return optional($user->role)->hasPrivilege($actionPrivilege) ? true : false;
                });
            }
        }
    }
}
