<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Spatie\Permission\Models\Role;
use Spatie\Permission\Models\Permission;

class CheckRoles extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'check:roles';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Check roles and permissions in the system';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $this->info('Roles in the system:');
        $roles = Role::all()->toArray();
        $this->table(['ID', 'Name', 'Guard Name', 'Created At', 'Updated At'], $roles);

        $this->newLine();
        $this->info('All Permissions:');
        $permissions = Permission::all()->toArray();
        $this->table(['ID', 'Name', 'Guard Name', 'Created At', 'Updated At'], $permissions);

        // 显示每个角色的权限
        $this->newLine();
        $this->info('Role Permissions:');

        foreach (Role::all() as $role) {
            $this->line("<fg=yellow>Role: {$role->name}</>");
            $rolePermissions = [];

            foreach ($role->permissions as $permission) {
                $rolePermissions[] = [
                    'permission' => $permission->name
                ];
            }

            if (count($rolePermissions) > 0) {
                $this->table(['Permission'], $rolePermissions);
            } else {
                $this->line('No permissions.');
            }

            $this->newLine();
        }

        return Command::SUCCESS;
    }
}
