<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\User;

class OtpVerificationController extends Controller
{
    public function showForm(Request $request)
    {
        $email = session('email');
        if (!$email) {
            return redirect()->route('register')->with('error', 'Email tidak ditemukan.');
        }

        return view('auth.verify-otp', compact('email'));
    }

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

        $user = User::where('email', $request->email)
                    ->where('email_otp', $request->otp)
                    ->first();

        if (!$user) {
            return back()->with('error', 'Kode OTP salah atau tidak valid.');
        }

        $user->email_verified_at = now();
        $user->email_otp = null;
        $user->save();

        return redirect()->route('login')->with('success', 'Email berhasil diverifikasi! Silakan login.');
    }
}



