<?php

namespace App\Exceptions;

use Illuminate\Validation\UnauthorizedException;
use Symfony\Component\HttpFoundation\Response;
use Throwable;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Illuminate\Validation\ValidationException;
use Illuminate\Auth\Access\AuthorizationException;

class Handler extends ExceptionHandler
{
    /**
     * A list of the exception types that are not reported.
     *
     * @var array
     */
    protected $dontReport = [
        //
    ];

    /**
     * A list of the inputs that are never flashed for validation exceptions.
     *
     * @var array
     */
    protected $dontFlash = [
        'password',
        'password_confirmation',
    ];

    /**
     * Report or log an exception.
     *
     * @param \Exception $exception
     * @return void
     */
    public function report(Throwable $exception)
    {
        parent::report($exception);
    }

    /**
     * Render an exception into an HTTP response.
     *
     * @param \Illuminate\Http\Request $request
     * @param \Exception $exception
     * @return \Symfony\Component\HttpFoundation\Response
     * @throws Exception
     */
    public function render($request, Throwable $exception)
    {
        if ($exception instanceof AuthorizationException) {
            if ($request->expectsJson()) {
                return fdb_fail_api_response(
                    __('forbidden'),
                    __('forbidden'),
                    [],
                    Response::HTTP_FORBIDDEN
                );
            }
            return redirect()->route('panel.index');
        }
        if ($exception instanceof UnauthorizedException) {
            if ($request->expectsJson()) {
                return fdb_fail_api_response(
                    __('unauthenticated'),
                    __('unauthenticated'),
                    [],
                    Response::HTTP_UNAUTHORIZED
                );
            }
            return abort(401);
        }
        return parent::render($request, $exception);
    }

    public function invalidJson($request, ValidationException $exception)
    {
        return response()->json([
            /*'message' => $exception->getMessage(),*/
            //get the first error message in errors array to show it to user
            'message' => $exception->errors()[array_key_first($exception->errors())][0],
            'errors' => $exception->errors(),
        ], $exception->status);
    }
}
