<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Route;
use App\Models\Setting;

class MaintenanceMode
{
    public function handle(Request $request, Closure $next)
    {
        // Check DB setting
        $maintenanceMode = Setting::where('name', 'maintenance_mode')->first();
        if ((!Auth::check() || Auth::user()->user_role !== 'admin') && $maintenanceMode && ($maintenanceMode->val == 1 || $maintenanceMode->val === '1')) {
            // Exclude login, register, password reset, etc.
            $allowedRoutes = [
                'login', 'logout', 'register', 'password.request', 'password.email', 'password.reset', 'password.update'
            ];

            // Allow specific URIs if route names aren't set
            $allowedPaths = [
                'login', 'logout', 'register', 'password/reset'
            ];

            $currentRouteName = Route::currentRouteName();
            $currentPath = $request->path();

            if (in_array($currentRouteName, $allowedRoutes) || $this->pathMatches($currentPath, $allowedPaths)) {
                return $next($request);
            }

            // Allow admins
            if (Auth::check() && Auth::user()->user_role === 'admin') {
                return $next($request);
            }

            // Show maintenance view
            return response()->view('front_end.pages.maintenance');
        }

        return $next($request);
    }

    private function pathMatches($currentPath, $allowedPaths)
    {
        foreach ($allowedPaths as $path) {
            if (str_starts_with($currentPath, $path)) {
                return true;
            }
        }
        return false;
    }
}