<?php

namespace App\Http\Middleware;

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

class MaintenanceMode
{
    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        // maintanence mode
        $maintenance = Cache::remember('setting_maintenance', now()->addMonth(), function () {
            return Setting::where('key', 'maintenance')->first();
        });
        $maintenance = $maintenance != null ? $maintenance->value : 'off';

        // excluded routes
        $excludedRoutes = [
            // auth routes
            'login',
            'login.process',
            'login.verify',
            'login.do',
            'login.account.information',
            'login.account.information.update',
            'logout',
            'verification.verify',
            'verification.send',
            // sitemap routes
            'sitemap.index',
            'sitemap.urls',
        ];

        // allow if maintenance is of
        if ($maintenance !== 'on') {
            return $next($request);
        }

        // allow for login route
        if ($request->route() && in_array($request->route()->getName(), $excludedRoutes)) {
            return $next($request);
        }

        // allow for owner and admin
        if (auth()->check() && in_array(auth()->user()->type, ['owner', 'admin'])) {
            return $next($request);
        }

        // show maintenance mode view
        return response(view('maintenance'), 503);
    }
}
