<?php

namespace App\Components\Admin\Users;

use App\Models\Solicitor\Solicitor;
use App\Models\User\Role;
use App\Models\User\User;
use App\Services\HistoryService;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Livewire\Component;

class UserCreate extends Component {
    use AuthorizesRequests;
    public string $name_first = '';
    public string $name_last = '';
    public string $email = '';
    public string $username = '';
    public string $password = '';
    public $roles;
    public $selectedRoles;
    public ?int $solicitor_id = null;
    public ?string $wip_grade = null;

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

    public function save(HistoryService $historyService) {
        $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']),
            'solicitor_id' => $data['solicitor_id'],
            'wip_grade' => $data['wip_grade'],
        ]);

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

        $historyService->add(
            auth()->user(),
            "Created user '{$user->name_first} {$user->name_last}' ({$user->email_address})",
            [
                'target_user_id' => $user->id,
                'roles'          => (array) $this->selectedRoles,
            ]
        );

        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',
            'solicitor_id' => 'nullable|exists:solicitors,id',
            'roles' => 'array',
            'wip_grade' => 'nullable|in:C,D',
        ];
    }

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