<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Actions\Fortify\CreateNewUser;
use Illuminate\Auth\Events\Registered;
use Illuminate\Foundation\Auth\EmailVerificationRequest;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Redirect;

use Illuminate\Auth\Events\Verified;

use App\Models\User;
use App\Models\PendingUser;

use App\Mail\NewUserNotification;
use Illuminate\Support\Facades\Mail;


class CustomRegistrationController extends Controller
{
    public function store(Request $request): RedirectResponse
    {
        $user = app(CreateNewUser::class)->create($request->all());

        event(new Registered($user));
        // Chame sendEmailVerificationNotification para enviar o e-mail de verificação
        $user->sendEmailVerificationNotification();


        $pendingUser = PendingUser::where('pending_email', $user->email)->first();
        if ($pendingUser) {
            $pendingUser->delete();
        }

        return $request->wantsJson()
            ? new JsonResponse([], 201)
            : Redirect::to('/CreateUsers')->with('success', 'Usuário criado com sucesso, aguarda confirmacao por Email!!');
    }


    public function yourVerificationMethod(Request $request, $id, $hash)
    {
        $user = User::findOrFail($id);

        if (!hash_equals((string) $hash, sha1($user->getEmailForVerification()))) {
            abort(403, 'Unauthorized action.');
        }

        if ($user->markEmailAsVerified()) {
            event(new Verified($user));
        }

        // Redirecione para a rota desejada após a verificação bem-sucedida
        return redirect()->route('CreateUsers')->with('message', 'E-mail verificado com sucesso!');
    }
}
