<?php

namespace App\Http\Middleware;

use App\Events\LoginDetail;
use Closure;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cache;

class LoginActivity
{
    /**
     * Handle an incoming request.
     *
     * @param Request $request
     * @param Closure(Request): (Response|RedirectResponse) $next
     * @return Response|RedirectResponse
     */
    public function handle(Request $request, Closure $next)
    {
        if (Auth::check()) {
            $expireAt = now()->addMinutes(2); /* keep online for 2 min */
            if (Cache::has('isOnline')) {
                $onlineUsers = json_decode(Cache::get('isOnline', []), true);
            }
            $onlineUsers[Auth::id()] = now();
            Cache::put('isOnline', json_encode($onlineUsers), $expireAt);
            // update last seen
            event(new LoginDetail(Auth::user()));

        }
        return $next($request);
    }
}
