<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
use App\Models\WebsiteVisitLog;

class TrackVisit
{
    /**
     * Handle an incoming request.
     *
     * @param  Closure(Request): (Response)  $next
     */
    public function handle(Request $request, Closure $next)
    {
        

        // optional: prevent spam refresh
        $exists = WebsiteVisitLog::where('ip_address', $request->ip())
            ->where('created_at', '>', now()->subMinutes(10))
            ->exists();

        //if (!$exists) {
        //if (!session()->has('visited')) {

            WebsiteVisitLog::create([
                'ip_address' => $request->ip(),
                'user_agent' => $request->userAgent(),
                'user_id' => auth()->id(),
                'url' => $request->fullUrl(),
                'referrer' => $request->headers->get('referer'),
            ]);

            session(['visited' => true]);
        //}

        return $next($request);
    }
}
