<?php

namespace App\Http\Middleware;

use App\Helpers\HashIdObj;
use Closure;
use Hashids\Hashids;
use Illuminate\Http\Request;

class HashIdMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        $allowedKeys    =   ['country_id', 'key', 'category_id', 'shop_id', 'product_id', 'id', 'package_id', 'payment_id', 'category_id'];
        $arraysValue    =   ['deleted_images_ids'];
        $hashObj    =   new Hashids(env('HASH_ID_KEY'), 10);

        foreach($request->only(array_merge($allowedKeys,$arraysValue)) as $key => $value) {
            if(is_array($value)){
                $decodedVal = collect($value)
                    ->map(function ($elem)use($hashObj){return $hashObj->decode($elem)[0];})
                    ->toArray();
            } else {
                $decodedVal =   $hashObj->decode($value);
            }
            if(count($decodedVal) > 0)
                $request->offsetSet($key, in_array($key, $arraysValue) ? $decodedVal:$decodedVal[0]);
        }
        return $next($request);
    }
}
