<?php

namespace App\Exceptions;

use App\Helpers\Helper;
use Carbon\Carbon;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Throwable;

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

    /**
     * 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()
    {
        $appName = config("app.name");
        
        $dt = Carbon::now();
        $isAjax = request()->ajax() ? "TRUE" : "FALSE";
        $this->reportable(function (Throwable $e) use ($appName, $dt, $isAjax) {
            $user = auth()->user()->name ?? '';
            if (config("app.env") == 'production') {
                $errorMessage = "<b>###### {$appName} ###### </b>
                <pre>URL: " . request()->fullUrl() . "</pre>
                <pre>IP: " . request()->ip() . "</pre>
                <pre>Request Method: " . request()->method() . "</pre>
                <pre>HTTP Code: 500</pre>
                <pre>Ajax Request: {$isAjax}</pre>
                <pre>User Agent: " . request()->header("User-Agent") . "</pre>
                <pre>User: {$user}</pre>
                <pre>Error: " . $e->getMessage() . "</pre>
                <pre>File: {$e->getFile()}</pre>
                <pre>Date: {$dt}</pre>
                <pre>Line: {$e->getLine()}</pre>";
                Helper::sendTelegramMessage(config('somnab.telegram.debug_id'), $errorMessage);
            }
        });
        $this->renderable(function (NotFoundHttpException $e, $request) use ($appName, $dt, $isAjax) {
            $user = auth()->user()->name ?? '';
            if (config("app.env") == 'production') {
                $errorMessage = "<b>###### {$appName} ###### </b>
                <pre>URL: " . $request->fullUrl() . "</pre>
                <pre>IP: " . $request->ip() . "</pre>
                <pre>Request Method: " . $request->method() . "</pre>
                <pre>HTTP Code: " . $e->getStatusCode() . "</pre>
                <pre>Ajax Request: {$isAjax}</pre>
                <pre>User Agent: " . $request->header("User-Agent") . "</pre>
                <pre>User: {$user}</pre>
                <pre>Error: " . $e->getMessage() . "</pre>
                <pre>File: {$e->getFile()}</pre>
                <pre>Date: {$dt}</pre>
                <pre>Line: {$e->getLine()}</pre>";
                Helper::sendTelegramMessage(config('somnab.telegram.debug_id'), $errorMessage);
            }
        });
    }
}
