<?php

namespace App\Http\Livewire\Pages\FormatFileMaster;

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

class FormatFileEdit extends Component
{
    public $editRoleId;
    public $permissions;
    public $roleId;
    public $role;
    public $name, $description, $permission_lists = [];
    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->permission_lists = $this->role->permissions->pluck('id')->toArray();
        $this->permissions = Permission::all();
    }
    public function render()
    {
        $permission_lists = $this->permission_lists;
        return view('livewire.pages.role.role-edit', compact('permission_lists'));
    }

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