<?php

namespace App\Http\Livewire\Pages\Group;

use Livewire\Component;
use App\Models\Group;
use App\Models\Permission;

class GroupEdit extends Component
{
    public $editGroupId;
    public $permissions;
    public $groupId;
    public $group;
    public $name ,$companies , $company;
    public $role_lists;
    public  $user_lists;

    protected $rules = [
        'name' => 'required',
        // 'group.company_id' => 'required',
    ];
    public function mount($editGroupId, $roles, $users, $companies)
    {
        $this->editGroupId = $editGroupId;
        $this->group = Group::findOrFail($editGroupId);
        $this->name = $this->group->name;
        $this->company = $this->group->company_id;

    }
    public function render()
    {
        $groupRoles =  $this->group->roles()->pluck('role_id')->toArray();
        $groupUsers =  $this->group->users()->pluck('user_id')->toArray();
        return view('livewire.pages.group.group-edit' , [
            'groupRoles' => $groupRoles,
            'groupUsers' => $groupUsers
        ]);
    }

    public function submitEditForm()
    {
        $this->validate();
  
      
        $this->company = isset($this->company) && $this->company != null ? $this->company : $this->companies->first()->id ?? null;

        $groupeData = [
            'name' => $this->name,
            'company_id' => $this->company
        ];

        $this->group->update($groupeData);

        $arr_role_lists = explode(",",$this->role_lists);
        $arr_user_lists = explode(",",$this->user_lists);
        $this->group->roles()->sync($arr_role_lists);
        $this->group->users()->sync($arr_user_lists);

        $this->emit('showGroupList', 'Group successfully updated.');
    }
    public function goBack()
    {
        $this->emit('showGroupList', '');
    }
}
