<?php

namespace App\Http\Livewire\Pages\Role;

use Livewire\Component;
use App\Models\Role;

class RoleCreate extends Component
{

    public $name;
    public $description;
    public $permissions;
    public $action;
    public $permission_lists = [];
    public $permission_lists_temp = [];
    protected $rules = [
        'name' => 'required',
    ];
    public function mount($permissions)
    {
        $this->permissions = $permissions;
    }
    public function render()
    {
        return view('livewire.pages.role.role-create');
    }

    public function submitForm($selectedList)
    {
        $validatedData = $this->validate([
            'name' => 'required',
            'description' => 'nullable',
            'permission_lists' => 'array',
        ]);
        $this->permission_lists = $selectedList;
        $roleData = [
            'name' => $this->name,
            'description' => $this->description,
        ];

        $role = Role::create($roleData);

        if (!empty($this->permission_lists)) {
            $role->permissions()->sync($this->permission_lists);
        }

        // Reset form fields
        $this->reset([
            'name', 'description', 'permission_lists'
        ]);
        $this->emit('showRoleList', 'Role successfully created.');
    }
    public function goBack()
    {
        $this->emit('showRoleList', '');
    }
}
