<?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)
    {
        try {
            $response = $next($request);
        } catch (\App\Exceptions\FormException $e) {
            list($code, $message) = [Response::HTTP_BAD_REQUEST, json_decode($e->getMessage(), true)];
        } catch (\App\Exceptions\DatabaseException $e) {
            list($code, $message) = [Response::HTTP_INTERNAL_SERVER_ERROR, json_decode($e->getMessage(), true)];
        } catch (\App\Exceptions\ControllerException $e) {
            list($code, $message) = [Response::HTTP_INTERNAL_SERVER_ERROR, json_decode($e->getMessage(), true)];
        }
        if (isset($code)) {

            if (count($message) == 1) {
                $message = $message[0];
            } else if (count($message) == 2) {
                list($code, $message) = $message;
            } else if (count($message) == 3) {
                list($client_info, $code, $message) = $message;
            }
//            Log::error('\\' . implode(CustomLog::getRoute()), $client_info, $code, $message, $request->all());
//            Log::flush();
            return error($message, $code);
        }

        return $response;















        $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)){
            $user = Auth::user();
            $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);
    }
}
