<?php

namespace App\Console\Commands;

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

class FixSuperAdminRole extends Command
{
    protected $signature = 'admin:fix-role';
    protected $description = 'Fix Super Admin role by assigning all permissions';

    public function handle()
    {
        $superAdminRole = Role::where('name', 'Super Admin')->first();
        
        if (!$superAdminRole) {
            $this->error("Super Admin role not found!");
            return Command::FAILURE;
        }
        
        $this->info("Found Super Admin role");
        
        // Get all permissions
        $allPermissions = Permission::all();
        $this->info("Total permissions available: {$allPermissions->count()}");
        
        // Get current role permissions
        $currentPermissions = $superAdminRole->permissions;
        $this->info("Current role permissions: {$currentPermissions->count()}");
        
        // Assign all permissions to Super Admin
        $superAdminRole->syncPermissions($allPermissions);
        
        $this->info("✅ All permissions assigned to Super Admin role!");
        
        // Verify critical permissions
        $criticalPermissions = ['view users', 'view roles', 'access dashboard'];
        foreach ($criticalPermissions as $permission) {
            if ($superAdminRole->hasPermissionTo($permission)) {
                $this->info("✅ Super Admin has '{$permission}' permission");
            } else {
                $this->error("❌ Super Admin missing '{$permission}' permission");
            }
        }
        
        return Command::SUCCESS;
    }
}