<?php

namespace App\Http\Middleware;

use Closure;

class EnableCrossRequestMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param \Illuminate\Http\Request $request
     * @param \Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $response = $next($request);


//        if (in_array($origin, $allow_origin)) {
        //DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization
//        $response->header('Access-Control-Allow-Headers', '*');
//        $response->header('Access-Control-Expose-Headers', 'Authorization, authenticated');

        $origin = $request->server('HTTP_ORIGIN') ?? '*';
        $this->header('Access-Control-Allow-Origin', $origin);
        $this->header('Access-Control-Allow-Headers', 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Origin, Content-Type, Cookie, X-CSRF-TOKEN, Accept, Authorization, X-XSRF-TOKEN');
        $this->header('Access-Control-Expose-Headers', '*');
        $this->header('Access-Control-Allow-Methods', 'GET, POST, PATCH, PUT, OPTIONS');
        $this->header('Access-Control-Allow-Credentials', 'true');
//        }
        return $response;
    }
    protected function header($key, $value)
    {
        header(sprintf('%s: %s', $key, $value));
    }
}
