<?php

namespace App\Services\TG;
use App\Services\TomTool\Http as TomHttp;

class Http {
    
    public $sApiToken;
    public $sApiChatId;
    
    function __construct()
    {
        $this->sApiToken = env('telegram_token');
        $this->sApiChatId = env('telegram_chatid');
    }
    
    public function send($sMsg = "msg空", $aUpdate = [])
    {
        
        $bSendTg = true;
        
        $sShell = $aUpdate["shell"] ?? false;
        $bIsDove = $aUpdate["is_dove"] ?? false;
        
        if ($sShell == "cmd") {
            $bSendTg = false;
        }
        
        if ($bIsDove == true) {
            $bSendTg = false;
        }
        
        if (env("is_loc") == true) {
            $bSendTg = false;
        }
        
        if (is_array($sMsg)) {
            foreach ($sMsg as $sMsgRow) {
                if ($bSendTg) {
                    $this->sendTg($sMsgRow);
                } else {
                    echo $sMsgRow;
                }
            }
        } else {
            if ($bSendTg) {
                $this->sendTg($sMsg);
            } else {
                echo $sMsg;
            }
        }
        
        if ($bSendTg) {
            TomHttp::response(200);
        } else {
            exit;
        }
        
    }
    
    private function sendTg($sMsg)
    {
        $url = "https://api.telegram.org/bot$this->sApiToken/sendMessage?chat_id=$this->sApiChatId&text=" . urlencode($sMsg);
        file_get_contents($url);
    }
    
    public function sendToTG($sMsg, $aUpdate = [])
    {
        
        if (isset($aUpdate["shell"]) && $aUpdate["shell"] == "cmd") {

            echo $sMsg;
            
        } else if (isset($aUpdate["is_dove"]) && $aUpdate["is_dove"] == true) {
            
            echo $sMsg;
            
        } else {
            
            if (env("is_loc") == true) {
                echo $sMsg;
            } else {
                $url = "https://api.telegram.org/bot$this->sApiToken/sendMessage?chat_id=$this->sApiChatId&text=" . urlencode($sMsg);
                file_get_contents($url);
            }
            
//            if (env("is_loc") == true) {
//                echo "<pre>";
//                echo $sMsg;
//            } else {
//                $url = "https://api.telegram.org/bot$this->sApiToken/sendMessage?chat_id=$this->sApiChatId&text=" . urlencode($sMsg);
//                file_get_contents($url);
//            }

        }
        
    }
    
}
