namespace App\Filters;

use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use CodeIgniter\Filters\FilterInterface;

class IdleTimeout implements FilterInterface
{
    public function before(RequestInterface $request, $arguments = null)
    {
        if (session()->get('isLoggedIn')) {
            $lastActivity = session()->get('last_activity');
            $timeout = 120; // 30 minutes
            $now = time();

            if ($lastActivity && ($now - $lastActivity > $timeout)) {
                session()->destroy();
                return redirect()->to(base_url('login'))->with('status', 'You were logged out due to inactivity.');
            }

            session()->set('last_activity', $now);
        }
    }

    public function after(RequestInterface $request, ResponseInterface $response, $arguments = null)
    {
        // Not needed
    }
}
