<?php

namespace App\Http\Middleware;

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

class SubmissionsEnabled
{
    /**
     * Handle an incoming request.
     *
     * @param  Closure(Request): (Response)  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        if( Cache::get('submissions_maintenance', false ) ){
            if( $request->expectsJson() ){
                return response()->json([
                    'message' => 'The submissions are currently in maintenance mode.',
                ], 503 );
            }

            return back()->withErrors([
                'maintenance' => "The submissions are currently in maintenance mode.",
            ])->withInput();
        }

        return $next($request);
    }
}
