<?php

namespace App\Http\Middleware;

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

class AffiliateReferralMiddleware
{
    /**
     * 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')) {
            $refCode = $request->query('ref');
            $referrer = \App\Models\User::where('affiliate_code', $refCode)->first();
            if ($referrer) {
                // Store referrer ID in session
                session(['referred_by_id' => $referrer->id]);
                // Queue a cookie for 30 days
                cookie()->queue('referred_by_id', $referrer->id, 60 * 24 * 30);
            }
        }

        return $next($request);
    }
}
