<?php

namespace App\Http\Controllers\Frontend;

use App\Http\Controllers\Controller;
use App\Mail\VerifyEmailMail;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\URL;

class EmailVerificationController extends Controller
{
    public function notice()
    {
        if (auth()->user()->email_verified_at) {
            return redirect()->route('home');
        }
        return view('frontend.auth.verify-email');
    }

    public function verify(Request $request, int $id, string $hash)
    {
        $user = \App\Models\User::findOrFail($id);

        if (!hash_equals(sha1($user->email), $hash)) {
            abort(403);
        }

        if (!$user->email_verified_at) {
            $user->email_verified_at = now();
            $user->save();
        }

        return redirect()->route('home')->with('status', 'E-posta adresin doğrulandı!');
    }

    public function resend(Request $request)
    {
        $user = $request->user();

        if ($user->email_verified_at) {
            return back()->with('status', 'E-posta zaten doğrulanmış.');
        }

        $url = URL::temporarySignedRoute(
            'verification.verify',
            now()->addHours(24),
            ['id' => $user->id, 'hash' => sha1($user->email)]
        );

        Mail::to($user->email)->send(new VerifyEmailMail($url, $user->name));

        return back()->with('status', 'Doğrulama e-postası tekrar gönderildi.');
    }

    public static function sendVerificationMail(\App\Models\User $user): void
    {
        $url = URL::temporarySignedRoute(
            'verification.verify',
            now()->addHours(24),
            ['id' => $user->id, 'hash' => sha1($user->email)]
        );
        Mail::to($user->email)->send(new VerifyEmailMail($url, $user->name));
    }
}
