<?php

namespace inc;

use CURLFile;
use Database\blocked;

class functions
{
    public static $pathGames = __DIR__ . '/../Games/';

    public static function formatBot($bots)
    {
        $arr = [];

        foreach ($bots as $item) {
            $arr = array_merge($arr, [$item->bot => $item->token]);
        }
        return $arr;
    }

    public static function deleteAll($dir)
    {
        foreach (glob($dir . '/*') as $file) {
            if (is_dir($file))
                deleteAll($file);
            else
                unlink($file);
        }
        rmdir($dir);
    }

    public function memory_usage()
    {
        $mem_usage = memory_get_usage(true);
        if ($mem_usage < 1024) {
            return $mem_usage . " b";
        } elseif ($mem_usage < 1048576) {
            return round($mem_usage / 1024, 2) . " kb";
        } else {
            return round($mem_usage / 1048576, 2) . " mb";
        }
    }

    public function RandomText($length = 8)
    {
        $vmsString = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';

        return substr(str_shuffle($vmsString), 0, $length);
    }

    public function Randomnumber($length = 8)
    {
        return substr(str_shuffle('0123456789'), 0, $length);
    }

    public function regex_search($text, $vl)
    {

        foreach ($vl as $pt) {
            if (preg_match('/^' . $pt . '/', $text) or $pt == $text) {
                return true;
            }
        }

        return false;
    }


    public function Check_empty($v)
    {
        return empty($v) or is_null($v) or !isset($v);
    }

    public static function generationMentions($userid, $title)
    {
        return '<a href="tg://user?id=' . $userid . '">' . $title . '</a>';
    }

    public function TypeGame($type = 1)
    {

        return msg('game_' . $type);

    }

    public static function arrayUnset($arr, $value)
    {
        $ar = [];
        foreach ($arr as $item) {
            if ($item != $value) {
                $ar[] = $item;

            }
        }

        return $ar;
    }

    public function timeDiff($time)
    {
        $diff = time() - $time;
        if ($diff < 60) {
            return ['count' => $diff, 'type' => 'second'];
        } elseif ($diff < 3600) {
            return ['count' => round($diff / 60, 0, 1), 'type' => 'minutes'];
        } elseif ($diff >= 3660 && $diff < 86400) {
            return ['count' => round($diff / 3600, 0, 1), 'type' => 'hour'];

        } elseif ($diff > 86400) {
            return ['count' => round($diff / 86400, 0, 1), 'type' => 'day'];
        }
    }

    public static function deleteFolderAndSub($rand)
    {
        self::deleteAll(self::getPathGame($rand));
        return true;
    }

    // Games Folder
    public function generation_Replybtn($random_id, $type)
    {
        return [
            "inline_keyboard" =>
                [
                    [["text" => msg('goTobot'), "url" => "https://t.me/" . USERNAME_BOT],],
                    [["text" => msg('succreply'), "callback_data" => "replys_" . $random_id . '_' . $type,]],
                    [["text" => msg('nextplayer'), "callback_data" => "nexplayer_" . $random_id . '_' . $type]]
                ]
        ];
    }

