<?php

namespace App\Actions\Fortify;

use App\Models\User;
use App\Models\Prospecto;
use Laravel\Jetstream\Jetstream;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\ValidationException;
use Laravel\Fortify\Contracts\CreatesNewUsers;

class CreateNewUser implements CreatesNewUsers
{
    use PasswordValidationRules;

    public function create(array $input)
    {
        Validator::make($input, [
            'name' => ['required', 'string', 'max:255'],
            'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
            'telefono' => ['required', 'digits:10', 'unique:users,telefono'],
            'password' => $this->passwordRules(),
            'terms' => Jetstream::hasTermsAndPrivacyPolicyFeature() ? ['accepted', 'required'] : '',
        ])->validate();



         if (User::where('email', $input['email'])
        ->orWhere('telefono', $input['telefono'])
        ->exists()) {

          throw ValidationException::withMessages([
        'email' => ['El correo o teléfono ya están registrados.']
    ]);

        }

        $user = User::create([
            'name'      => $input['name'],
            'email'     => $input['email'],
            'telefono'  => $input['telefono'],
            'direccion' => "",
            'password'  => Hash::make($input['password']),
            'status' => 1
        ]);

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

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

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



        return $user;
    }
}
