<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Auth\Events\Verified;
use App\Models\User;

class VerificationController extends Controller
{
    public function __construct()
    {
        //
    }

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

        if (! hash_equals((string) $hash, sha1($user->getEmailForVerification()))) {
            return response()->json(["msg" => "Invalid link or already verified"], 422);
        }

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

        return response()->json(["msg" => "Email verified successfully!"]);
    }

    public function resend(Request $request)
    {
        $user = User::where('email', $request->email)->first();

        if (!$user) {
            return response()->json(["message" => "User not found."], 404);
        }

        if ($user->hasVerifiedEmail()) {
            return response()->json(["message" => "Email is already verified."], 400);
        }

        $user->sendEmailVerificationNotification();

        return response()->json(["message" => "Verification link sent."]);
    }
}
