<?php

namespace App\Http\Middleware;

use App\Exceptions\ControllerException;
use Closure;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Redirect;

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

        $except_url = [
            'web/login',
            'web/logout',
        ];

        if (in_array($url,$except_url)){
            return $next($request);
        }

        $ajax = $request->ajax();

        $user = Auth::user();

        if (isset($user->mis_uid)){
            $request->replace(array_merge($request->all(),['mis_uid'=>$user->mis_uid]));
        }

        if (empty($user->name)){
            if ($ajax){
                throw new ControllerException(Response::HTTP_UNAUTHORIZED);
            }
            return Redirect::to("web/logout");
        }

        return $next($request);
    }
}
