<?php

namespace App\Http\Middleware;

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

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

        // Only track GET requests that are successful and not Livewire internal requests
        if ($request->method() === 'GET' && $response->getStatusCode() === 200 && ! $request->header('X-Livewire')) {
            $ip = $request->ip();
            $route = $request->route() ? $request->route()->getName() : $request->path();

            // Skip if route is not defined or route is Livewire
            if (! $route || str_contains($route, 'livewire')) {
                return $response;
            }

            $today = Carbon::today();

            // Check if IP has already visited this route today
            $alreadyVisited = Visitor::where('ip', $ip)
                ->where('route', $route)
                ->whereDate('date', $today)
                ->exists();

            if (! $alreadyVisited) {
                Visitor::create([
                    'user_id' => auth()->id(),
                    'method' => $request->method(),
                    'route' => $route,
                    'status' => $response->getStatusCode(),
                    'ip' => $ip,
                    'date' => Carbon::now(),
                    'counter' => 1, // Set 1 because this is the first unique visit today
                ]);
            }
        }

        return $response;
    }
}
