<?php

namespace App\Actions\Fortify;

use App\Mail\NewUserRegistered;
use App\Models\Setting;
use App\Models\User;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
use Laravel\Fortify\Contracts\CreatesNewUsers;

class CreateNewUser implements CreatesNewUsers
{
    use PasswordValidationRules;

    /**
     * Validate and create a newly registered user.
     *
     * @param  array<string, string>  $input
     */
    public function create(array $input): User
    {
        Validator::make($input, [
            ...User::nameValidationRules(),
            'email' => [
                'required',
                'string',
                'email',
                'max:255',
                Rule::unique(User::class),
            ],
            'password' => $this->passwordRules(),
            'timezone' => ['nullable', 'string', 'timezone:all'],
        ], [
            'email.unique' => 'This email already has a profile. Use the forgot password to create a new password if this is your first time here.',
        ])->validate();

        $user = User::create([
            'first_name' => $input['first_name'],
            'last_name' => $input['last_name'],
            'email' => $input['email'],
            'password' => $input['password'],
            'timezone' => $input['timezone'] ?? Setting::get('default_timezone') ?? config('app.timezone'),
        ]);

        // Notify admins who have opted in to receive new user alerts
        $adminsToNotify = User::where('is_admin', true)
            ->where('receive_new_user_alerts', true)
            ->get();

        foreach ($adminsToNotify as $admin) {
            Mail::to($admin)->send(new NewUserRegistered($user));
        }

        return $user;
    }
}
