<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
use App\Services\AnalyticsLoggingService;

class TrackAnalytics
{
    /**
     * Handle an incoming request.
     */
    public function handle(Request $request, Closure $next): Response
    {
        // Only run for frontend page requests (not AJAX, APIs, or asset routes)
        if ($request->isMethod('GET') && !$request->expectsJson() && !$request->is('admin*')) {
            try {
                AnalyticsLoggingService::getCurrentSessionId();

                $path = $request->path();
                if ($path === '/' || $path === '') {
                    AnalyticsLoggingService::logEvent('browse_home');
                } elseif ($path === 'shop') {
                    AnalyticsLoggingService::logEvent('browse_shop');
                } elseif ($path === 'categories') {
                    AnalyticsLoggingService::logEvent('browse_categories');
                } elseif ($path === 'contact') {
                    AnalyticsLoggingService::logEvent('browse_contact');
                } elseif ($path === 'dashboard') {
                    AnalyticsLoggingService::logEvent('browse_dashboard');
                }
            } catch (\Throwable $e) {
                // Fail silently to not disrupt user browsing
                \Illuminate\Support\Facades\Log::error('Analytics middleware failed: ' . $e->getMessage());
            }
        }

        return $next($request);
    }
}
