<?php

namespace App\Http\Livewire\Pages\User;

use Livewire\Component;
use App\Models\User;
use Illuminate\Support\Facades\Hash;

class UserEdit extends Component
{
    public $editUserId;
    public $userId;
    public $user;
    public $username, $first_name , $last_name, $phone ,$email, $current_password, $new_password, $new_password_confirmation ,$changePassword = false ;
    public $group_lists;

    protected function rules()
    {
        $rules = [
            'username' => 'required|string|max:255',
            'email' => 'required|string|email|max:255|unique:users,email,' . $this->user->id,
        ];

        if ($this->changePassword) {
            $rules['current_password'] = 'required|string|min:8';
            $rules['new_password'] = 'nullable|string|min:8|confirmed';
        }

        return $rules;
    }

    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.',
        'current_password.required' => 'The current password field is required.',
        'current_password.min' => 'The current password must be at least 8 characters.',
        'new_password.min' => 'The new password must be at least 8 characters.',
        'new_password.confirmed' => 'The new password confirmation does not match.',
    ];

    public function mount($editUserId)
    {
        $this->editUserId = $editUserId;
        $this->user = User::findOrFail($editUserId);
        $this->username = $this->user->username;
        $this->first_name = $this->user->first_name;
        $this->last_name = $this->user->last_name;
        $this->phone = $this->user->phone;
        $this->email = $this->user->email;
        $this->group_lists = $this->user->groups()->pluck('group_id')->implode(',');
    }

    public function render()
    {
        $userGroups = $this->user->groups()->pluck('group_id')->toArray();

        return view('livewire.pages.user.user-edit', [
            'userGroups' => $userGroups,
        ]);
    }

    public function submitEditForm()
    {
        $this->validate();
  
      
        if ($this->changePassword && !Hash::check($this->current_password, $this->user->password)) {
            $this->addError('current_password', 'The current password is incorrect.');
            return;
        }
        $this->user->username = $this->username;
        $this->user->email = $this->email;
        $this->first_name = $this->user->first_name;
        $this->last_name = $this->user->last_name;
        $this->phone = $this->user->phone;
        
        if ($this->changePassword) {
            $this->user->password = Hash::make($this->new_password);
        }
        $this->user->save();

        if (!empty($this->group_lists)) {
            if(!is_array($this->group_lists)) {
                $arr_group_lists = explode(",", $this->group_lists);
            }else{
                $arr_group_lists = $this->group_lists;
            }
            
            if (!empty($arr_group_lists)) {
                $this->user->groups()->sync($arr_group_lists);
            } else {
                $this->user->groups()->sync([]);
            }
        } else {
            $this->user->groups()->sync([]);
        }

        $this->reset(['current_password']); // Clear the password field after saving

        $this->emit('showUserList', 'User successfully updated.');
    }

    public function goBack()
    {
        $this->emit('showUserList', '');
    }
}
