<?php

namespace Middlewares;

use Slim\Container;

class ResponseMiddleware
{
    /**
     * @var Container
     */
    private $container;

    public function __construct(Container $container)
    {
        $this->container = $container;
    }
    /**
     *
     * @param  \Psr\Http\Message\ServerRequestInterface $request PSR7 request
     * @param  \Psr\Http\Message\ResponseInterface $response PSR7 response
     * @param  callable $next Next middleware
     *
     * @return \Psr\Http\Message\ResponseInterface
     */

    public function __invoke($request, $response, $next)
    {
        try {
            $response = $next($request, $response);
        } catch (\Exception $e) {
            $data = [
                'success' => false,
                'message' => $e->getMessage(),
            ];
            $response = $response->withStatus(422);
            $response = $response->withJson($data);
            $this->container->logger->error($e->getMessage());
        }

        return $response;
    }
}
