<?php

namespace App\Exceptions;

use Exception;
use Throwable;
use Illuminate\Support\Facades\Log;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

class Handler extends ExceptionHandler
{
    /**
     * The list of the inputs that are never flashed to the session on validation exceptions.
     *
     * @var array<int, string>
     */
    protected $dontFlash = [
        'current_password',
        'password',
        'password_confirmation'
    ];

    public function report(Throwable $exception)
    {

        $this->logExceptions($exception);

        if ($this->shouldReport($exception)) {
            $this->sendExceptionNotification($exception);
        }

        return parent::report($exception);
    }

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

    private function sendExceptionNotification($exception)
    {

        if (!checkDemo()) {
            return;
        }

        $url = config('srm_config.dashboard.demo.notification_url') . "/exception";

        $error = [
            "time"    => now()->toDateTimeString(),
            'message' => $exception->getMessage(),
            'code'    => $exception->getCode(),
            'file'    => $exception->getFile(),
            'line'    => $exception->getLine(),
            'trace'   => $exception->getTraceAsString()
        ];

        try {
            sendApiNotification($url, $error);

        } catch (Exception $e) {

        }

    }

    private function logExceptions($exception){

        if(! $exception instanceof NotFoundHttpException){
            Log::error('Exception occurred', ['exception' => $exception]);
        }

    }

}