<?php

namespace App\Components\Admin\Users;

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

class UserCreate extends Component {
    public string $name_first = '';
    public string $name_last = '';
    public string $email = '';
    public string $username = '';
    public string $password = '';
    public $roles;
    public $selectedRoles;

    public function mount() {
        $this->authorize('users.create');
        $this->roles = Role::orderBy('name')->get();
    }

    public function save() {
        $this->authorize('create', User::class);

        $data = $this->validate();

        $user = User::create([
            'name_first' => $data['name_first'],
            'name_last' => $data['name_last'],
            'username' => $data['username'],
            'email_address' => $data['email'],
            'password' => bcrypt($data['password']),
        ]);

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

        return redirect()->route('admin.users.profile', $user);
    }

    protected function rules(): array {
        return [
            'name_first' => 'required|string|max:100',
            'name_last' => 'required|string|max:100',
            'username' => 'required|unique:users,username',
            'email' => 'required|email|unique:users,email_address',
            'password' => 'required|min:12',
            'roles' => 'array',
        ];
    }

    public function render() {
        return view('components.admin.users.user-create');
    }
}
