<?php

namespace App\Actions\Fortify;

use App\Models\User;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Laravel\Fortify\Contracts\CreatesNewUsers;
use Laravel\Jetstream\Jetstream;
use Haruncpi\LaravelIdGenerator\IdGenerator;
class CreateNewUser implements CreatesNewUsers
{
    use PasswordValidationRules;

    /**
     * Validate and create a newly registered user.
     *
     * @param  array  $input
     * @return \App\Models\User
     */
    public function create(array $input)
    {
        Validator::make($input, [
            'name' => ['required', 'string', 'max:255'],
            'username' => ['required', 'string', 'max:255'],
            'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
            'password' => $this->passwordRules(),
            'terms' => Jetstream::hasTermsAndPrivacyPolicyFeature() ? ['required', 'accepted'] : '',
        ])->validate();

        $id = IdGenerator::generate(['table' => 'users', 'field' => 'iduser', 'length' => 6, 'prefix' => 'USR']);
        return User::create([
            'iduser' => $id,
            'name' => $input['name'],
            'username' => $input['username'],
            'level' => 'administrator',
            'email' => $input['email'],
            'isactive' => '1',
            'created_at' => date('Y-m-d H:i:s'),
            'password' => Hash::make($input['password']),
        ]);
    }
}
