<?php

namespace App\Providers;

// use Illuminate\Support\Facades\Gate;

use App\Models\Permission;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Gate;

class AuthServiceProvider extends ServiceProvider
{
    /**
     * The model to policy mappings for the application.
     *
     * @var array<class-string, class-string>
     */
    protected $policies = [
        //
    ];

    /**
     * Register any authentication / authorization services.
     */
    public function boot(): void
    {
        try {
            // Admin Panel ACL
            foreach ($this->getPermissions() as $permission) {
                Gate::define($permission->name, function ($user) use ($permission) {
                    return $user->hasRole($permission->roles);
                });
            }

            // Seller Panel Access Gate
            Gate::define('seller-access', function ($user) {
                return $user->status == 'active' && $user->store != null && $user->store->status == 'active';
            });
        } catch (\Exception $e) {
        }
    }

    protected function getPermissions()
    {
        return Cache::remember('permissions', now()->addHour(), function () {
            return Permission::with('roles')->get();
        });
    }
}
