<?php

namespace App\Http\Middleware;

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

class Authenticate
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @param  string|null  $guard
     * @return mixed
     */
    public function handle($request, Closure $next, $guard = null)
    {
        Log::info('=== AUTH MIDDLEWARE CHECK ===', [
            'url' => $request->url(),
            'method' => $request->method(),
            'auth_check' => Auth::guard($guard)->check(),
            'user_id' => Auth::guard($guard)->check() ? Auth::guard($guard)->user()->id : null,
            'session_id' => $request->hasSession() ? $request->session()->getId() : 'no_session',
            'guard' => $guard,
            'has_session' => $request->hasSession(),
        ]);

        if (Auth::guard($guard)->guest()) {
            Log::info('User not authenticated, redirecting to login', [
                'url' => $request->url(),
                'intended_url' => $request->url()
            ]);
            
            if ($request->ajax() || $request->wantsJson()) {
                return response('Unauthorized.', 401);
            } else {
                return redirect()->guest('login');
            }
        }

        Log::info('User authenticated, proceeding', [
            'user_id' => Auth::guard($guard)->user()->id,
            'url' => $request->url()
        ]);

        return $next($request);
    }
}
