<?php

namespace App\Http\Middleware;

use App\Exceptions\ControllerException;
use Closure;
use Illuminate\Http\Response;
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);
        }

        $user = getAdmin();

        $ajax = $request->ajax();

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

        return $next($request);
    }
}
