<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class StoreReferralCode
{
    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        if ($request->has('ref')) {
            // We only want to store the referral code if the user is not authenticated.
            // If they are authenticated, we don't need to track a new referral for them.
            if (!auth()->check()) {
                session(['referral_code' => $request->query('ref')]);
            }
        }

        return $next($request);
    }
}
