<?php
 namespace App\Http\Middleware; use App\Services\VisitorService; use Closure; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Cookie; use Symfony\Component\HttpFoundation\Response; class TrackVisitor { public function __construct(private VisitorService $visitorService) {} public function handle(Request $request, Closure $next): Response { $visitorId = $this->visitorService->getOrCreateVisitorId($request); $request->attributes->set('visitor_id', $visitorId); $this->visitorService->setEntryInfo($visitorId, $request); $ipAddress = $request->ip(); $this->visitorService->setIpAddress($visitorId, $ipAddress); $this->visitorService->setCountryFromIp($visitorId, $ipAddress); $browserLanguage = $this->visitorService->extractBrowserLanguage($request); if ($browserLanguage) { $this->visitorService->setBrowserLanguage($visitorId, $browserLanguage); } $determinedLanguage = $this->visitorService->determineVisitorLanguage($visitorId); $this->visitorService->setVisitorLanguage($visitorId, $determinedLanguage); $this->visitorService->setCreatedAt($visitorId); $affiliateId = $this->visitorService->extractAffiliateId($request); if ($affiliateId) { $this->visitorService->setAffiliateId($visitorId, $affiliateId); } $clientId = Auth::guard('client')->check() ? Auth::guard('client')->id() : null; if ($clientId) { $existingVisitorId = $this->visitorService->findVisitorByUserId($clientId); if ($existingVisitorId && $existingVisitorId !== $visitorId) { \App\Helpers\VisitorHelper::mergeVisitorBasket($existingVisitorId, $visitorId); } $this->visitorService->linkUserToVisitor($visitorId, $clientId); $client = Auth::guard('client')->user(); if ($client && $client->currency_id) { $clientCurrency = \App\Models\Currency::where('status', true) ->where('id', $client->currency_id) ->first(); if ($clientCurrency) { $this->visitorService->updateVisitorInfo($visitorId, [ 'currency' => $clientCurrency->code, 'currencySetFrom' => 'user_login', 'currencySyncedAt' => now()->toISOString(), ]); } } } Cookie::queue($this->visitorService->setVisitorCookie($visitorId)); return $next($request); } } 