<?php

namespace App\Http\Middleware;

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

class HandleSessionExpired
{
    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        $response = $next($request);
        
        // If response is 419 (CSRF token mismatch) or 401 (Unauthorized), handle session expiration
        if ($response->getStatusCode() === 419 || $response->getStatusCode() === 401) {
            if (Auth::check()) {
                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', ['expired' => 1])
                ->with('error', 'Your session has expired. Please log in again.');
        }
        
        return $response;
    }
}

















