<?php

namespace Mtc\Plugins\MembersMessaging\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Mtc\Core\Permissions;

class ThreadPermissionMiddleware
{
    public function handle(Request $request, Closure $next, $permissionConstant)
    {
        $permission = constant(Permissions::class . '::' . $permissionConstant);

        if (!Permissions::can($permission)) {
            if($request->expectsJson()) {
                return response()->json(['success' => false, 'message' => 'You do not have permission to do actions on this thread.'], 400);
            }

            return redirect()->back()->with('error', 'You do not have permission to access this thread.');
        }

        return $next($request);
    }
}
