<?php

namespace App\Livewire;

use Livewire\Component;
use App\Models\Project;
use App\Models\Folder;
use App\Models\User;

class PermissionManager extends Component
{
    public $selectedProject;
    public $selectedFolder;
    public $assignTo = 'user';
    public $selectedPermissions = [];
    public $selectedUser;
    public $selectedGroup;

    protected $listeners = ['userSelected', 'groupSelected'];

    public function rules()
    {
        return [
            'selectedProject' => 'required|exists:projects,id',
            'selectedFolder' => 'nullable|exists:folders,id',
            'selectedPermissions' => 'required|array|min:1',
            'selectedUser' => 'required_if:assignTo,user',
            'selectedGroup' => 'required_if:assignTo,group',
        ];
    }

    public function getSelectedResourceIdProperty()
    {
        return $this->selectedFolder ?: $this->selectedProject;
    }

    public function getCanSaveProperty()
    {
        return $this->selectedProject && 
               ($this->assignTo === 'group' ? $this->selectedGroup : $this->selectedUser) &&
               count($this->selectedPermissions) > 0;
    }

    public function getProjectsProperty()
    {
        return Project::accessibleBy(auth()->user())->get();
    }

    public function getFoldersProperty()
    {
        if (!$this->selectedProject) return collect();
        
        return Folder::where('project_id', $this->selectedProject)
            ->withDepth()
            ->get()
            ->toTree();
    }

    public function getPermissionsProperty()
    {
        $type = $this->selectedFolder ? 'folder' : 'project';
        return config("permissions.types.$type", []);
    }

    public function userSelected($userId)
    {
        $this->selectedUser = $userId;
    }

    public function groupSelected($groupId)
    {
        $this->selectedGroup = $groupId;
    }

    public function savePermissions()
    {
        $this->validate();

        $model = $this->assignTo === 'user' 
            ? User::find($this->selectedUser)
            : Group::find($this->selectedGroup);

        $resource = $this->selectedFolder 
            ? Folder::find($this->selectedFolder)
            : Project::find($this->selectedProject);

        // Asignar permisos usando Spatie
        $model->givePermissionTo(
            $resource->permissions()->whereIn('name', $this->selectedPermissions)->get()
        );

        $this->reset(['selectedPermissions']);
        $this->dispatch('permissionsUpdated');
        session()->flash('message', 'Permisos actualizados correctamente.');
    }

    public function render()
    {
        return view('livewire.permission-manager');
    }
}
