<?php

namespace App\Http\Livewire\Pages\Group;

use Livewire\Component;
use App\Models\Group;
class GroupCreate extends Component
{

    public $name ,$companies , $company;
    public $description;
    public $action;
    public $role_lists;
    public  $user_lists;
    protected $rules = [
        'name' => 'required',
    ];
    public function mount($companies)
    {
        $this->companies = $companies;
    }

    public function render()
    {
        return view('livewire.pages.group.group-create');
    }

    public function submitForm()
    {
        $validatedData = $this->validate([
            'name' => 'required'
        ]);
      
        $this->company = isset($this->company) && $this->company != null ? $this->company : $this->companies->first()->id ?? null;

        $groupeData = [
            'name' => $this->name,
            'company_id' => $this->company
        ];
        $group = Group::create($groupeData);
        $arr_role_lists = explode(",",$this->role_lists);
        $arr_user_lists = explode(",",$this->user_lists);
   
        if (!empty($this->role_lists)) {
            $group->roles()->sync($arr_role_lists);
        }
        // dd($group->roles);
        if (!empty($this->user_lists)) {
            $group->users()->sync($arr_user_lists);
        }

        // Reset form fields
        $this->reset([
            'name', 'company' ,'description', 'role_lists' , 'user_lists'
        ]);
        $this->emit('showGroupList', 'Group successfully created.');
    }
    public function goBack()
    {
        $this->emit('showGroupList', '');
    }
}
