<?php

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

if ($user_rank != 'admin') {
    if (Settings::getSettings('offline') && $data) {
        $Telegram->answerCallbackQuery($Telegram->Callback_Query()->getId(), msg('offline2')."\n\n".$signature, true);
        die();
    }
}
if (preg_match('/^([Jj]oingame_)(.*)/', $data)) {
    $ex = explode('_', str_replace('joingame_', '', $data));
    $random_id = $ex[0];
    $type = $ex[1];
    if (Users::check($Userid) == false) {
        $Telegram->answerCallbackQuery($Telegram->Callback_Query()->getId(), msg('FirstJoinBot'), true);
        die();
    }
    if (Settings::getSettings('lock') == 1 && Channels::channelCount() > 0) {
        if ($user_rank != 'admin') {
            $beforToken = $Telegram->bot_token;
            $Telegram->bot_token = getStore('botDefToken');
            foreach (Channels::getAll() as $channel) {

                $get = $Telegram->getChatMember($channel->chatid, $Userid);
                if ($get->getOk() == false || !in_array($get->getResult()->getStatus(), [
                        'creator',
                        'member',
                        'administrator'
                    ])) {
                    $Telegram->bot_token = $beforToken;
                    $Telegram->answerCallbackQuery($Telegram->Callback_Query()->getId(), msg('errorGame_11'), true);
                    die();
                }

            }
            $Telegram->bot_token = $beforToken;
        }
    }
    if (Games::hasGame($random_id) == false) {
        $Telegram->answerCallbackQuery($Telegram->Callback_Query()->getId(), msg('errorGame_2'), true);
        die();
    }
    $game = Games::getGame($random_id);
    $sender = $game->sender;
    if ($sender == $Userid) {
        $Telegram->answerCallbackQuery($Telegram->Callback_Query()->getId(), msg('errorGame_1'), true);
        die();
    }

    $HasJoin = Games::addUser($random_id, $Userid);
    if ($HasJoin == false) {
        $Telegram->answerCallbackQuery($Telegram->Callback_Query()->getId(), msg('AlreadyJoinGame'), true);
        die();
    }
    $game = Games::getGame($random_id);
    $users = $game->users;
    if (count(explode('|', $users)) > 30) {
        $Telegram->answerCallbackQuery($Telegram->Callback_Query()->getId(), msg('LimitPlayer'), true);
        die();
    }
    $user_txt = '';
    $i = 1;
    $info_sender = $Telegram->getChat($sender);

    $info_sender_men = functions::generationMentions($sender, $info_sender->getResult()->getFirstName());

    foreach (explode('|', $users) as $user) {
        $info = $Telegram->getChat($user)->getResult()->getFirstName();
        Profile::updateRealname($user, $info);
        $info_men = functions::generationMentions($user, $info);
        $user_txt .= '- ' . $i . ' ' . $info_men . "\n";
        $i++;
    }
    $msginline = msg('startgame');
    if (Settings::getSettings('lock') == 1 && Channels::channelCount() > 0) {
        $chanel_id = '';
        $i = 1;
        $beforToken = $Telegram->bot_token;
        $Telegram->bot_token = getStore('botDefToken');
        foreach (Channels::getAll() as $channel) {
            $titles = $Telegram->getChat($channel->chatid)->getResult()->getTitle();
            $urlChannel = '<a href="' . $channel->link . '">' . $titles . '</a>';

            $chanel_id .= $i . '- ' . $urlChannel . "\n\n";
            $i++;
        }
        $Telegram->bot_token = $beforToken;
        $msginline = str_replace(['#channel'], [
            $chanel_id
        ], msg('startgameLock'));
    }
    $type_game = msg('game_' . $type);
    $txt = str_replace(['#name', '#users', '#type'], [
            $info_sender_men,
            $user_txt,
            $type_game
        ], $msginline)."\n\n".$signature;

    $Telegram->EditMessageText(null, null, $txt, 'html', $Telegram->callback_query()->getInlineMessageId(), true, [
        "inline_keyboard" =>
            [
                [["text" => msg('goTobot'), "url" => "https://t.me/" . USERNAME_BOT],],
                [
                    [
                        "text" => msg('StartGames'),
                        "callback_data" => "startgame_" . $random_id . '_' . $type,
                    ],
                    [
                        "text" => msg('joinToGame'),
                        "callback_data" => "joingame_" . $random_id . '_' . $type,
                    ]
                ]
            ]
    ]);
    $Telegram->answerCallbackQuery($Telegram->Callback_Query()->getId(), msg('succJoinGame'), true);

} elseif (preg_match('/^([Ss]tartgame)(.*)/', $data)) {
    $ex = explode('_', str_replace('startgame_', '', $data));
    $random_id = $ex[0];
    $type = $ex[1];
    $game = Games::getGame($random_id);
    $sender = $game->sender;
    $users = explode('|', $game->users);
    if (count($users) <= 1) {
        $Telegram->answerCallbackQuery($Telegram->Callback_Query()->getId(), msg('errorGame_5'), true);
        die();
    }
    if (Games::hasGame($random_id) == false) {
        $Telegram->answerCallbackQuery($Telegram->Callback_Query()->getId(), msg('errorGame_2'), true);
        die();
    }
    if ($sender != $Userid) {
        $Telegram->answerCallbackQuery($Telegram->Callback_Query()->getId(), msg('errorGame_3'), true);
        die();
    }
    $status_game = in_array($type, [3, 4]) ? 'plus' : 'Normal';
    Games::updateStatus($random_id, 'start');
    Games::updateType($random_id, $status_game);
    functions::createFolderGame($random_id);
    $cur = $users[array_rand($users, 1)];
    functions::createPlayerList($random_id, functions::arrayUnset($users, $cur));
    functions::createPlayerListClick($random_id, $users);
    functions::updateCurrentPlayer($random_id, $cur);

    functions::createInfoFile($random_id, [
        'type' => $type,
        'count' => count($users),
        'sender' => $sender
    ]);

    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));

    if (in_array($type, [3, 4])) {
        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));
    }

    $btn = $func->generation_btn($random_id, $type);
    $txt = str_replace(['#name'], [functions::generationMentions($cur, Profile::getRealName($cur))], msg('StartGame'))."\n\n".$signature;
    $Telegram->EditMessageText(null, null, $txt, 'html', $Telegram->callback_query()->getInlineMessageId(), true, $btn);

} elseif (preg_match('/^([Qq]uestion_)(.*)/', $data)) {
    $ex = explode('_', str_replace('question_', '', $data));
    $type_qu = $ex[0];
    $random_id = $ex[1];
    $type = $ex[2];
    // Check the existence of the game
    if (Games::hasGame($random_id) == false) {
        $Telegram->answerCallbackQuery($Telegram->Callback_Query()->getId(), msg('errorGame_2'), true);
        die();
    }
    //Check the identity of the current player
    if (functions::checkCurrentPlayer($random_id, $Userid) == false) {
        $Telegram->answerCallbackQuery($Telegram->Callback_Query()->getId(), msg('errorGame_4'), true);
        die();
    }
    Games::updateAt($random_id);
    //Check the type of game
    if (in_array($type, ['2', '4'])) {
        $playersCount = functions::getGameInfo($random_id)['count'];
        $playerCount = functions::getCountClick($random_id, $Userid);
        $count_q1 = $playerCount['q1'];
        $count_q2 = $playerCount['q2'];
        if ($count_q1 > $playersCount && in_array($type_qu, ['1', '3'])) {
            $Telegram->answerCallbackQuery($Telegram->Callback_Query()->getId(), msg('errorGame_6'), true);
            die();
        }
        if ($count_q2 > $playersCount && in_array($type_qu, ['2', '4'])) {
            $Telegram->answerCallbackQuery($Telegram->Callback_Query()->getId(), msg('errorGame_7'), true);
            die();
        }
        // Update the number of clicks
        if (in_array($type_qu, ['1', '3'])) {
            functions::updateCountClick($random_id, $Userid);
            functions::resetCountClick($random_id, $Userid, 'q2');
        } else {
            functions::updateCountClick($random_id, $Userid, 'q2');
            functions::resetCountClick($random_id, $Userid, 'q1');
        }

    }

    $gender = Profile::getUserSex($Userid);
    $filename = $gender != null ? $type_qu . '_' . $gender : $type_qu;
    //Checking for questions
    $check = functions::checkQuestion($random_id, $filename);
    if (!$check) {
        //Receive and update questions
        functions::createQuestion($random_id, $gender != null ? $type_qu . '_' . $gender : $type_qu, array_column($gender != null ? Question::getQuestionRandom($type_qu, $gender) : Question::getQuestionRandomNotsex($type_qu), 'question'));
    }
    //Get questions
    $qu = functions::getQuestion($random_id, $filename);
    $select_text = 'qu_' . $type_qu;
    $txt = str_replace(['#name', '#qu'], [
            functions::generationMentions($Userid, Profile::getRealName($Userid)),
            $qu
        ], msg($select_text))."\n\n".$signature;
    $Telegram->EditMessageText(null, null, $txt, 'html', $Telegram->callback_query()->getInlineMessageId(), true, $func->generation_Replybtn($random_id, $type));


} elseif (preg_match('/^([Rr]eplys_)(.*)/', $data)) {
    $ex = explode('_', str_replace('replys_', '', $data));
    $random_id = $ex[0];
    $type = $ex[1];
    if (functions::checkCurrentPlayer($random_id, $Userid) == false) {
        $Telegram->answerCallbackQuery($Telegram->Callback_Query()->getId(), msg('errorGame_4'), true);
        die();
    }
    $check = functions::checkPlayer($random_id);
    if (!$check) {
        $game = Games::getGame($random_id);
        $users = explode('|', $game->users);
        functions::updatePlayerList($random_id, $users);
    }
    Games::updateAt($random_id);
    $players = functions::getPlayer($random_id);
    functions::updateCurrentPlayer($random_id, $players);
    $btn = $func->generation_btn($random_id, $type);
    $txt = str_replace(['#name'], [functions::generationMentions($players, Profile::getRealName($players))], msg('nextgame'))."\n\n".$signature;
    $Telegram->EditMessageText(null, null, $txt, 'html', $Telegram->callback_query()->getInlineMessageId(), true, $btn);

} elseif (preg_match('/^([Nn]explayer_)(.*)/', $data)) {
    $ex = explode('_', str_replace('nexplayer_', '', $data));
    $random_id = $ex[0];
    $type = $ex[1];
    if (functions::checkGameSender($random_id, $Userid) == false) {
        $Telegram->answerCallbackQuery($Telegram->Callback_Query()->getId(), msg('errorGame_8'), true);
        die();
    }
    $check = functions::checkPlayer($random_id);
    if (!$check) {
        $game = Games::getGame($random_id);
        $users = explode('|', $game->users);
        functions::updatePlayerList($random_id, $users);
    }
    $players = functions::getPlayer($random_id);
    functions::updateCurrentPlayer($random_id, $players);
    $btn = $func->generation_btn($random_id, $type);
    $txt = str_replace(['#name'], [functions::generationMentions($players, Profile::getRealName($players))], msg('nextgame'))."\n\n".$signature;
    $Telegram->EditMessageText(null, null, $txt, 'html', $Telegram->callback_query()->getInlineMessageId(), true, $btn);

} elseif (preg_match('/^([Ee]ndgame_)(.*)/', $data)) {
    $ex = explode('_', str_replace('endgame_', '', $data));
    $random_id = $ex[0];
    $type = $ex[1];
    if (functions::checkGameSender($random_id, $Userid) == false) {
        $Telegram->answerCallbackQuery($Telegram->Callback_Query()->getId(), msg('errorGame_8'), true);
        die();
    }
    Games::updateAt($random_id);
    functions::deleteFolderAndSub($random_id);
    Games::removeGame($random_id);
    $Telegram->EditMessageText(null, null, msg('endgametxt'), 'html', $Telegram->callback_query()->getInlineMessageId(), true);

} elseif (preg_match('/^([Gg]ameTransfer_)(.*)/', $data)) {
    $ex = explode('_', str_replace('GameTransfer_', '', $data));
    $random_id = $ex[0];
    $type = $ex[1];

    $game = Games::getGame($random_id);
    $sender = $game->sender;
    if ($sender != $Userid) {
        $Telegram->answerCallbackQuery($Telegram->Callback_Query()->getId(), msg('errorGame_3'), true);
        die();
    }
    $Telegram->EditMessageText(null, null, msg('GameTransfertxt'), 'html', $Telegram->callback_query()->getInlineMessageId(), true, [
        'inline_keyboard' => [
            [
                [
                    "text" => msg('GameTransfer'),
                    "switch_inline_query_current_chat" => "resend_" . $random_id
                ],
            ],
        ],
        'resize_keyboard' => true
    ]);
}
