<?php

namespace App\Exceptions;

use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Symfony\Component\ErrorHandler\Exception\FlattenException;
use Throwable;
use Laravel\Passport\Exceptions\MissingScopeException;
use Illuminate\Http\Exceptions\ThrottleRequestsException;
use Laravel\Passport\Exceptions\AuthenticationException;
use App\Http\Traits\UnauthenticatedApiIpTrait;
use Sentry\Laravel\Integration;

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

    use UnauthenticatedApiIpTrait;

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

    /**
     * Register the exception handling callbacks for the application.
     *
     * @return void
     */
    public function register()
    {
        $this->reportable(function (Throwable $e) {
            Integration::captureUnhandledException($e);

            if ($this->shouldReport($e)) {
                // $this->sendEmail($e); // sends an email
            }
        });
    }

    /**
     * Sends an email to the developer about the exception.
     *
     * @param  \Exception  $exception
     * @return void
     */
    public function sendEmail(Throwable $exception)
    {
        try {
            $e = FlattenException::create($exception);
            $handler = new SymfonyExceptionHandler();

            $html = $handler->getHtml($e);
            $configEmails = config('teqtivity-notification-mails.emails');
            $emails = explode(',', $configEmails);
            foreach ($emails as $email) {
                if (Notification::route('mail', $email)->notify(new Errors($html))) {
                }
            }
        } catch (\Exception $ex) {
            abort(404);
        }
    }

    public function render($request, Throwable $exception)
    {
        if ($exception instanceof AuthenticationException) {
            $this->addUnauthAttempt(getIp());

            return response()->json([
                'success'       => false,
                'message'       => "You are unautherized to access this resource!",
                'status_code'   => 401,
                'data'          => []
            ]);
        }

        if ($exception instanceof MissingScopeException) {
            return response()->json([
                'success'           => false,
                'message'           => "You have no permission to access this resource!",
                'status_code'       => 403,
                'data'              => []
            ]);
        }

        if ($exception instanceof ThrottleRequestsException) {
            return response()->json([
                'success'       => false,
                'message'       => "Too many requests. Please try again later.",
                'status_code'   => 429,
                'data'          => []
            ]);
        }

        return parent::render($request, $exception);
    }
}
