<?php

namespace App\Http\Middleware;

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

class MaintenanceModeMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        // Check if maintenance mode is enabled
        $maintenanceMode = Setting::get('maintenance_mode', false);
        
        if ($maintenanceMode) {
            // Allow access to admin routes and auth routes during maintenance
            $allowedRoutes = [
                'admin.*',
                'login',
                'register',
                'logout',
                'password.*',
                'verification.*',
                'livewire.*',
            ];
            
            $currentRoute = $request->route() ? $request->route()->getName() : null;
            
            // Check if current route is allowed during maintenance
            $isAllowedRoute = false;
            if ($currentRoute) {
                foreach ($allowedRoutes as $allowedRoute) {
                    if (str_contains($allowedRoute, '*')) {
                        $pattern = str_replace('*', '.*', $allowedRoute);
                        if (preg_match('/^' . $pattern . '$/', $currentRoute)) {
                            $isAllowedRoute = true;
                            break;
                        }
                    } elseif ($currentRoute === $allowedRoute) {
                        $isAllowedRoute = true;
                        break;
                    }
                }
            }
            
            // If not an allowed route and maintenance mode is on, show maintenance page
            if (!$isAllowedRoute) {
                return response()->view('maintenance', [
                    'siteName' => Setting::get('site_name', 'LLN Project'),
                    'copyrightText' => Setting::get('copyright_text', '© 2024 LLN Project. All rights reserved.'),
                ], 503);
            }
        }

        return $next($request);
    }
}