<?php

namespace App\Actions\Fortify;

use App\Models\Alumno;
use App\Models\User;
use Illuminate\Auth\Notifications\ResetPassword;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Password;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
use Laravel\Fortify\Contracts\CreatesNewUsers;
use Laravel\Jetstream\Jetstream;

class CreateNewUser implements CreatesNewUsers
{
    use PasswordValidationRules;

    public function create(array $input)
    {

        if( $input['plantels'] == 0){
            throw ValidationException::withMessages([
            'plantels' => ['Debes elegir un plantel']
            ]);
        }

        Validator::make($input, [
            'name' => ['required', 'string', 'max:255'],
            'apellidoPaterno' => ['required', 'string', 'max:255'],
            'apellidoMaterno' => ['required', 'string', 'max:255'],
            'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
            'telefono' => ['required', 'digits:10', 'unique:users,telefono'],
            'terms' => Jetstream::hasTermsAndPrivacyPolicyFeature() ? ['accepted', 'required'] : '',
        ])->validate();

        $passwordTemporal = Str::random(12);

        $user = User::create([
            'name' => mb_strtoupper($input['name'], 'UTF-8'),
            'apellidoPaterno' => mb_strtoupper($input['apellidoPaterno'], 'UTF-8'),
            'apellidoMaterno' => mb_strtoupper($input['apellidoMaterno'], 'UTF-8'),
            'email'     => $input['email'],
            'telefono'  => $input['telefono'],
            'direccion' => "",
            'password' => Hash::make($passwordTemporal),
            'status' => 1
        ]);

        $user->roles()->sync([4]);
        $user->plantelUsuarios()->sync($input['plantels']);

        $prospecto = Alumno::create([
            'nivel'            => 0,
            'plan_id'          => 0,
            'usuario_registro' => 0,
            'ciclo'            => 0,
            'turno'            => 0,
            'medio'            => 0,
        ]);

        $prospecto->alumnos()->sync([$user->id]);

        $token = Password::createToken($user);
        $user->notify(new ResetPassword($token));

        return $user;
    }
}
