<?php

namespace App\Components\Admin\Users;

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

class UserEdit extends Component
{
    public User $user;

    public string $name_first;
    public string $name_last;
    public string $email;
    public string $username;
    public ?string $password = null;
    public array $roles = [];

    public function mount(User $user)
    {
        $this->authorize('edit', $user);

        $this->fill([
            'name_first' => $user->name_first,
            'name_last'  => $user->name_last,
            'email'      => $user->email_address,
            'username'   => $user->username,
            'roles'      => $user->roles->pluck('name')->toArray(),
        ]);
    }

    public function save()
    {
        $this->user->update([
            'name_first'    => $this->name_first,
            'name_last'     => $this->name_last,
            'email_address' => $this->email,
            'username'      => $this->username,
        ]);

        if ($this->password) {
            $this->user->update([
                'password' => bcrypt($this->password),
            ]);
        }

        $this->user->syncRoles($this->roles);

        $this->dispatch('toast',
            title: 'Saved',
            message: 'Successfully saved data.',
            type: 'success'
        );
    }

    public function render() {
        return view('components.admin.users.user-edit', [
            'allRoles' => Role::orderBy('name')->get(),
        ]);
    }
}
