<?php

namespace App\Components\Admin\Users;

use App\Models\User\Role;
use App\Models\User\User;
use App\Components\Admin\Users\UserEdit;
use App\Services\HistoryService;
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 array $allowedWorkspaces = [];
    public bool $allWorkspaces = true;

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

    public function save(HistoryService $history) {
        $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']),
            'allowed_workspaces' => $this->allWorkspaces
                ? null
                : array_values(array_intersect($this->allowedWorkspaces, UserEdit::WORKSPACES)),
        ]);

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

        $history->add($user, 'User account created', [
            'user_id'  => $user->id,
            'username' => $user->username,
            'email'    => $user->email_address,
            'roles'    => $user->roles->pluck('name')->values()->toArray(),
        ]);

        return redirect()->route('admin.users.show', $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', [
            'roles' => Role::orderBy('name')->get(),
        ]);
    }
}
