<?php

namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\DB;

class EmailVerificationController extends Controller
{
    public function showForm(Request $request)
    {
        $email = $request->query('email');
        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_verification_code', $request->otp)
            ->first();

        if (!$user) {
            return back()->withErrors(['otp' => 'Kode OTP salah atau sudah digunakan.'])->withInput();
        }

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

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