<?php

namespace App\Http\Livewire\Pages\User;

use Livewire\Component;
use App\Models\User;
use Illuminate\Support\Facades\Hash;
use Str;
class UserCreate extends Component
{

    public $username, $first_name , $last_name, $phone , $email ,$password , $password_confirmation;
    public $description;
    public $action;
    public $group_lists;
    protected $rules = [
        'username' => 'required|string|max:255',
        'email' => 'required|string|email|max:255|unique:users,email',
        'password' => 'required|string|min:8|confirmed', 
    ];

    protected $messages = [
        'username.required' => 'The username field is required.',
        'email.required' => 'The email field is required.',
        'email.email' => 'The email must be a valid email address.',
        'email.unique' => 'This email address is already taken.',
        'password.required' => 'The password field is required.',
        'password.min' => 'The password must be at least 8 characters.',
        'password.confirmed' => 'The password confirmation does not match.',
    ];
    public function mount()
    {
    }

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

    public function submitForm()
    {
        $this->validate();
        $UsereData = [
            'username' => $this->username,
            'first_name' => $this->first_name,
            'last_name' => $this->last_name,
            'phone' => $this->phone,
            'uid' => Str::random(40),
            'email' => $this->email,
            'password' => Hash::make($this->password)
        ];

        $User = User::create($UsereData);
        if (!empty($this->group_lists)) {
            $arr_group_lists = explode(",", $this->group_lists);
            if (!empty($arr_group_lists)) {
                $User->groups()->sync($arr_group_lists);
            } else {
                $User->groups()->sync([]);
            }
        } else {
            $User->groups()->sync([]);
        }

        $this->reset([
            'username', 'email', 'description', 'group_lists'
        ]);
        if (auth()->guest()) {
            return redirect()->route('login'); 
        }
        $this->emit('showUserList', 'User successfully created.');
    }
    public function goBack()
    {
        if (auth()->guest()) {
            return redirect()->route('login'); 
        }
        $this->emit('showUserList');
    }
}
