<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Auth\Events\Registered;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\Rules;

class RegisteredUserController extends Controller
{
    public function create()
    {
        return view('auth.register');
    }

    public function store(Request $request): RedirectResponse
    {
        $request->validate([
            'name'     => ['required', 'string', 'max:255'],
            'email'    => ['required', 'email', 'unique:users,email'],
            'password' => ['required', 'confirmed', Rules\Password::defaults()],
            'otp'      => ['required', 'digits:6'],
        ]);

        // Cek OTP dari session
        if (
            session('register_email') !== $request->email ||
            session('register_otp') != $request->otp ||
            now()->gt(session('register_otp_expires_at'))
        ) {
            return back()->withErrors(['otp' => 'OTP salah atau sudah kadaluarsa'])->withInput();
        }

        $user = User::create([
            'name'        => $request->name,
            'email'       => $request->email,
            'password'    => Hash::make($request->password),
            'is_verified' => true,
        ]);

        event(new Registered($user));
        Auth::login($user);

        session()->forget(['register_email', 'register_otp', 'register_otp_expires_at']);

        return redirect()->route('dashboard')->with('success', 'Akun berhasil dibuat!');
    }
}