<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use App\Models\AdminSession;
use App\Models\User;
use Illuminate\Support\Facades\Auth;

class TrackAdminActivity
{
    /**
     * Handle an incoming request.
     */
    public function handle(Request $request, Closure $next)
    {
        if (Auth::check() && Auth::user()->hasAnyRole(['admin', 'super_admin'])) {
            // Update user's last activity time
            Auth::user()->update(['last_active_at' => now()]);

            // Update current admin session's last activity
            $sessionId = session('admin_session_id');

            if ($sessionId) {
                $session = AdminSession::find($sessionId);
                if ($session) {
                    $session->update(['last_activity_at' => now()]);
                }
            }
        }

        return $next($request);
    }
}

