<?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\Hash;
use Illuminate\Support\Facades\Log;
use Illuminate\Validation\Rules;
use Illuminate\View\View;

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

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

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

        try {
            // Kirim email verifikasi tanpa login user
            $user->sendEmailVerificationNotification();
            event(new Registered($user));
        } catch (\Exception $e) {
            Log::error('Email verification gagal: ' . $e->getMessage());
        }

        // ✅ TIDAK login, langsung redirect ke login dengan pesan
        return redirect()->route('login')
            ->with('status', 'Registrasi berhasil! Silakan cek email Anda untuk verifikasi akun sebelum login.');
    }
}