<?php

namespace App\Http\Middleware;

use Closure;
use App\User;
use Illuminate\Support\Facades\Auth;

class MarketerTokenMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        // dd($request->route('local'), $request->header('secret'), $request->bearerToken());
        // dd( $request->headers->all(), $request->header('MARKETERTOKEN'), $request->bearerToken());

        if(!$request->hasHeader('MARKETERTOKEN') ){
            return response()->json(['message' => 'Unauthenticated'], 401);
        }
        $ability= $request->user()->tokenCan('marketer_token:'.$request->header('MARKETERTOKEN'));
        // dd($ability);
        if( !$ability ){
            return response()->json(['message' => 'Unauthenticated'], 401);
        }
        $marketer= $request->user()->marketers()->where('token', $request->header('MARKETERTOKEN'))->first();
        if(!$marketer){
            return response()->json(['message' => 'Unauthenticated'], 401);
        }
        $request->merge(['marketer'=> $marketer]);
        return $next($request);
    }
}
