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

class RegisteredUserController extends Controller
{
    /**
     * Display the registration view.
     */
    public function create(Request $request, $referral_code = null): View|RedirectResponse
    {
        // If the user is already logged in, redirect them to their dashboard.
        if (Auth::check()) {
            $user = Auth::user();
            if ($user->role === 'admin') {
                return redirect()->route('admin.dashboard');
            }

            return redirect()->route('user.dashboard');
        }

        // Prioritize referral code from the URL, then from the session.
        if (!$referral_code) {
            $referral_code = session()->get('referral_code');
        }

        if ($referral_code) {
            session(['referral_code' => $referral_code]); // Store/update in session for the store method
        }

        return view('auth.register', compact('referral_code'));
    }

    /**
     * Handle an incoming registration request.
     *
     * @throws \Illuminate\Validation\ValidationException
     */
    public function store(Request $request): RedirectResponse
    {
        // Use referral_code from session if not in request
        if (!$request->filled('referral_code') && session()->has('referral_code')) {
            $request->merge(['referral_code' => session()->get('referral_code')]);
        }

        $request->validate([
            'name' => ['required', 'string', 'max:255'],
            'email' => ['required', 'string', 'lowercase', 'email', 'max:255', 'unique:'.User::class],
            'password' => ['required', 'confirmed', Rules\Password::defaults()],
            'referral_code' => ['nullable', 'string', 'exists:users,referral_code'],
        ]);

        $parentUser = null;
        if ($request->filled('referral_code')) {
            $parentUser = User::where('referral_code', $request->referral_code)->first();
        }

        // Generate a unique referral code for the new user
        do {
            $newUserReferralCode = md5(uniqid(rand(), true));
        } while (User::where('referral_code', $newUserReferralCode)->exists());

        $user = User::create([
            'name' => $request->name,
            'email' => $request->email,
            'password' => Hash::make($request->password),
            'parent_id' => $parentUser ? $parentUser->id : null,
            'referral_code' => $newUserReferralCode,
        ]);

        event(new Registered($user));

        Auth::login($user);

        // Clear the referral code from the session after it has been used
        session()->forget('referral_code');

        if ($user->role === 'admin') {
            return redirect(route('admin.dashboard'));
        }

        return redirect(route('user.dashboard'));
    }
}
