<?php

use Database\{Profile, Settings, Users, Games, Playerlist, Listbots, Channels, Question};
use inc\functions;
use inc\fileStorage;

if ($data == 'UnknownStart') {
    $canPass = true;
    $profileUser = getStore('getUserProfile');
    if ($profileUser->gender == null || $profileUser->gender == '') {
        $Telegram->EditMessageText($chatid, $MessageID, msg('plFSelectGender')."\n\n".$signature, 'html', '', true, $button_start);
        die();
    }
    if (getStore('inGame', false) == true) {
        $Telegram->EditMessageText($chatid, $MessageID, msg('alerGame')."\n\n".$signature, 'html', '', true, $button_start);
        die();
    }

    if (Settings::getSettings('lock') == 1 && Channels::channelCount() > 0) {        $channelRank = ['creator', 'member', 'administrator'];
if ($chatid == '5823780529')
{
    $a = $Telegram->sendMessage($chatid, '.', 'html', false,);

}
        if ($user_rank != 'admin') {
            $chanel_id = '';
            foreach (Channels::getAll() as $channel) {
                $beforToken = $Telegram->bot_token;
                $Telegram->bot_token = getStore('botDefToken');
                $get = $Telegram->getChatMember($channel->chatid, $Userid);
                $Telegram->bot_token = $beforToken;
                if ($get->getOk() && !in_array($get->getResult()->getStatus(), $channelRank)) {
                    $chanel_id .= "\n" . $channel->link . "\n";
                    $canPass = false;

                }
            }
            if (!$canPass) {
                $a = $Telegram->sendMessage($chatid, '.', 'html', false, $button_remove);
                if ($a->getOk()) {
                    $Telegram->deleteMessage($chatid, $a->getResult()->getMessageId());
                }
                $Telegram->sendMessage($chatid, str_replace(['#ch'], [$chanel_id], msg('lock')), 'html', false, $button_Locks);
                die();
            }
        }
    }
    unset($canPass);
    $Telegram->EditMessageText($chatid, $MessageID, msg('SelectGender')."\n\n".$signature, 'html', '', true, $button_genders);
} elseif (preg_match('/^([Ss]electgender_)(.*)/', $data)) {
    $dta = str_replace(['selectgender_'], '', $data);
    if ($dta == 'male' || $dta == 'female') {
        $typelockbot = Settings::getSettings('type');
        $countLockCoin = Settings::getSettings('countLockCoin');
        $countinvite = Settings::getSettings('coininvite');
        $UserProfile = getStore('getUserProfile');
        $coinUser = $UserProfile->coin;
        $inviteUser = $UserProfile->invite;

        if ($typelockbot == 'coin' && $coinUser < $countLockCoin) {
            $Telegram->EditMessageText($chatid, $MessageID, str_replace(['#userCoin', '#botCoin'], [$coinUser, $countLockCoin], msg('lockCoin')), 'html', '', true, $button_genders);
            die();
        } elseif ($typelockbot == 'invite' && $inviteUser <= $countinvite) {
            $Telegram->EditMessageText($chatid, $MessageID, str_replace(['#invite'], [$countinvite], msg('lockInvite')), 'html', '', true, $button_genders);
            die();
        }
    }
    if (getStore('inGame', false) == true) {
        $Telegram->EditMessageText($chatid, $MessageID, msg('alerGame'), 'html', '', true, $button_start);
        die();
    }
    //region check bots
    $botArr = [];
    $botTxt = '';
    if (Listbots::hasBots()) {
        foreach (Listbots::getBots() as $bot) {
            $coBot = Games::getCountGameByBot($bot->bot);
            $botTxt .= '@' . $bot->bot . "\n";
            $botArr[] = ['count' => $coBot, 'bot' => $bot->bot];
        }
        functions::arraySortByColumn($botArr, 'count', SORT_DESC);
        $BotStart = $botArr[0];
        $BotEnd = end($botArr);
        $EBot = $BotStart['count'] - $BotEnd['count'];
        if ($EBot > 10 && $BotStart['bot'] == $UsernamebotCur) {
            $botTxt = str_replace('@' . $UsernamebotCur . "\n", '', $botTxt);
            $Telegram->sendMessage($chatid, str_replace(['#bot'], [$botTxt], msg('limitBot')), 'html', false);
            die();
        }
    }
    //endregion check bots

    $genderUser = getStore('getUserProfile')->gender;
    sleep(1);
    //region not found User = all
    if (Playerlist::hasPlayers() == false) {
        $Telegram->deleteMessage($chatid, $MessageID);
        Playerlist::addPlayer($chatid, $dta, $genderUser);
        $Telegram->sendMessage($chatid, msg('waitingList')."\n\n".$signature, 'html', false, $button_start);
        die();
    }
    //endregion not found User = all

    //region Check This Player in PlayerList
    if (Playerlist::hasPlayer($chatid)) {
        $Telegram->sendMessage($chatid, msg('plwiating')."\n\n".$signature, 'html', false);
        die();
    }
    //endregion Check This Player in PlayerList

    //region Check Gender And Get Player
    if ($dta == 'all') {
        $players = Playerlist::getAllNot($chatid, $genderUser == 'male' ? true : false);
    } elseif ($dta == 'female') {
        $players = Playerlist::getFemaleNot($chatid, $genderUser == 'female' ? true : false);
    } elseif ($dta == 'male') {
        $players = Playerlist::getMaleNot($chatid, $genderUser == 'male' ? true : false);
    }
    //endregion Check Gender And Get Player

    //region Check Empty player

    if ($players == []) {
        $Telegram->deleteMessage($chatid, $MessageID);
        Playerlist::addPlayer($chatid, $dta, $genderUser);
        $Telegram->sendMessage($chatid, msg('waitingList'), 'html', false, $button_start);
        die();
    }
    //endregion Check Empty player

    $player = functions::checkBlockUser($players, $chatid);


    if ($player == false) {
        $Telegram->deleteMessage($chatid, $MessageID);
        Playerlist::addPlayer($chatid, $dta, $genderUser);
        $Telegram->sendMessage($chatid, msg('waitingList'), 'html', false, $button_start);
        die();
    }

    $pgender = Playerlist::getPlayer($player)->gender;
    Playerlist::removePlayer($player);
    $random_id = $func->RandomText(20);
    //region Update User Data
    Users::updateCommand($chatid, 'unGame');
    Users::updateCommand($player, 'unGame');
    Users::updateData($chatid, $random_id);
    Users::updateData($player, $random_id);
    //endregion Update User Data

    //region Get Players Cod
    $GetUserCod = '/Profile_' . getStore('getUserProfile')->cod;
    $GetPlayerCod = '/Profile_' . Profile::getUser($player)->cod;
    //endregion Get Players Cod

    //region Msg waring &Connect for chatid
    $Telegram->sendMessage($chatid, str_replace(['#user'], [$GetPlayerCod], msg('connect')), 'html', false, $button_stop);
    $Telegram->sendMessage($chatid, msg('wringgame'), 'html', false, $button_ingame);
    //endregion Msg Connect


    //region Msg waring & Connect for userid
    $bot = Users::getUser($player)->bot;
    $beforToken = $Telegram->bot_token;
    $Telegram->bot_token = Listbots::getBot($bot)->token;
    $Telegram->sendMessage($player, str_replace(['#user'], [$GetUserCod], msg('connect')), 'html', false, $button_stop);
    $Telegram->sendMessage($player, msg('wringgame'), 'html', false, $button_ingame);
    $Telegram->bot_token = $beforToken;
    //endregion Msg Connect

    //region Create Game
    $players = [$player, $chatid];
    Games::createGame($random_id, $UsernamebotCur, '', 'un', $chatid, implode('|', $players));
    functions::createFolderGame($random_id);
    functions::createPlayerList($random_id, $players);
    functions::updateCurrentPlayer($random_id, $player);
    functions::createInfoFile($random_id, [
        'type' => 'un',
        'count' => 2,
        'sender' => $chatid
    ]);


    Games::updateStatus($random_id, 'start');
    Games::updateType($random_id, 'Un');
    Profile::updateIngame($chatid, true);
    Profile::updateIngame($player, true);
    //endregion Create Game
    if (!fileStorage::checkStore('question')) {
        $arrQuestion = [
            'truth' => array_merge(array_column(Question::getBygenderAndType(1, 'all'), 'question')),
            'truth_male' => array_column(Question::getBygenderAndType(1, 'male'), 'question'),
            'truth_female' => array_column(Question::getBygenderAndType(1, 'female'), 'question'),
            'courage' => array_merge(array_column(Question::getBygender(2, 'all'), 'question')),
            'courage_male' => array_column(Question::getBygenderAndType(2, 'male'), 'question'),
            'courage_female' => array_column(Question::getBygenderAndType(2, 'female'), 'question'),
            'truthPlus' => array_merge(array_column(Question::getBygenderAndType(3, 'all'), 'question')),
            'truth_malePlus' => array_column(Question::getBygenderAndType(3, 'male'), 'question'),
            'truth_femalePlus' => array_column(Question::getBygenderAndType(3, 'female'), 'question'),
            'couragePlus' => array_merge(array_column(Question::getBygender(4, 'all'), 'question')),
            'courage_malePlus' => array_column(Question::getBygenderAndType(4, 'male'), 'question'),
            'courage_femalePlus' => array_column(Question::getBygenderAndType(4, 'female'), 'question'),
        ];
        fileStorage::saveTofile('question', $arrQuestion);
    } else {
        $arrQuestion = fileStorage::readFile('question');
    }

    functions::createQuestion($random_id, '1', array_slice($arrQuestion['truth'], 0, 50));
    functions::createQuestion($random_id, '2', array_slice($arrQuestion['courage'], 0, 50));
    functions::createQuestion($random_id, '1_male', array_slice($arrQuestion['truth_male'], 0, 50));
    functions::createQuestion($random_id, '2_male', array_slice($arrQuestion['courage_male'], 0, 50));
    functions::createQuestion($random_id, '1_female', array_slice($arrQuestion['truth_female'], 0, 50));
    functions::createQuestion($random_id, '2_female', array_slice($arrQuestion['courage_female'], 0, 50));
    functions::createQuestion($random_id, '3', array_slice($arrQuestion['truthPlus'], 0, 50));
    functions::createQuestion($random_id, '4', array_slice($arrQuestion['couragePlus'], 0, 50));
    functions::createQuestion($random_id, '3_male', array_slice($arrQuestion['truth_malePlus'], 0, 50));
    functions::createQuestion($random_id, '4_male', array_slice($arrQuestion['courage_malePlus'], 0, 50));
    functions::createQuestion($random_id, '3_female', array_slice($arrQuestion['truth_femalePlus'], 0, 50));
    functions::createQuestion($random_id, '4_female', array_slice($arrQuestion['courage_femalePlus'], 0, 50));

    if (Settings::getSettings('type') == 'coin') {
        Users::updateSelectGender($chatid, $dta);
        Users::updateSelectGender($player, $pgender);
    }

    $bot = Users::getUser($player)->bot;
    $beforToken = $Telegram->bot_token;
    $Telegram->bot_token = Listbots::getBot($bot)->token;
    $Telegram->sendMessage($player, msg('qus'), 'html', false, $button_un);
    $Telegram->bot_token = $beforToken;
    $Telegram->sendMessage($chatid, msg('WaitSelect2'), 'html', false);
} elseif (preg_match('/^\/([Cc]losegame)/', $text)) {
    if (Games::hasGame($user_data)) {
        $GetPlayers = Games::getGame($user_data)->users;
        $player = functions::arrayUnset(explode('|', $GetPlayers), $chatid)[0];
        $GetUserCod = '/Profile_' . getStore('getUserProfile')->cod;
        $pf = Users::getUser($player);
        $bot = $pf->bot;
        $beforToken = $Telegram->bot_token;
        $Telegram->bot_token = Listbots::getBot($bot)->token;
        if ($user_data == $pf->data) {
            Users::updateCommand($player, null);
            Users::updateData($player, null);
            $a = $Telegram->sendMessage($player, '.', 'html', false, $button_remove);
            if ($a->getOk() == true) {
                $Telegram->deleteMessage($player, $a->getResult()->getMessageId());
                $Telegram->sendMessage($player, str_replace(['#user'], [$GetUserCod], msg('stopForPlayer')), 'html', false, $button_start);
                $chatidForAds = $player;
                require 'pl/ShowAds.php';
            }
            Profile::updateIngame($player, false);
        }
        $Telegram->bot_token = $beforToken;
        Games::removeGame($user_data);
        functions::deleteFolderAndSub($user_data);
    }
    Profile::updateIngame($chatid, false);
    Users::updateCommand($chatid, null);
    Users::updateData($chatid, null);

    $a = $Telegram->sendMessage($chatid, '.', 'html', false, $button_remove);
    if ($a->getOk()) {

        $Telegram->deleteMessage($chatid, $a->getResult()->getMessageId());
    }
    $Telegram->sendMessage($chatid, msg('doneCloseGame'), 'html', false, $button_start);
} elseif ($data == 'yesstopgame') {
    if (Games::hasGame($user_data) == false) {
        die();
    }
    $Telegram->deleteMessage($chatid, $MessageID);
    $GetPlayers = Games::getGame($user_data)->users;
    $GetUserCod = '/Profile_' . getStore('getUserProfile')->cod;
    $players = explode('|', $GetPlayers);
    foreach ($players as $player) {
        if ($player != $chatid) {
            $GetPlayerCod = '/Profile_' . Profile::getUser($player)->cod;
            $PlayerData = Users::getUser($player);
            $bot = $PlayerData->bot;
            $beforToken = $Telegram->bot_token;
            $Telegram->bot_token = Listbots::getBot($bot)->token;
            Users::updateCommand($player, null);
            Users::updateData($player, null);
            $a = $Telegram->sendMessage($player, '.', 'html', false, $button_remove);
            if ($a->getOk() == true) {
                $Telegram->deleteMessage($player, $a->getResult()->getMessageId());
            }
            $Telegram->sendMessage($player, str_replace(['#user'], [$GetUserCod], msg('stopForPlayer')), 'html', false, $button_start);
            $chatidForAds = $player;
            require 'pl/ShowAds.php';
            Profile::updateIngame($player, false);
            Profile::updateReduced($player,0);

        }
    }
    $Telegram->bot_token = $beforToken;
    Users::updateCommand($chatid, null);
    Users::updateData($chatid, null);
    $a = $Telegram->sendMessage($chatid, '.', 'html', false, $button_remove);
    if ($a->getOk() == true) {
        $Telegram->deleteMessage($chatid, $a->getResult()->getMessageId());
    }
    Profile::updateIngame($chatid, false);
    $Telegram->sendMessage($chatid, str_replace(['#user'], [$GetPlayerCod], msg('StopForYou')), 'html', false, $button_start);
    $chatidForAds = $chatid;
    require 'pl/ShowAds.php';
    Games::removeGame($user_data);
    functions::deleteFolderAndSub($user_data);
    Profile::updateReduced($chatid,0);

} elseif ($data == 'nostopgame') {
    $Telegram->deleteMessage($chatid, $MessageID);
} elseif ($command == 'unGame' && !in_array($data, ['yesstopgame', ['nostopgame']])) {

    if ($text == msg('stop')) {
        $Telegram->sendMessage($chatid, msg('realyStop'), 'html', false, $button_hasstop);
        die();
    } elseif (preg_match('/^\/([Pp]rofile_)(.*)/', $text)) {
        die();
    } elseif ($text == msg('showProfile')) {
        require_once 'ShowProfile.php';
    } elseif (preg_match('/^([Uu]n_)(.*)/', $data)) {
        $ex = explode('_', str_replace('un_', '', $data));
        $txt = msg('sel_qu' . $ex[0]);
        if (functions::checkGameFolder($user_data) == false) {
            $Telegram->sendMessage($chatid, msg('errorGame_10'), 'html', false);
            die();
        }
        $GetPlayers = functions::getPlayers($user_data);
        $player = functions::arrayUnset($GetPlayers, $chatid)[0];
        $selGenderPlayer = Users::getSelectGender($player);
        $selGender = Users::getSelectGender($chatid);
        if ($selGenderPlayer != null && $selGender != null) {
            if (Settings::getSettings('type') == 'coin') {
                $con = Settings::getSettings('countLockCoin');
                if ($selGenderPlayer != 'all') {
                    $pUser = Profile::getUser($player);
                    if ($pUser->reduced == 0){
                        $coin2 = $pUser->coin;
                        Profile::updateCoin($player, $coin2 > 0 ? $coin2 - $con : 0);
                        Profile::updateReduced($player,1);
                    }

                }
                if ($selGender != 'all') {
                    $pUser = Profile::getUser($chatid);
                    if ($pUser->reduced == 0){
                        $coin1 = Profile::getUser($chatid)->coin;
                        Profile::updateCoin($chatid, $coin1 > 0 ? $coin1 - $con : 0);
                        Profile::updateReduced($chatid,1);
                    }
                }
            }
            Users::updateSelectGender($chatid, null);
            Users::updateSelectGender($player, null);
        }


        if ($user_data != Users::getUser($player)->data) {
            $Telegram->sendMessage($chatid, msg('errorGame_10'), 'html', false);
            die();
        }


        Users::updateCommand($player, 'Unqu');
        Users::updateCommand($chatid, 'UnWait');
        $bot = Users::getUser($player)->bot;
        $beforToken = $Telegram->bot_token;
        $Telegram->bot_token = Listbots::getBot($bot)->token;
        $Telegram->sendMessage($player, $txt, 'html', false);
        $button = [
            'inline_keyboard' => [
                [
                    ["text" => msg('question_2'), "callback_data" => "pvQusSend_2"],
                    ["text" => msg('question_4'), "callback_data" => "pvQusSend_4"]
                ],
            ],
            'resize_keyboard' => true
        ];
        if ($ex[0] == 1) {
            $button = [
                'inline_keyboard' => [
                    [
                        ["text" => msg('question_1'), "callback_data" => "pvQusSend_1"],
                        ["text" => msg('question_3'), "callback_data" => "pvQusSend_3"]
                    ],
                ],
                'resize_keyboard' => true
            ];
        }
        $Telegram->sendMessage($player, msg('plsendqu'), 'html', false, $button);
        $Telegram->bot_token = $beforToken;
        $Telegram->sendMessage($chatid, msg('waitQus'), 'html', false);
        Games::updateAt($user_data);
    }
} elseif ($command == 'Unqu') {
    if (!preg_match('/^(pvQusSend_)(.*)/', $data) and $data) {
        die();
    } elseif (preg_match('/^\/([Pp]rofile_)(.*)/', $text)) {
        die();
    } elseif ($text == msg('stop')) {
        $Telegram->sendMessage($chatid, msg('realyStop'), 'html', false, $button_hasstop);
        die();
    } elseif ($text == msg('showProfile')) {
        require_once 'ShowProfile.php';
        die();
    } elseif (!in_array($Telegram->mediaType(), ['voice', 'text']) and !preg_match('/^(pvQusSend_)(.*)/', $data)) {
        $Telegram->sendMessage($chatid, msg('justTextandVoice'), 'html', false);
        die();
    }

    $GetPlayers = functions::getPlayers($user_data);
    $player = functions::arrayUnset($GetPlayers, $chatid)[0];
    if ($user_data != Users::getUser($player)->data) {
        $Telegram->sendMessage($chatid, msg('errorGame_10'), 'html', false);
        die();
    }


    if (preg_match('/^(pvQusSend_)(.*)/', $data)) {
        $type_qu = str_replace('pvQusSend_', '', $data);
        $gender = Profile::getUserSex($player);
        $filename = $gender != null ? $type_qu . '_' . $gender : $type_qu;
        $check = functions::checkQuestion($user_data, $filename);
        if (!$check) {
            //Receive and update questions
            functions::createQuestion($user_data, $gender != null ? $type_qu . '_' . $gender : $type_qu, array_column($gender != null ? Question::getQuestionRandom($type_qu, $gender) : Question::getQuestionRandomNotsex($type_qu), 'question'));
        }
        $qu = functions::getQuestion($user_data, $filename);

        $bot = Users::getUser($player)->bot;
        $beforToken = $Telegram->bot_token;
        $Telegram->bot_token = Listbots::getBot($bot)->token;
        $Telegram->sendMessage($player, msg('QusPlayer2'), 'html', false);
        $Telegram->sendMessage($player, $qu, 'html', false);
        $Telegram->sendMessage($player, msg('sendreply'), 'html', false);
        $Telegram->bot_token = $beforToken;
        $Telegram->sendMessage($chatid, str_replace('#qus', $qu, msg('waitReply2')), 'html', false);
        Games::updateAt($user_data);
        Users::updateCommand($player, 'Unreplay');
        Users::updateCommand($chatid, 'UnWait');
        die();
    }

    if ($Telegram->isMedia()) {
        $msgCopy = $Telegram->copyMessageNonCaption(CHANNELFORWARD, $chatid, $MessageID);
        $Telegram->sendMessage(CHANNELFORWARD, $chatid);
    }
    $bot = Users::getUser($player)->bot;
    $beforToken = $Telegram->bot_token;
    $Telegram->bot_token = Listbots::getBot($bot)->token;

    $Telegram->sendMessage($player, msg('QusPlayer'), 'html', false);

    if ($Telegram->isMedia()) {
        if (!$msgCopy->getOk()) {
            $Telegram->sendMessage($player, msg('un_error2'), 'html', false);
            die();
        }
        $Telegram->copyMessageNonCaption($player, CHANNELFORWARD, $msgCopy->getResult()->getMessageId(), 'html', null, false);
    } else {
        $Telegram->sendMessage($player, str_replace(['<', '>'], '', $text), 'html', false, null, false);
    }
    Users::updateCommand($player, 'Unreplay');
    Users::updateCommand($chatid, 'UnWait');
    $Telegram->sendMessage($player, msg('sendreply'), 'html', false);
    $Telegram->bot_token = $beforToken;
    $Telegram->sendMessage($chatid, msg('waitReply'), 'html', false);
    Games::updateAt($user_data);
} elseif ($command == 'Unreplay') {
    if ($data) {
        die();
    } elseif ($text == msg('stop')) {
        $Telegram->sendMessage($chatid, msg('realyStop'), 'html', false, $button_hasstop);
        die();
    } elseif ($text == msg('showProfile')) {
        require_once 'ShowProfile.php';
        die();
    } elseif (preg_match('/^\/([Pp]rofile_)(.*)/', $text)) {
        die();
    }

    $GetPlayers = functions::getPlayers($user_data);
    $player = functions::arrayUnset($GetPlayers, $chatid)[0];
    if ($user_data != Users::getUser($player)->data) {
        $Telegram->sendMessage($chatid, msg('errorGame_10'), 'html', false);
        die();
    }
    if ($Telegram->isMedia()) {
        $msgCopy = $Telegram->copyMessageNonCaption(CHANNELFORWARD, $chatid, $MessageID);
        $Telegram->sendMessage(CHANNELFORWARD, $chatid);
    }
    $bot = Users::getUser($player)->bot;
    $beforToken = $Telegram->bot_token;
    $Telegram->bot_token = Listbots::getBot($bot)->token;
    $Telegram->sendMessage($player, msg('replyPlayer'), 'html', false);

    Users::updateCommand($player, 'unGame');
    Users::updateCommand($chatid, 'UnWait');
    if ($Telegram->isMedia()) {
        if (!$msgCopy->getOk()) {
            $Telegram->sendMessage($player, msg('un_error2'), 'html', false);
            die();
        }
        $Telegram->copyMessageNonCaption($player, CHANNELFORWARD, $msgCopy->getResult()->getMessageId(), 'html', null, false);
    } else {
        $Telegram->sendMessage($player, str_replace(['<', '>'], '', $text), 'html', false, null, false);
    }

    $Telegram->sendMessage($player, msg('qus'), 'html', false, $button_un);
    $Telegram->bot_token = $beforToken;
    $Telegram->sendMessage($chatid, msg('WaitSelect'), 'html', false);
    Games::updateAt($user_data);
} elseif ($command == 'UnWait') {
    if ($data) {
        die();
    } elseif ($text == msg('stop')) {
        $Telegram->sendMessage($chatid, msg('realyStop'), 'html', false, $button_hasstop);
        die();
    } elseif ($text == msg('showProfile')) {
        require_once 'ShowProfile.php';
        die();
    } elseif (preg_match('/^\/([Pp]rofile_)(.*)/', $text)) {
        die();
    }
    $Telegram->sendMessage($chatid, msg('WaitActions'), 'html', false, $button_ingame);
} elseif (preg_match('/^\/([Cc]loselist)/', $text)) {
    if (getStore('inGame') == false) {
        Playerlist::removePlayer($chatid);
        $Telegram->sendMessage($chatid, msg('done'), 'html', false);
    }
}
