<?php

namespace App\Http\Middleware;

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

class TrackRouteVisitsMiddleware
{
    /**
    * Handle an incoming request.
    *
    * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
    */
    public function handle($request, Closure $next)
    {
        $routeName = $request->route()->getName();

        // Check if the route has been visited by the same session
        if (!$request->session()->has('visited_' . $routeName)) {
            $request->session()->put('visited_' . $routeName, true);

            // Increment the visit count for the route in the database
            \App\Models\Visit::firstOrCreate(['route_name' => $routeName])->increment('visits_count');
        }

        return $next($request);
    }
}
