<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Crypt;

class DataEncrypt
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $response = $next($request);
        if ('production' == config('app.env') && $response instanceof JsonResponse) {
            $data = $response->getData();
            if (isset($data->data)) {
                $original = $data->data;
                $entrypt = Crypt::encrypt(json_encode($original), false);
                $data->data = $entrypt;
                $data->entrypt = true;
                $response->setData($data);
            }
        }
        return $response;
    }
}
