<?php

namespace App\Http\Livewire\Pages\Role;

use Livewire\Component;
use App\Models\Role;
use App\Models\Permission;
use Illuminate\Http\Request;

class RoleEdit extends Component
{
    public $editRoleId;
    public $permissions;
    public $roleId;
    public $role;
    public $name;
    public $description;
    public $permissionLists = [];
    protected $rules = [
        'role.name' => 'required',
    ];
    public function mount($editRoleId, $permissions)
    {
        $this->editRoleId = $editRoleId;
        $this->permissions = $permissions;
        $this->role = Role::findOrFail($editRoleId);
        $this->name = $this->role->name;
        $this->description = $this->role->description;
        $this->permissionLists = $this->role->permissions->pluck('id')->toArray();
        $this->permissions = Permission::all();
    }
    public function render()
    {
        $permissionLists = $this->permissionLists;
        return view('livewire.pages.role.role-edit', compact('permissionLists'));
    }

    public function submitEditForm($selectedList)
    {
        // $this->validate();
        $this->permissionLists = array_map('intval', $selectedList);
        $this->role->name = $this->name;
        $this->role->description = $this->description;
        $this->role->permissions()->sync($this->permissionLists);
        $this->role->save();
       
        $this->emit('showRoleList', 'Role successfully updated.');
    }
    public function goBack()
    {
        $this->emit('showRoleList', '');
    }
}
