<?php

namespace App\Http\Controllers;

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

class VerificationController extends Controller
{
    public function showForm(Request $request)
    {
        if (!$request->session()->has('pending_user_id')) {
            return redirect()->route('login')->with('error', 'Silakan daftar atau login terlebih dahulu.');
        }
        return view('auth.verify');
    }

    public function verify(Request $request)
    {
        $request->validate([
            'code' => ['required', 'digits:6'],
        ]);
        $userId = $request->session()->get('pending_user_id');
        $user = User::find($userId);
        if (!$user) {
            return redirect()->route('login')->with('error', 'User tidak ditemukan.');
        }
        if ($user->email_verification_code !== $request->code) {
            return back()->withErrors(['code' => 'Kode verifikasi salah.'])->withInput();
        }
        $user->email_verified_at = now();
        $user->email_verification_code = null;
        $user->save();
        Auth::login($user);
        $request->session()->forget('pending_user_id');
        $request->session()->regenerate();
        return redirect()->route('absensi.history')->with('status', 'Verifikasi email berhasil. Akun Anda sudah aktif.');
    }
}
