<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Session\Store;

class SessionTimeout{
    protected $session;
    protected $timeout = 600;  

    public function __construct(Store $session){
        $this->session = $session;
    }

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse)  $next
     * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
     */
    public function handle(Request $request, Closure $next)
    {
        if( !$this->session->has('lastActivityTime') ) {
            $this->session->put('lastActivityTime', time());
         }
         elseif ( time() - $this->session->get('lastActivityTime') > $this->timeout ) {
            $this->session->forget('lastActivityTime');
            #\App\Http\Controllers\LoginController::merchant_logout($request);
   
            $cookie =  \Cookie::forget('fortunae');
            return redirect("/")->withErrors(['You had no activity over the past '. $this->timeout/60 .' minutes.'])->withCookie($cookie);
         }
   
        $this->session->put('lastActivityTime',time());
        return $next($request);
    }
}
