<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\DB;

class SessionTimeout
{
    public function handle(Request $request, Closure $next)
    {
        if (Auth::check()) {
            $lastActivity = session('last_activity_time');
            $timeout = 10 * 60; // 5 minutes in seconds

            // Check if last activity exceeded timeout
            if ($lastActivity && (time() - $lastActivity > $timeout)) {
                // Save current URL to redirect after login
                Session::put('url.intended', url()->current());

                Auth::logout();
                $request->session()->invalidate();
                $request->session()->regenerateToken();

                return redirect()
                    ->route('login')
                    ->with('message', 'Your session expired. Please log in again.');
            }

            // 2. Check if session was invalidated by another login
            $sessionExists = DB::table('sessions')
                ->where('id', session()->getId())
                ->exists();

            if (!$sessionExists) {
                Auth::logout();
                $request->session()->invalidate();
                $request->session()->regenerateToken();

                return redirect()->route('login')
                    ->with('message', 'You have been logged out because your account was logged in from another device.');
            }

            // Update last activity time
            session(['last_activity_time' => time()]);
        }

        return $next($request);
    }
}
