<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

/**
 * Middleware: CheckTabPermission
 *
 * Protects individual tab/section endpoints within a menu page.
 * Checks both scoped (e.g. "view global settings:login-security") and
 * legacy menu-level ("manage global settings") permissions.
 *
 * Route usage:
 *   ->middleware('tab-permission:global settings,login-security')
 *   ->middleware('tab-permission:mobile settings,branding,manage')
 *
 * Parameters:
 *   $menu   — the menu slug, e.g. "global settings"
 *   $tab    — the tab slug, e.g. "login-security"
 *   $action — "view" (default) or "manage"
 */
class CheckTabPermission
{
    public function handle(Request $request, Closure $next, string $menu, string $tab, string $action = 'view'): Response
    {
        if (! auth()->check()) {
            return $request->expectsJson()
                ? response()->json(['message' => 'Unauthenticated.'], 401)
                : redirect()->route('login');
        }

        $allowed = $action === 'manage'
            ? can_manage_tab($menu, $tab)
            : can_view_tab($menu, $tab);

        if (! $allowed) {
            return $request->expectsJson()
                ? response()->json(['message' => 'This action is unauthorized.'], 403)
                : abort(403, "Access denied to tab: {$tab}");
        }

        return $next($request);
    }
}
