<?php

namespace App\Providers;

use App\Models\Permission;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\ServiceProvider;

class PermissionServiceProvider extends ServiceProvider
{
    public function register()
    {
        //
    }

    public function boot()
    {
        try {
            // Register all permissions as gates
            Permission::all()->each(function ($permission) {
                Gate::define($permission->name, function ($user, $businessId = null) use ($permission) {
                    return $user->hasPermission($permission->name, $businessId);
                });
            });

            // Define super admin gate (can do everything)
            Gate::before(function ($user, $ability) {
                if ($user->hasRole('super_admin')) {
                    return true;
                }
            });

            // Define role-based gates
            Gate::define('has-role', function ($user, $role, $businessId = null) {
                return $user->hasRole($role, $businessId);
            });

            Gate::define('has-any-role', function ($user, $roles, $businessId = null) {
                return $user->hasAnyRole($roles, $businessId);
            });

            Gate::define('has-permission', function ($user, $permission, $businessId = null) {
                return $user->hasPermission($permission, $businessId);
            });

            Gate::define('has-any-permission', function ($user, $permissions, $businessId = null) {
                return $user->hasAnyPermission($permissions, $businessId);
            });

        } catch (\Exception $e) {
            // Silently fail if database is not set up yet
            // This prevents errors during migrations
        }
    }
}
