<?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\Support\Facades\Session;
use Illuminate\Validation\Rules;
use Inertia\Inertia;
use Inertia\Response;

class RegisteredUserController extends Controller
{
    /**
     * Show the registration page.
     */
    public function create(): Response
    {
        // Generate captcha for registration
        $captcha = $this->generateCaptcha();
        
        return Inertia::render('auth/register', [
            'captcha' => $captcha
        ]);
    }

    /**
     * Generate a random 6-digit captcha and store in session
     */
    private function generateCaptcha(): string
    {
        $captcha = str_pad(rand(0, 999999), 6, '0', STR_PAD_LEFT);
        Session::put('registration_captcha', $captcha);
        return $captcha;
    }

    /**
     * Handle an incoming registration request.
     *
     * @throws \Illuminate\Validation\ValidationException
     */
    public function store(Request $request): RedirectResponse
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'email' => 'required|string|lowercase|email|max:255|unique:' . User::class,
            'phone_number' => 'required|string|max:255|unique:' . User::class,
            'password' => ['required', Rules\Password::defaults()],
            'verification_code' => 'required|string|size:6',
            'captcha_code' => 'required|string|size:6',
            'accept_term_condition' => ['required', 'accepted'],
        ]);

        // Verify captcha from session
        $sessionCaptcha = Session::get('registration_captcha');
        if (!$sessionCaptcha || $request->verification_code !== $sessionCaptcha) {
            return back()->withErrors([
                'verification_code' => 'Kode verifikasi tidak sesuai dengan captcha.',
            ])->withInput();
        }

        // Additional validation: ensure verification code is numeric
        if (!is_numeric($request->verification_code)) {
            return back()->withErrors([
                'verification_code' => 'Kode verifikasi harus berupa angka.',
            ])->withInput();
        }

        // Clear the captcha from session after successful verification
        Session::forget('registration_captcha');

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

        event(new Registered($user));

        // Log in the user automatically and redirect to dashboard
        Auth::login($user);

        return redirect()->route('home')->with('status', 'Akaun berjaya dibuat! Selamat datang ke Bank Negara Malaysia.');
    }
}
