<?php

namespace App\Http\Controllers\Public;

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

/**
 * PublicContributorRegistrationController
 * 
 * Handles public registration for contributors.
 * This controller manages the registration flow when visitors
 * attempt to contribute to the discussion board.
 * 
 * @package App\Http\Controllers\Public
 */
class PublicContributorRegistrationController extends Controller
{
    /**
     * Create a new controller instance.
     */
    public function __construct(
        protected RegistrationService $registrationService
    ) {}

    /**
     * Show the contributor registration form.
     *
     * @param \Illuminate\Http\Request $request
     * @return \Illuminate\View\View
     */
    public function showRegistrationForm(Request $request): View
    {
        // If user is already logged in, redirect to contributor dashboard
        if (auth()->check()) {
            return redirect()->route('contributor.dashboard');
        }

        // Store the intended URL if provided (where user was trying to go)
        if ($request->has('intended')) {
            session()->put('registration_intended', $request->get('intended'));
        }

        // Store any draft contribution data
        if ($request->has('draft')) {
            session()->put('draft_contribution', $request->get('draft'));
        }

        return view('public.auth.register');
    }

    /**
     * Handle contributor registration.
     *
     * @param \Illuminate\Http\Request $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function register(Request $request): RedirectResponse
    {
        // Validate input
        $validated = $request->validate([
            'name' => 'required|string|max:191',
            'email' => 'required|string|email|max:191|unique:users,email',
            'password' => 'required|string|min:8|confirmed',
            'terms' => 'required|accepted',
        ], [
            'name.required' => 'Please enter your name.',
            'name.max' => 'Name cannot exceed 191 characters.',
            'email.required' => 'Please enter your email address.',
            'email.email' => 'Please enter a valid email address.',
            'email.unique' => 'This email is already registered. Please log in instead.',
            'password.required' => 'Please enter a password.',
            'password.min' => 'Password must be at least 8 characters.',
            'password.confirmed' => 'Password confirmation does not match.',
            'terms.required' => 'You must accept the terms and conditions.',
            'terms.accepted' => 'You must accept the terms and conditions.',
        ]);

        // Register the contributor
        $user = $this->registrationService->registerContributor($validated);

        // Log the user in
        Auth::login($user);

        // Clear any stored draft data
        $draftContribution = session()->pull('draft_contribution');
        $intendedUrl = session()->pull('registration_intended');

        // Redirect to intended URL or contributor dashboard
        if ($intendedUrl) {
            return redirect($intendedUrl)
                ->with('success', 'Welcome! Your contributor account has been created successfully.');
        }

        // If there was draft data, redirect to create discussion with that data
        if ($draftContribution) {
            return redirect()->route('knowledge-sharing.discussions.create')
                ->with('success', 'Welcome! Your contributor account has been created. You can now create your discussion.')
                ->withInput($draftContribution);
        }

        return redirect()->route('contributor.dashboard')
            ->with('success', 'Welcome! Your contributor account has been created successfully.');
    }

    /**
     * Show the login form for contributors.
     *
     * @param \Illuminate\Http\Request $request
     * @return \Illuminate\View\View
     */
    public function showLoginForm(Request $request): View
    {
        // If user is already logged in, redirect appropriately
        if (auth()->check()) {
            if (auth()->user()->hasRole('Contributor') && !auth()->user()->hasAnyRole(['Super Manager', 'Manager'])) {
                return redirect()->route('contributor.dashboard');
            }
            return redirect()->route('dashboard');
        }

        // Store intended URL
        if ($request->has('intended')) {
            session()->put('url.intended', $request->get('intended'));
        }

        return view('public.auth.login');
    }

    /**
     * Show the "Become a Contributor" page.
     * This is the landing page for potential contributors.
     *
     * @return \Illuminate\View\View
     */
    public function showBecomeContributor(): View
    {
        return view('public.auth.become-contributor');
    }

    /**
     * Check if email exists and redirect appropriately.
     * Used for the "Continue" flow in contribution prompt.
     *
     * @param \Illuminate\Http\Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function checkEmail(Request $request)
    {
        $request->validate([
            'email' => 'required|string|email',
        ]);

        $exists = $this->registrationService->isEmailRegistered($request->email);

        return response()->json([
            'exists' => $exists,
            'redirect' => $exists 
                ? route('public.contributor.login', ['intended' => session('registration_intended', url()->previous())])
                : route('public.contributor.register', ['intended' => session('registration_intended', url()->previous())]),
        ]);
    }
}
