<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Models\User;
use App\Services\RecaptchaService;
use App\Support\TemplatedMailer;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;

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

    public function register(Request $request)
    {
        $data = $request->validate([
            'name'     => ['required', 'string', 'max:255'],
            'username' => ['required', 'alpha_dash', 'min:3', 'max:30', 'unique:users,username'],
            'email'    => ['required', 'email', 'unique:users,email'],
            'password' => ['required', 'string', 'min:8', 'confirmed'],
        ]);

        if (recaptcha_enabled() && setting('recaptcha_on_register', true)) {
            if (!RecaptchaService::verify($request->input('g-recaptcha-response'))) {
                return back()->withErrors(['email' => 'Captcha verification failed.'])->withInput();
            }
        }

        $user = User::create([
            'name'     => $data['name'],
            'username' => $data['username'],
            'email'    => $data['email'],
            'password' => Hash::make($data['password']),
            'role'     => 'user',
            'status'   => 'active',
        ]);

        TemplatedMailer::send(
            $user,
            'email_template_welcome_subject',
            'email_template_welcome_body'
        );

        Auth::login($user);
        return redirect('/dashboard')->with('success', 'Welcome aboard!');
    }
}
