<?php

include('../includes/overall.inc.php');

use Mnv\Core\Bot\Telegram;
use Mnv\Core\Bot\TelegramNotifications;
use Mnv\Core\Test\Log;


$sapi_type = php_sapi_name();
if (substr($sapi_type, 0, 3) == 'cgi') {
    header("Status: 200 Ok'");
} else {
    header("HTTP/1.0 200 OK");
}

$request = file_get_contents('php://input');
$input = json_decode($request, true);

if (isset($input['message'])) {

    $key = TelegramNotifications::getValue('telegram_key');
    $webhook = TelegramNotifications::getValue('webhook');

    if (!empty($key) && ($webhook != 'no')) {

        $telegram = new Telegram($key, TelegramNotifications::getValue('timeout'));
        $telegram->setLog( new Log('telegram.log'), TelegramNotifications::getValue('logs'));
        $last_name  = $input['message']['from']['last_name'] ?? '';
        $first_name = $input['message']['from']['first_name'] ?? '';
        $id         = $input['message']['from']['id'] ?? '';
        $lang_code  = $input['message']['from']['language_code'] ?? '';
        $id_chat    = $input['message']['chat']['id'] ?? '';
        $name_chat  = $input['message']['chat']['name'] ?? '';

        // file_put_contents('test2.json', json_encode($input['message']));
        if ($id_chat) {
            $message = 'Здравствуйте, ' . $last_name . ' ' . $first_name . '!' . chr(10) . 'ID группы ' . $name_chat . ': ' . $id_chat . ' (копировать со знаком минус в начале!)';
        } else {
            $message = 'Здравствуйте, ' . $last_name . ' ' . $first_name . '!' . chr(10) . 'Ваш ID: ' . $id . chr(10) . 'Язык: ' . $lang_code;
        }

        $telegram->setTo($id);
        $telegram->sendMessage($message, TelegramNotifications::getValue('trim_messages'));
    }
} else {
    echo 'error';
}
