<?php
/**
 * Created by IntelliJ IDEA.
 * User: solu
 * Date: 2019/3/26
 * Time: 4:59 PM
 */
class TgController extends BaseController {

    protected $ajaxLoginActions = [
        'sync',
        'doSync',
    ];

    /**
     * Webhook
     * @author solu
     * @param $args
     */
    public function actionWebhook($args) {
        $content = file_get_contents("php://input");
        $update = json_decode($content, true);
        file_put_contents('/tmp/telegram_message.log', var_export($update, true), FILE_APPEND);
        if (isset($update["message"])) {
            try {
                Telegram::processMessage($update["message"]);
            } catch (Exception $e) {
                Response::error(CODE_NORMAL_ERROR, $e->getMessage());
            }
        }
    }

    /**
     * 同步确认页面
     * @author solu
     * @param $args
     * @return array
     */
    public function actionSync($args) {
        $rules = [
            'admin_id' => ['int', 'desc' => 'Telegram管理员id'],
            'group_id' => ['int', 'desc' => 'Telegram群id'],
            'auth_date' => ['int', 'desc' => '校验时间'],
            'hash' => ['string', 'desc' => '校验码'],
        ];
        Param::checkParam2($rules, $args);

        try {
            $args = ThirdApi::checkTelegramAuthorization($args);
        } catch (Exception $e) {
            Response::error(CODE_SIGN_ERROR, $e->getMessage());
        }

        $adminId = intval($args['admin_id']);
        $tgGroupId = intval($args['group_id']);
        $tgGroupInfo = ThirdApi::getTelegramChatInfo($tgGroupId);
        $tgGroupTitle = $tgGroupInfo['title'] ?: '';

        $userId = (new UserBindInfo())->getUserIdByTgId($args['admin_id']);
        $meeChatId = User::getUserId();

        // 判断是不是管理员自己
        if ($userId !== 0 && $userId != $meeChatId) {
            Response::error(CODE_NO_PERMITION, 'no permission');
        }

        $objGroup = new GroupInfo();
        // 已经绑定
        $alreadySync = $objGroup->objTable->getCount(['tg_group_id' => $tgGroupId]);

        // 未绑定的群
        $groups = $objGroup->objTable->getAll(['creator' => $userId, 'tg_group_id' => 0], [
            '_field' => 'group_id, group_title, group_name',
            '_sortKey' => 'group_id DESC',
        ]);

        return compact('alreadySync', 'adminId', 'tgGroupId', 'tgGroupTitle', 'userId', 'groups');
    }

    /**
     * 绑定操作
     * @author solu
     * @param $args
     * @throws DB_Exception
     */
    public function actionDoSync($args) {
        $rules = [
            'group_id' => ['int', 'desc' => 'MeeChat群id'],
            'tg_group_id' => ['int', 'desc' => 'Telegram群id'],
        ];
        Param::checkParam2($rules, $args);

        $userId = User::getUserId();
        $tgGroupId = intval($args['tg_group_id']);
        $objGroup = new GroupInfo();

        $group = $objGroup->objTable->getRow(['creator' => $userId, 'group_id' => $args['group_id']]);
        if (!$group) {
            Response::error(CODE_NO_PERMITION, 'no permission');
        }

        if ($objGroup->objTable->getCount(['tg_group_id' => $tgGroupId])) {
            Response::error(CODE_NORMAL_ERROR, 'already sync other group');
        }

        try {
            $objGroup->joinGroup(TG_BOT_ID, $args['group_id'], $group);
        } catch (Exception $e) {
            Response::error($e->getCode(), $e->getMessage());
        }

        Telegram::setGroupByTG($tgGroupId, $args['group_id']);
        $objGroup->objTable->updateObject(['tg_group_id' => $tgGroupId], ['group_id' => $args['group_id']]);

        // 绑定成功提示
        $url = "https://{$_SERVER['HTTP_HOST']}/s/{$group['group_name']}";
        $text = "该群已成功关联并同步MeeChat群组 \"{$url}\"
Group already synced with \"{$url}\"";
        try {
            Telegram::apiRequest('sendMessage', [
                'chat_id' => $tgGroupId,
                'text' => $text,
//                'parse_mode' => 'HTML',
            ]);
        } catch (Exception $e) {
            var_log($e->getMessage());
        }
    }
}