<?php

namespace App\Livewire;

use Livewire\Component;
use Spatie\Permission\Models\Permission;
use App\Models\{User, Group};

class PermissionsList extends Component
{
    public $resourceId;
    public $resourceType;

    public function mount($resourceId)
    {
        $this->resourceId = $resourceId;
        $this->determineResourceType();
    }

    protected function determineResourceType()
    {
        if (Project::find($this->resourceId)) {
            $this->resourceType = 'project';
        } else {
            $this->resourceType = 'folder';
        }
    }

    public function getPermissions()
    {
        return Permission::where('name', 'like', "{$this->resourceType}-{$this->resourceId}-%")
            ->get()
            ->groupBy(function ($permission) {
                return explode('-', $permission->name)[2]; // Obtener tipo de permiso
            });
    }

    public function revokePermission($permissionId, $modelType, $modelId)
    {
        $permission = Permission::findOrFail($permissionId);
        
        $model = $modelType === 'user' 
            ? User::find($modelId)
            : Group::find($modelId);

        $model->revokePermissionTo($permission);
        
        $this->dispatch('permissionsUpdated');
    }

    public function render()
    {
        return view('livewire.permissions-list', [
            'permissions' => $this->getPermissions(),
            'users' => User::withPermissionsForResource($this->resourceId, $this->resourceType)->get(),
            'groups' => Group::withPermissionsForResource($this->resourceId, $this->resourceType)->get()
        ]);
    }
}
