<?php

namespace App\Http\Middleware;

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

class EnsureAdminSessionIsActive
{
    public function handle(Request $request, Closure $next): Response
    {
        $lastActivity = (int) $request->session()->get('admin_last_activity', time());
        $timeout = max(1, (int) config('session.admin_timeout', 30)) * 60;

        if (time() - $lastActivity > $timeout) {
            Auth::guard('admin')->logout();
            $request->session()->invalidate();
            $request->session()->regenerateToken();

            return redirect()->route('admin.login')->withErrors(['email' => __('Your session expired. Please sign in again.')]);
        }

        $request->session()->put('admin_last_activity', time());

        return $next($request);
    }
}
