<?php

namespace App\Http\Controllers\Earn;

use App\Enums\EarnMemberStatus;
use App\Http\Controllers\Controller;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;

class EarnVerificationController extends Controller
{
    public function notice(): View|RedirectResponse
    {
        if (auth('earn')->user()->hasVerifiedEmail()) {
            return redirect()->route('earn.dashboard');
        }

        return view('earn-auth.verify');
    }

    public function send(): RedirectResponse
    {
        if (! auth('earn')->user()->hasVerifiedEmail()) {
            auth('earn')->user()->sendEmailVerificationNotification();
        }

        return back()->with('status', __('earn_portal.verification_sent'));
    }

    public function verify(Request $request): RedirectResponse
    {
        $member = auth('earn')->user();
        abort_unless((string) $member->getKey() === (string) $request->route('id'), 403);
        abort_unless(hash_equals((string) $request->route('hash'), sha1($member->getEmailForVerification())), 403);

        if (! $member->hasVerifiedEmail()) {
            $member->forceFill(['email_verified_at' => now(), 'status' => EarnMemberStatus::Active])->save();
        }

        return redirect()->route('earn.dashboard');
    }
}
