<?php

namespace App\Http\Middleware;

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

class CheckMenuEnabled
{
    /**
     * Handle an incoming request.
     * Check if the requested menu is enabled in settings.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     * @param  string  $menuKey  The menu key to check (e.g., 'online', 'voucher', 'shop')
     */
    public function handle(Request $request, Closure $next, string $menuKey): Response
    {
        $settingKey = "menu_{$menuKey}_enabled";
        
        $setting = DB::table('settings')
            ->where('key', $settingKey)
            ->value('value');
        
        // Default to enabled (true) if setting doesn't exist
        // Only block if explicitly set to '0'
        if ($setting === '0') {
            return redirect()->route('dashboard')
                ->with('error', 'This feature is currently disabled.');
        }
        
        return $next($request);
    }
}
