<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Http\Requests\RegisterRequest;
use App\Services\RegistrationService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;
use Illuminate\Support\Facades\Auth;

class RegisterController extends Controller
{
    protected RegistrationService $registrationService;

    public function __construct(RegistrationService $registrationService)
    {
        $this->registrationService = $registrationService;
    }

    /**
     * Show the registration form.
     */
    public function showRegistrationForm(): View
    {
        $roles = $this->registrationService->getAvailableRoles();
        return view('auth.register', compact('roles'));
    }

    /**
     * Handle a registration request for the application.
     */
    public function register(RegisterRequest $request): RedirectResponse
    {
        $user = $this->registrationService->register($request->validated());

        // Auto-login after registration (optional - can be removed for email verification requirement)
        Auth::login($user);

        // Redirect to verification notice if email not verified
        if (!$user->hasVerifiedEmail()) {
            return redirect()->route('verification.notice')
                ->with('status', 'Registration successful! Please verify your email address.');
        }

        return redirect()->to($user->getDashboardUrl())
            ->with('status', 'Welcome! Your account has been created successfully.');
    }

    /**
     * Get role-specific registration fields via AJAX.
     */
    public function getRoleFields(Request $request): JsonResponse
    {
        $request->validate([
            'role' => ['required', 'string', 'exists:roles,name'],
        ]);

        $fields = $this->registrationService->getRoleSpecificFields($request->role);

        return response()->json([
            'success' => true,
            'fields' => $fields,
        ]);
    }

    /**
     * Check username availability via AJAX.
     */
    public function checkUsername(Request $request): JsonResponse
    {
        $request->validate([
            'username' => ['required', 'string', 'min:3', 'alpha_dash'],
        ]);

        $available = $this->registrationService->isUsernameAvailable($request->username);

        return response()->json([
            'available' => $available,
            'message' => $available ? 'Username is available!' : 'Username is already taken.',
        ]);
    }

    /**
     * Check email availability via AJAX.
     */
    public function checkEmail(Request $request): JsonResponse
    {
        $request->validate([
            'email' => ['required', 'string', 'email'],
        ]);

        $available = $this->registrationService->isEmailAvailable($request->email);

        return response()->json([
            'available' => $available,
            'message' => $available ? 'Email is available!' : 'Email is already registered.',
        ]);
    }
}
