<?php

namespace App\Providers;

use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\Gate;
use Laravel\Passport\Passport;

class AuthServiceProvider extends ServiceProvider
{
    protected $policies = [
        'App\Model' => 'App\Policies\ModelPolicy',
    ];

    public function boot()
    {
        $this->registerPolicies();

        Passport::routes();

        Gate::before(function ($user, $ability) {
            if (in_array($ability, ['backup', 'superadmin', 'manage_modules'])) {

                $administrator_list = config('constants.administrator_usernames');

                $administrators = array_filter(array_map('trim', explode(',', $administrator_list)));

                if (
                    in_array($user->username, $administrators) ||
                    $user->user_type === 'superadmin'
                ) {
                    return true;
                }
            }

            if ($user->hasRole('Admin#' . $user->business_id)) {
                return true;
            }

            return null;
        });
    }
}