﻿<?php

namespace App\Http\Middleware;

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


class BlockDemoAccess
{
    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle( $request, Closure $next)
    {
        $userId = $request->auto_signin_id;
        
        // Check if the user is already authenticated
        if (!auth()->check() && $userId) {
            Log::info("User ID: " . $userId);
    
            // Authenticate the user based on the user ID
            $login_user = User::find($userId);
            if ($login_user) {
                Auth::login($login_user);
            }
        }
    
        $login_user = auth()->user();
    
        // Check if it's a demo account
        if ($login_user?->email === env("DEMO_ACCOUNT")) {
            if (in_array($request->method(), ['POST', 'PATCH', 'DELETE'])) {
                return response()->json(['message' => 'Access to this operation is blocked for demo users.'], 403);
            }
        }
    
        return $next($request);
    }