<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use App\Services\PackageModuleService;

class VerifyModuleAccess
{
    protected $packageService;

    public function __construct(PackageModuleService $packageService)
    {
        $this->packageService = $packageService;
    }

    public function handle(Request $request, Closure $next, $module)
    {
        $hotel = request()->user()->hotel ?? null;

        if (!$hotel) {
            abort(403, 'No active hotel context found for tenant isolation validation.');
        }

        if (!$this->packageService->hasAccessToModule($hotel, $module)) {
            if ($request->expectsJson() || $request->ajax()) {
                return response()->json([
                    'status' => 'error',
                    'message' => 'Your current package does not include access to the ' . ucfirst(str_replace('_', ' ', $module)) . ' module. Please upgrade to use this feature.'
                ], 403);
            }
            
            return redirect()->back()->with('error', 'Your current package does not grant access to the ' . ucfirst($module) . ' module.');
        }

        return $next($request);
    }
}