    public function generation_BtnStart($random_id, $type)
    {
        return [
            "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,

                    ]
                ]
            ]
        ];
    }

    public function generation_btn($random_id, $type)
    {
        $btn = [
            "inline_keyboard" =>
                [
                    [["text" => msg('goTobot'), "url" => "https://t.me/" . USERNAME_BOT],],
                    [
                        [
                            "text" => msg('question_1'),
                            "callback_data" => "question_1_" . $random_id . '_' . $type,
                        ],
                        [
                            "text" => msg('question_2'),
                            "callback_data" => "question_2_" . $random_id . '_' . $type,
                        ],
                    ],
                    [
                        [
                            "text" => msg('nextplayer'),
                            "callback_data" => "nexplayer_" . $random_id . '_' . $type
                        ],
                        [
                            "text" => msg('endgame'),
                            "callback_data" => "endgame_" . $random_id . '_' . $type
                        ]
                    ],

                    [
                        [
                            "text" => msg('GameTransfer'),
                            "callback_data" => "GameTransfer_" . $random_id . '_' . $type
                        ]
                    ],
                ]
        ];
        if (in_array($type, [3, 4])) {
            $btn = [
                "inline_keyboard" =>
                    [
                        [["text" => msg('goTobot'), "url" => "https://t.me/" . USERNAME_BOT],],
                        [
                            [
                                "text" => msg('question_1'),
                                "callback_data" => "question_1_" . $random_id . '_' . $type,
                            ],
                            [
                                "text" => msg('question_2'),
                                "callback_data" => "question_2_" . $random_id . '_' . $type,
                            ],
                        ],
                        [
                            [
                                "text" => msg('question_3'),
                                "callback_data" => "question_3_" . $random_id . '_' . $type,
                            ],
                            [
                                "text" => msg('question_4'),
                                "callback_data" => "question_4_" . $random_id . '_' . $type,
                            ],
                        ],
                        [
                            [
                                "text" => msg('nextplayer'),
                                "callback_data" => "nexplayer_" . $random_id . '_' . $type
                            ],
                            [
                                "text" => msg('endgame'),
                                "callback_data" => "endgame_" . $random_id . '_' . $type
                            ]
                        ],
                        [
                            [
                                "text" => msg('GameTransfer'),
                                "callback_data" => "GameTransfer_" . $random_id . '_' . $type
                            ]
                        ],

                    ]
            ];
        }

        return $btn;
    }

    public static function getPathGame($rand)
    {
        return self::$pathGames . $rand;
    }

    public static function checkGameFolder($rand)
    {
        $dir = self::getPathGame($rand);

        return file_exists($dir);
    }

    public static function createFolderGame($rand_id)
    {
        $dir = self::getPathGame($rand_id);
        if (!file_exists($dir)) {
            mkdir($dir);
        }
    }


    public static function createFileOnGameFolder($rand_id, $filename, $data)
    {
        if (self::checkGameFolder($rand_id)) {
            file_put_contents(self::getPathGame($rand_id) . DIRECTORY_SEPARATOR . $filename . '.json', $data);
        }
    }

    public static function getFileOnGameFolder($rand_id, $filename)
    {
        if (self::checkGameFolder($rand_id)) {
            return json_decode(file_get_contents(self::getPathGame($rand_id) . DIRECTORY_SEPARATOR . $filename . '.json'), true);
        }

    }

    public static function updateCurrentPlayer($rand_id, $userid)
    {
        self::createFileOnGameFolder($rand_id, 'CurrentPlayer', json_encode([$userid]));
    }

    public static function createPlayerList($rand_id, $users)
    {
        if (self::checkGameFolder($rand_id)) {
            self::createFileOnGameFolder($rand_id, 'players', json_encode($users));
        }
    }

    public static function createPlayerListClick($rand_id, $users)
    {
        if (self::checkGameFolder($rand_id)) {
            $arr = [];
            if(is_array($users)){
                foreach ($users as $user) {
                    $arr[$user] = ['q1' => 0, 'q2' => 0];
                }
            }
            self::createFileOnGameFolder($rand_id, 'players_click', json_encode($arr));
        }
    }

    public static function getGameInfo($rand_id)
    {
        if (self::checkGameFolder($rand_id)) {
            return (array)self::getFileOnGameFolder($rand_id, 'info');
        }

    }

    public static function getCountClick($rand_id, $user)
    {
        $dir = 'Games/' . $rand_id;
        if (self::checkGameFolder($rand_id)) {
            $arr = (array)self::getFileOnGameFolder($rand_id, 'players_click');
            return $arr[$user];
        }
    }

    public static function updateCountClick($rand_id, $user, $t = 'q1')
    {
        if (self::checkGameFolder($rand_id)) {
            $arr = (array)self::getFileOnGameFolder($rand_id, 'players_click');
            $playerCount = self::getCountClick($rand_id, $user);
            $count_q1 = $playerCount['q1'];
            $count_q2 = $playerCount['q2'];
            if ($t == 'q1') {
                $arr[$user]['q1'] = $count_q1 + 1;
            } else {
                $arr[$user]['q2'] = $count_q2 + 1;
            }
            self::createPlayerListClick($rand_id, $user);
            return true;
        }
    }

    public static function resetCountClick($rand_id, $user, $t = 'q1')
    {
        if (self::checkGameFolder($rand_id)) {
            $arr = (array)self::getFileOnGameFolder($rand_id, 'players_click');

            if ($t == 'q1') {
                $arr[$user]['q1'] = 0;
            } else {
                $arr[$user]['q2'] = 0;
            }
            self::createPlayerListClick($rand_id, $user);

            return true;
        }
    }

    public static function updatePlayerList($rand_id, $users)
    {
        if (self::checkGameFolder($rand_id)) {
            self::createFileOnGameFolder($rand_id, 'players', json_encode($users));
        }
    }

    public static function createInfoFile($rand_id, $arr)
    {
        if (self::checkGameFolder($rand_id)) {
            self::createFileOnGameFolder($rand_id, 'info', json_encode($arr));
        }
    }

    public static function createQuestion($rand_id, $type, $question)
    {
        if (self::checkGameFolder($rand_id)) {
            self::createFileOnGameFolder($rand_id, 'question_' . $type, json_encode($question));
        }
    }

    public static function checkQuestion($rand_id, $type)
    {
        if (self::checkGameFolder($rand_id)) {
            $arr = self::getFileOnGameFolder($rand_id, 'question_' . $type);
            if (count($arr) > 0) {
                return true;
            }
        }

        return false;
    }

    public static function checkPlayer($rand_id)
    {
        if (self::checkGameFolder($rand_id)) {
            $arr = self::getFileOnGameFolder($rand_id, 'players');
            if (count($arr) > 0) {
                return true;
            }
        }

        return false;
    }

    public static function getPlayer($rand_id)
    {
        if (self::checkGameFolder($rand_id)) {
            $arr = self::getFileOnGameFolder($rand_id, 'players');
            $rand = array_rand($arr, 1);
            $pl = $arr[$rand];
            self::createFileOnGameFolder($rand_id, 'players', json_encode(self::arrayUnset($arr, $pl)));
            return $pl;
        }

        return false;
    }

    public static function getPlayers($rand_id)
    {
        if (self::checkGameFolder($rand_id)) {

            return self::getFileOnGameFolder($rand_id, 'players');
        }

        return false;
    }

    public static function getQuestion($rand_id, $type)
    {
        if (self::checkGameFolder($rand_id)) {

            $arr = self::getFileOnGameFolder($rand_id, 'question_' . $type);
            $rand = array_rand($arr, 1);
            $qu = $arr[$rand];
            self::createFileOnGameFolder($rand_id, 'question_' . $type, json_encode(self::arrayUnset($arr, $qu)));
            return $qu;
        }

        return false;
    }

    public static function checkCurrentPlayer($rand_id, $userid)
    {
        $dir = self::getPathGame($rand_id);
        $dir_file = self::getPathGame($rand_id) . '/CurrentPlayer.json';

        if (self::checkGameFolder($rand_id)) {
            $arr = json_decode(file_get_contents($dir_file), true);

            return $arr[0] == $userid;
        }

        return false;
    }

    public function GetCurrentPlayer($rand_id)
    {
        $dir = 'Games/' . $rand_id;
        $dir_file = 'Games/' . $rand_id . '/CurrentPlayer.json';

        if (file_exists($dir)) {
            return $arr = json_decode(file_get_contents($dir_file), true);
        }

        return false;
    }

    public static function checkGameSender($rand_id, $userid)
    {

        $dir = self::getPathGame($rand_id);
        $dir_file = self::getPathGame($rand_id) . '/info.json';

        if (self::checkGameFolder($rand_id)) {
            $arr = json_decode(file_get_contents($dir_file), true);
            return $arr['sender'] == $userid;
        }

        return false;
    }

    public function UploadPhoto($dir, $file)
    {
        file_put_contents($dir, file_get_contents($file));
    }

    public function lastAgotime($ptime)
    {
        $etime = time() - $ptime;

        if ($etime < 1) {
            return msg('lastNow');
        }

        $a = array(365 * 24 * 60 * 60 => 'year',
            30 * 24 * 60 * 60 => 'month',
            24 * 60 * 60 => 'day',
            60 * 60 => 'hour',
            60 => 'minute',
            1 => 'second'
        );
        $a_plural = array('year' => 'years',
            'month' => 'months',
            'day' => 'days',
            'hour' => 'hours',
            'minute' => 'minutes',
            'second' => 'seconds'
        );

        foreach ($a as $secs => $str) {
            $d = $etime / $secs;
            if ($d >= 1) {
                $r = round($d);
                $type = $str;
                if ($r > 1) {
                    $type = $a_plural[$str];
                }

                if ($type == 'seconds') {
                    return msg('lastNow');
                } elseif ($type == 'minutes' and $r == 1) {
                    return msg('lastOneMin');
                } elseif ($type == 'minutes') {
                    return str_replace('#time', $r, msg('lastMin'));
                } elseif ($type == 'hours' and $r == 1) {
                    return msg('lastOnehour');
                } elseif ($type == 'hours') {
                    return str_replace('#time', $r, msg('lasthour'));
                } elseif ($type == 'days' and $r == 1) {
                    return msg('lastOneDay');
                } elseif ($type == 'days') {
                    return str_replace('#time', $r, msg('lastDay'));
                } elseif ($type == 'month' and $r == 1) {
                    return msg('lastOnemonth');
                } elseif ($type == 'month') {
                    return str_replace('#time', $r, msg('lastmonth'));
                } elseif ($type == 'years' and $r == 1) {
                    return msg('lastOneyear');
                } elseif ($type == 'years') {
                    return str_replace('#time', $r, msg('lastyear'));
                }

//                return $r . ' ' . ($r > 1 ? $a_plural[$str] : $str) . ' ago';
            }
        }
    }

    public static function arraySortByColumn(&$arr, $col, $dir = SORT_ASC)
    {
        $sort_col = array();
        foreach ($arr as $key => $row) {
            $sort_col[$key] = $row[$col];
        }

        array_multisort($sort_col, $dir, $arr);
    }

    public static function checkBlockUser($Playerlist, $chatid)
    {

        foreach ($Playerlist as $users) {

            if (blocked::hasBlocked($chatid, $users->chatid) || blocked::hasUserBlocked($chatid, $users->chatid)) {
                return false;
            }

            return $users->chatid;

        }
    }
}