<?php

namespace App\Log;

use App\IpLocation;
use App\Notification\TelegramBot;
use Illuminate\Support\Facades\Crypt;
use Monolog\Handler\AbstractProcessingHandler;
use Monolog\Logger;

class TelegramHandler extends AbstractProcessingHandler
{
    /**
     * @var DingDingRobot
     */
    protected $telegramBot;

    public function __construct(TelegramBot $telegramBot, $level = Logger::DEBUG, $bubble = true)
    {
        parent::__construct($level, $bubble);
        $this->telegramBot = $telegramBot;
    }

    /**
     * Writes the record down to the log of the implementing handler
     *
     * @param array $record
     * @return void
     */
    protected function write(array $record)
    {
        $ip = IpLocation::getIP();
        $agent=@$_SERVER['HTTP_USER_AGENT']??"";
        $locale=@$_SERVER['HTTP_ACCEPT_LANGUAGE']??"";
        $ref = @$_SERVER['HTTP_REFERER'];
        $url = @$_SERVER['REQUEST_URI'];
        $host = @$_SERVER['HTTP_HOST'];
        $request=$_REQUEST;
        if(isset($_REQUEST['sign'])){
            try {
                $request['user'] = Crypt::decryptString($_REQUEST['sign']);
                unset($request['sign']);
            }catch (\Exception $e){

            }
        }
        $envs=json_encode(compact('ip','agent','locale','ref','url','host','request'),JSON_PRETTY_PRINT);
        $this->telegramBot->sendMsg(
            env('APP_ENV')."## [ERROR级别日志]\n$envs\n{$record['formatted']}"
        );
//        unset($record['formatted']);
//        $this->telegramBot->sendMsg(
//            json_encode($record, JSON_UNESCAPED_UNICODE)
//        );
    }
}
