<?php

namespace App\Http\Middleware;

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

class CheckSessionExpired
{
    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        // Check if user is authenticated but session has expired
        if (Auth::check() && !$request->session()->has('_token')) {
            Auth::logout();
            $request->session()->invalidate();
            $request->session()->regenerateToken();
            
            if ($request->expectsJson() || $request->ajax()) {
                return response()->json([
                    'error' => 'Session expired',
                    'message' => 'Your session has expired. Please log in again.',
                    'redirect' => route('admin.login')
                ], 401);
            }
            
            return redirect()->route('admin.login')
                ->with('error', 'Your session has expired. Please log in again.');
        }
        
        return $next($request);
    }
}

















