<?php

namespace App\Http\Middleware;

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

class CheckMembershipToken
{
    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        // Check for membership token in session
        $membershipToken = Session::get('membership_token');
        $membershipUser = Session::get('membership_user');
        
        // Check for Authorization header (for API requests)
        $authHeader = $request->header('Authorization');
        if ($authHeader && str_starts_with($authHeader, 'Bearer ')) {
            $tokenFromHeader = substr($authHeader, 7);
            if ($tokenFromHeader) {
                // Valid token found in header, allow request
                return $next($request);
            }
        }
        
        // Check for token in session
        if ($membershipToken && $membershipUser) {
            // Valid membership session found, allow request
            return $next($request);
        }
        
        // No valid token found
        if ($request->expectsJson() || $request->is('api/*')) {
            // For API requests, return JSON response
            return response()->json([
                'success' => false,
                'message' => 'Membership authentication required',
                'error' => 'MEMBERSHIP_TOKEN_MISSING'
            ], 401);
        }
        
        // For web requests, redirect to login with message
        if ($request->ajax()) {
            return response()->json([
                'success' => false,
                'message' => 'Please log in to your membership account to continue',
                'redirect' => '/'
            ], 401);
        }
        
        // Regular web request - redirect to home with login modal trigger
        return redirect()->route('home')->with('show_login_modal', true)->with('error', 'Please log in to your membership account to access this page.');
    }
}
