<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;

class CleanData
{

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        // return sendError('Error Getting all parameters in mid:', $request->all());  
        /**
         *           Firstly decrypt request body 
         */
            $request->replace(encryptable($request->all(), false)); 
        /**
         *           Firstly decrypt request body - END
         */

        /**
         *           Secondly decrypt request parameters 
         */
        $encryptable_keys = array('_id', 'id_', 'Id', '_Id', 'Id_', 'iD', '_iD', 'iD_');
        $routeParameters = encryptable($request->route()->Parameters(), false, $encryptable_keys);
        $routeArray = $request->route();
        $routeArray->parameters = $routeParameters;

        $request->setRouteResolver(function() use ($routeArray)
        {
            return $routeArray;
        });
        // return sendError('Error Getting all parameters in mid:', $request->route()->Parameters());  
        /**
         *           Secondly decrypt request parameters - END
         */

        return $next($request);
    }
}