<?php

namespace App\Http\Middleware;

use Closure;

class Cors
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if($request->getMethod() === 'OPTIONS'){
             return $this->addPreflightHeaders(response('Preflight OK', 200));
        }
         $response = $next($request);

        return $this->addCorsHeaders($response);;
    }
    
    public function addPreflightHeaders($response)
    {
        return $response
            ->header('Access-Control-Allow-Methods', 'POST, GET, PATCH,DELETE,HEAD,OPTIONS')
            ->header('Access-Control-Allow-Headers', 'Content-Type, X-Auth-Token, Origin, Authorization')
            ->header('Access-Control-Allow-Origin', '*')
            ->header('Access-Control-Max-Age', 60 * 60 * 24);
    }
    
    public function addCorsHeaders($response)
    {
        return $response
            ->header('Access-Control-Allow-Origin','*');
    }
}
