<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Models\User;

class TestUserPermissions extends Command
{
    protected $signature = 'test:user-permissions {email=admin@admin.com}';
    protected $description = 'Test user permissions';

    public function handle()
    {
        $email = $this->argument('email');
        $user = User::where('email', $email)->first();
        
        if (!$user) {
            $this->error("User with email {$email} not found");
            return 1;
        }
        
        $this->info("Testing permissions for: {$user->name} ({$user->email})");
        $this->info("User branch_code: " . ($user->branch_code ?? 'NULL'));
        
        // Test role assignment
        $roles = $user->roles()->where('user_roles.is_active', true)->get();
        $this->info("Active roles: " . $roles->pluck('name')->join(', '));
        
        // Test hasRole
        $hasSuperAdmin = $user->hasRole('super_admin');
        $this->info("Has super_admin role: " . ($hasSuperAdmin ? 'YES' : 'NO'));
        
        // Test hasPermission with and without branch code
        $hasUsersViewWithBranch = $user->hasPermission('users.view', $user->branch_code);
        $hasUsersViewWithoutBranch = $user->hasPermission('users.view');
        
        $this->info("Has users.view with branch code: " . ($hasUsersViewWithBranch ? 'YES' : 'NO'));
        $this->info("Has users.view without branch code: " . ($hasUsersViewWithoutBranch ? 'YES' : 'NO'));
        
        // Check role permissions
        foreach ($roles as $role) {
            $rolePermissions = $role->permissions()->where('name', 'users.view')->count();
            $this->info("Role '{$role->name}' has users.view permission: " . ($rolePermissions > 0 ? 'YES' : 'NO'));
        }
        
        return 0;
    }
}
