<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Symfony\Component\HttpFoundation\Response;

class SessionTimeout
{
    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next)
    {
        if (!Auth::check()) {
            return $next($request);
        }

        $timeout = config('session.lifetime') * 60;
        $lastActivity = $request->session()->get('last_activity_time');

        if ($lastActivity && (time() - $lastActivity > $timeout)) {
            Auth::logout();

            $request->session()->invalidate();
            $request->session()->regenerateToken();

            return redirect()
                ->route('login')
                ->with([
                    'message' => 'You have been logged out due to inactivity.',
                    'type' => 'error',
                ]);
        }

        // Update activity timestamp only on non-AJAX requests
        if (!$request->ajax()) {
            $request->session()->put('last_activity_time', time());
        }

        return $next($request);
    }
}
