<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Mail;
use App\Models\User;
use App\Models\Setting;
use App\Mail\VerificationMail;

class VerificationController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth')->except(['showVerificationForm', 'verify', 'resendCode']);
    }

    public function showVerificationForm(Request $request)
    {
        $settings = Setting::first();
        $unverifiedUserId = $request->session()->get('unverified_user_id');
        if ($unverifiedUserId) {
            $user = User::find($unverifiedUserId);
            return view('auth.verify', compact('settings', 'user'));
        } else {
            return redirect()->route('login')->with('message', 'Please login to verify your email.');
        }
    }

    public function verify(Request $request)
    {
        $request->validate([
            'verification_code' => 'required|numeric|digits:6',
        ]);

        $unverifiedUserId = $request->session()->get('unverified_user_id');
        $user = User::where('verification_code', $request->verification_code)
                    ->where('id', $unverifiedUserId)
                    ->first();

        if ($user) {
            $user->email_verified_at = now();
            $user->verification_code = null;
            $user->email_verified = 1;
            $user->save();

            $request->session()->forget('unverified_user_id');

            return redirect('/login')->with('message', 'Email verified successfully! Please login.');
        } else {
            return back()->withErrors(['verification_code' => 'Invalid verification code.']);
        }
    }

    public function resendCode(Request $request)
    {
        $unverifiedUserId = $request->session()->get('unverified_user_id');
        if ($unverifiedUserId) {
            $user = User::find($unverifiedUserId);
            $verification_code = rand(100000, 999999);
            $user->verification_code = $verification_code;
            $user->save();

            Mail::to($user->email)->send(new VerificationMail($user));

            return back()->with('message', 'Verification code has been resent.');
        } else {
            return redirect()->route('login')->with('message', 'Please login to resend the verification code.');
        }
    }
}
