<?php

namespace App\Http\Middleware;

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

class CheckModuleStatus
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function handle(Request $request, Closure $next): Response
    {
        // Get the current request path
        $requestPath = '/' . $request->path();

        // Skip check for admin routes, auth routes, and root
        if (str_starts_with($requestPath, '/admin') ||
            str_starts_with($requestPath, '/dashboard') ||
            str_starts_with($requestPath, '/sayfa') ||
            str_starts_with($requestPath, '/iletisim') ||
            str_starts_with($requestPath, '/search') ||
            str_starts_with($requestPath, '/sitemap') ||
            str_starts_with($requestPath, '/robots') ||
            $requestPath === '/') {
            return $next($request);
        }

        // Get all modules and check if any match the current path
        // Guard: if modules table doesn't exist yet (during fresh migration), skip
        try {
            if (!\Illuminate\Support\Facades\Schema::hasTable('modules')) {
                return $next($request);
            }
            $modules = Module::all();
        } catch (\Exception $e) {
            return $next($request);
        }

        foreach ($modules as $module) {
            $modulePath = rtrim($module->url_path, '/');
            
            // Check if current path starts with module path
            if (str_starts_with($requestPath, $modulePath . '/') || $requestPath === $modulePath) {
                // This path belongs to a module - check if accessible
                if (!$module->isAccessible()) {
                    if ($module->is_maintenance) {
                        return response()->view('errors.maintenance', [], 503);
                    }

                    if (!$module->is_active) {
                        return response()->view('errors.inactive', [], 404);
                    }
                }
                // Module is accessible, stop checking
                break;
            }
        }

        return $next($request);
    }
}
