<?php

/**
 * Created by PhpStorm.
 * User: Admin
 * Date: 01.12.2016
 * Time: 21:37
 */
class Cabinet
{
    /**
     * @var bool The account is online
     */
    public $AccountOnline;

    public function __construct()
    {
        if ($this->isLogin()) {
            if (isset($_SESSION['cabinet_login'])) {
                if (App::$DBs[$_SESSION['cabinet_db']]
                    ->select('memb___id')
                    ->from('MEMB_STAT')
                    ->where('ConnectStat', 1)
                    ->where('memb___id', $_SESSION['cabinet_login'])
                    ->count_all_results()
                ) {
                    $this->AccountOnline = true;
                } else {
                    $this->AccountOnline = false;
                }
            } else {
                $this->AccountOnline = false;
            }
        } else {
            $this->AccountOnline = false;
        }


    }
    public static function ValidateEmail($email)
    {
        if (function_exists("filter_var")) {
            $s = filter_var($email, FILTER_VALIDATE_EMAIL);
            return !empty($s);
        }
    }

    public function Register()
    {
        if (property_exists(App::$Post, 'num_db') && App::$Post->num_db > 0 && App::$Post->num_db < App::$countDB)
            $Db = App::Validate(App::$Post->num_db);
        else
            $Db = 0;

        if (property_exists(App::$Post, 'login'))
            $login = App::Validate(App::$Post->prefix.App::$Post->login);
        else
            $login = "";
        if (property_exists(App::$Post, 'name'))
            $name = App::Validate(App::$Post->name);
        else
            $name = "";
        if (property_exists(App::$Post, 'pass'))
            $pass = App::Validate(App::$Post->pass);
        else
            $pass = "";
        if (property_exists(App::$Post, 'repass'))
            $repass = App::Validate(App::$Post->repass);
        else
            $repass = "";
        if (property_exists(App::$Post, 'email'))
            $email = App::Validate(App::$Post->email);
        else
            $email = "";
        if (property_exists(App::$Post, 'referer'))
            $referer = App::Validate(App::$Post->referer);
        else
            $referer = "";


        if (strlen($login) < 3 || strlen($login) >= 10)
            Messages::Add('incorect_login');
        if (App::$Configs->user['NeedName'])
            if (strlen($name) < 3 || strlen($name) >= 10)
                Messages::Add('incorect_name');
        if (strlen($pass) < 3 || strlen($pass) >= 10)
            Messages::Add('incorect_pass');
        if ($repass !== $pass)
            Messages::Add('incorect_repass');
        if (strlen($email) < 3 || strlen($email) > 30 || !static::ValidateEmail($email))
            Messages::Add('incorect_email');
        if ($referer != "") {
            if (strlen($referer) > 20 || strlen($referer) < 3) {
                Messages::Add('incorect_referer');
            }
        }

        if (!Messages::CountMessages()) {
            if (App::$DBs[$Db]
                ->select('mail_addr')
                ->from('MEMB_INFO')
                ->where('mail_addr', $email)
                ->count_all_results()) {
                Messages::Add('exists_mail');
            }
            if (App::$DBs[$Db]
                ->select('memb___id')
                ->from('MEMB_INFO')
                ->where('memb___id', $login)
                ->count_all_results()) {
                Messages::Add('exists_login');
            }
        }
        if ($referer != "") {
            if (static::IssetAccount($referer, $Db) == false) {
                Messages::Add('incorect_referer');
            }
        }

        if (!Messages::CountMessages()) {

            $RegisterArr = array();

            if (App::$Configs->user['LoginToLower'])
                $RegisterArr['memb___id'] = strtolower($login);
            else
                $RegisterArr['memb___id'] = $login;

            $RegisterArr['memb__pwd'] = $pass;

            if (App::$Configs->user['NeedName'])
                $RegisterArr['memb_name'] = $name;

            $RegisterArr['bloc_code'] = 0;
            $RegisterArr['ctl1_code'] = 1;
            $RegisterArr['mail_addr'] = $email;
            $RegisterArr['rdate'] = time();

            //Premium
            $FinalTime = time() + ($Count * 60 * 60 * 24);
            $RegisterArr['AccountLevel'] = 1;
            $RegisterArr['AccountExpireDate'] = date("Y-m-d H:i:s", $FinalTime);

            if (App::$Configs->customs['madmu'])
                $RegisterArr['sno__numb'] = 1;
            else
                $RegisterArr['sno_numb'] = 1;

            if ( App::$DBs[$Db]->insert('MEMB_INFO', $RegisterArr)) {
                App::$DBs[$Db]->insert('CashShopData' ,array('AccountID' => $RegisterArr['memb___id'],'WCoinC' => 0,'WCoinP' => 0,'GoblinPoint' => 0));
                
                if ($referer != "") {
                    ReferralSystem::AddReferral($referer, $login, $Db);
                }
                Messages::Add('success_register_login', $RegisterArr['memb___id']);
                Messages::Add('success_register_pass', $pass);
                if (App::$Configs->user['NeedName'])
                    Messages::Add('success_register_name', $name);
                Messages::Add('success_register_email', $email);

                $_SESSION['RegFile'] = "
Игровой сервер Freyamu.RU\r\n
Данные для авторизации :\r\n
Login: $login\r\n
Password: $pass\r\n
Name: $name\r\n
Email: $email\r\n
Храните их в надежном месте!\r\n"
                ;

                

               /* header( 'Location: /cabinet' );
                die;*/
                //header("Location: /cabinet");

 $Title = "Успешная регистрация";
            $From = "From: Администрация Freyamu.RU";
            $Message = "Регистрационные данные.\r\n".
                "Вы получили это письмо, поскольку вы успешно зарегистрировались на сайте Freyamu.RU.\r\n\r\n".
                "Login: ".$login."\r\n".
                "Password: ".$pass."\r\n".
                "Name: ".$name."\r\n".
                "Email: ".$email."\r\n".
                "Приятной вам игры на нашем сервере!\r\n\r\n".
                "Пожалуйста не отвечайте на это сообщение. Сообщение отправлено роботом, который не сможет Вам ответить.\r\n\r\n";
            mail($email, $Title, $Message, $From);

                Logs::WriteLog("Account [{$login}] Register Success Referrer -- {$referer} IP: [{$_SERVER['REMOTE_ADDR']}] DB: [{$Db}]", 'User.log');
                return true;
            } else {
                Logs::WriteLog("Account [{$login}] Register Fail Referrer -- {$referer} IP: [{$_SERVER['REMOTE_ADDR']}] DB: [{$Db}]", 'User.log');
                Messages::Add('Неудачная попытка регистрации');
                return false;
            }
        }
    }
    public function Login()
    {
        if (property_exists(App::$Post, 'login_db') && App::$Post->login_db > 0 && App::$Post->login_db < App::$countDB)
            $Db = App::Validate(App::$Post->login_db);
        else
            $Db = 0;

        if (property_exists(App::$Post, 'login'))
            $login = App::Validate(App::$Post->login);
        else
            return false;
        if (property_exists(App::$Post, 'pass'))
            $pass = App::Validate(App::$Post->pass);
        else
            return false;


        if (App::$DBs[$Db]
            ->select('memb___id, memb__pwd')
            ->from('MEMB_INFO')
            ->where('memb___id', $login)
            ->where('memb__pwd', $pass)
            ->count_all_results()
        )
        {
            $_SESSION['cabinet_login'] = $login;
            $_SESSION['cabinet_db'] = $Db;
            Logs::WriteLog("Account [{$login}] Success Login IP: [{$_SERVER['REMOTE_ADDR']}] DB: [{$Db}]", 'Cabinet/User.log');
            return true;
        }
        Messages::Add("Неправильный логин или пароль");
        var_dump($_SESSION);
        Logs::WriteLog("Account [{$login}] Login Fail IP: [{$_SERVER['REMOTE_ADDR']}] DB: [{$Db}]", 'Cabinet/User.log');
        Messages::Add('login_pass_incorect');
        return false;
    }
    public function isLogin()
    {
        if (isset($_SESSION['cabinet_login']) && $_SESSION['cabinet_login'] != "") {
            return true;
        } else {
            return false;
        }
    }
    public static function Logout()
    {
        unset($_SESSION['cabinet_login']);
        $Db = $_SESSION['cabinet_db'];
        unset($_SESSION['cabinet_db']);

        Logs::WriteLog("Account [{$_SESSION['cabinet_login']}] Logout IP: [{$_SERVER['REMOTE_ADDR']}] DB: [{$Db}]", 'Cabinet/User.log');
        session_unset();
        session_destroy();
        setcookie(session_name(),'');
    }
    public function PanelInfo()
    {
        $ReturnArr = array();
        $forum = new Forum();
        $ReturnArr['ForumPost'] = $forum->Main();
        $ReturnArr['AccountInfo']['CurrentIP'] = $_SERVER['REMOTE_ADDR'];
        $ReturnArr['AccountInfo']['AccountOnline'] = $this->AccountOnline;
        $row = App::$DBs[$_SESSION['cabinet_db']]
            ->select(array('GameID1','GameID2', 'GameID3','GameID4','GameID5'))
            ->where('ID', $_SESSION['cabinet_login'])
            ->from('AccountCharacter')
            ->get()->result_array();

        $row = $row[0];
        if (
            $row['GameID1'] == NULL &&
            $row['GameID2'] == NULL &&
            $row['GameID3'] == NULL &&
            $row['GameID4'] == NULL &&
            $row['GameID5'] == NULL
            ) {
            $ReturnArr['Chars'] = "Персонажей не найдено";
        } else {
            
            if($row['GameID1'])
                $ReturnArr['Chars'][0] = $this->CharInfo($row['GameID1']);
            else
                $ReturnArr['Chars'][0] = null;
            
            if($row['GameID2'])
                $ReturnArr['Chars'][1] = $this->CharInfo($row['GameID2']);
            else
                $ReturnArr['Chars'][1] = null;
            
            if($row['GameID3'])
                $ReturnArr['Chars'][2] = $this->CharInfo($row['GameID3']);
            else
                $ReturnArr['Chars'][2] = null;
            
            if($row['GameID4'])
                $ReturnArr['Chars'][3] = $this->CharInfo($row['GameID4']);
            else
                $ReturnArr['Chars'][3] = null;
            
            if($row['GameID5'])
                $ReturnArr['Chars'][4] = $this->CharInfo($row['GameID5']);
            else
                $ReturnArr['Chars'][4] = null;

        }


        $ReturnArr['Info'] = App::$DBs[$_SESSION['cabinet_db']]->select(array('rdate', 'mail_addr' ))->from("MEMB_INFO")->where('memb___id', $_SESSION['cabinet_login'])->get()->result_array();
        $ReturnArr['AccountInfo']['RegisterDate'] = $ReturnArr['Info'][0]['rdate'];
        $ReturnArr['AccountInfo']['Mail'] = $ReturnArr['Info'][0]['mail_addr'];
        return $ReturnArr;
    }
    public function StatisticInfo()
    {
        $ReturnArr = array();
        $ReturnArr['Players'] = Statistic::TopPlayers('', $_SESSION['cabinet_db']);
        $ReturnArr['Guilds'] = Statistic::TopGuilds($_SESSION['cabinet_db']);
        $ReturnArr['Killers'] = Statistic::TopPk($_SESSION['cabinet_db']);
        $ReturnArr['Castle'] = Statistic::Castle($_SESSION['cabinet_db']);

        return $ReturnArr;
    }

    public function CharInfo($Nick)
    {
        $ReturnArr = Statistic::PlayerInfo($Nick, $_SESSION['cabinet_db']);
        return $ReturnArr[0];
    }
    public function ClanInfo($Guild)
    {
        $ReturnArr = Statistic::GuildInfo($Guild, $_SESSION['cabinet_db']);
        return $ReturnArr;
    }

    public function ChangePass($OldPassword, $NewPassword)
    {
        if ($this->AccountOnline)
        {
            return false;
        }
        $OldPassword = App::Validate($OldPassword);
        $NewPassword = App::Validate($NewPassword);

        if (strlen($NewPassword) < 3 || strlen($NewPassword) >= 10) {
            Logs::WriteLog("Module: [ChangePassword][".date('d.m.Y H:i:s')."], Account [{$_SESSION['cabinet_login']}]. Error in length password", 'Cabinet/Modules.log');
            Messages::Add('Слишком длинный пароль');
            return false;
        }
        $Result = App::$DBs[$_SESSION['cabinet_db']]->select('memb___id')->from('MEMB_INFO')->where(array('memb__pwd'=> $OldPassword, 'memb___id' => $_SESSION['cabinet_login']))->get();
        if ($Result->num_rows())
        {
            if (App::$DBs[$_SESSION['cabinet_db']]->where('memb___id', $_SESSION['cabinet_login'])->update('MEMB_INFO', array('memb__pwd'=> $NewPassword))) {
                Logs::WriteLog("Module: [ChangePassword][".date('d.m.Y H:i:s')."], Account [{$_SESSION['cabinet_login']}]. Success change password", 'Cabinet/Modules.log');
                Messages::Add('Вы успешно сменили пароль');
            }

        }
        else {
            Logs::WriteLog("Module: [ChangePassword][".date('d.m.Y H:i:s')."], Account [{$_SESSION['cabinet_login']}]. Error incorrect password", 'Cabinet/Modules.log');
            Messages::Add('Неправильный пароль ');
        }
    }
    public function Forgot()
    {
        if (property_exists(App::$Post, 'num_db') && App::$Post->num_db > 0 && App::$Post->num_db < App::$countDB)
            $Db = App::Validate(App::$Post->num_db);
        else
            $Db = 0;

        $Login = App::Validate(App::$Post->login);
        $Email = App::Validate(App::$Post->email);
        $UsernameCheck = App::$DBs[$Db]->select('memb___id')->from('MEMB_INFO')->where('memb___id', $Login)->where('mail_addr', $Email)->count_all_results();
        //$EmailCheck = App::$DBs[$_SESSION['cabinet_db']]->select('mail_addr')->from('MEMB_INFO')->where('mail_addr', $Email)->count_all_results();

        if (empty($Login) || empty($Email)) {
            Messages::Add('Вам нужно заполнить все поля!');
        }
        elseif ($UsernameCheck <= 0) {
            Messages::Add('Неверный логин/email!');
        }
        else {
            $Password = substr(str_shuffle('01234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'), 0, 8);

            App::$DBs[$Db]
                ->where('memb___id', $Login)
                ->update('MEMB_INFO', array('memb__pwd' => $Password));

            // Письмо
            $Title = "Restore Password";
            $From =	"From: Администрация Freyamu.RU";
            $Message = "Восстановление пароля.\r\n".
                "Вы получили это письмо, поскольку был сделан запрос на восстановление вашего пароля на сайте.\r\n\r\n".
                "Ваш новый пароль: ".$Password."\r\n".
                "Приятной вам игры на нашем сервере!\r\n\r\n".
                "Пожалуйста не отвечайте на это сообщение. Сообщение отправлено роботом, который не сможет Вам ответить.\r\n\r\n";
            mail($Email, $Title, $Message, $From);

            Messages::Add('Письмо с паролем было отправлено вам на электронную почту');
        }
    }
    public function SettingsInfo()
    {
        $ReturnArr = array();
        
        return $ReturnArr;
    }
    public function GetListCharsInAccount()
    {
        $Array = App::$DBs[$_SESSION['cabinet_db']]->select()->from('AccountCharacter')->where('ID', $_SESSION['cabinet_login'])->get()->result_array();
        $chars = array();
        for ($i=1; $i <= 5; $i++) {
            $chars[] = $Array[0]['GameID'.$i];
        }
        return $chars;
    }

    public function GetAllValutes()
    {
        $Db = $_SESSION['cabinet_db'];
        $ValutesConfig = json_decode(file_get_contents("configs/DB_" . $Db . "/ValuteManager.json"),true);
        $ResultArr = array();
        $i = 0;
        foreach ($ValutesConfig as $valute)
        {
            if ($valute['Table'] == '') continue;
            $ResultArr[$i]['Name'] = $valute['Name'];
            /**
             * @var $query QueryBuilder
             */
            $query = App::$DBs[$Db]->select($valute['Column'])->from($valute['Table']);
            if ($valute['CharacterNameColumn'] != '')
            {
                $query->where($valute['CharacterNameColumn'], $_SESSION['ActivePlayer']);
            }
            else if ($valute['AccountNameColumn'])
            {
                $query->where($valute['AccountNameColumn'], $_SESSION['cabinet_login']);
            }
            $ResultArr[$i]['Count'] = $query->get()->result_array();
            $ResultArr[$i]['Count'] = $ResultArr[$i]['Count'][0][$valute['Column']];
            $i++;
        }
        return $ResultArr;
    }
    public function NeedToHide(){
        $HideInfoConfig = json_decode(file_get_contents("configs/modules/DB_" . $_SESSION['cabinet_db'] . "/HideInfo.json"),true);         
        $ReturnArr = array();
        $ReturnArr['NeedLevel'] = $HideInfoConfig['NeedLevel'];
        $ReturnArr['NeedReset'] = $HideInfoConfig['NeedReset'];
        $ReturnArr['Take']['Valutes'] = $HideInfoConfig['Take']['Valutes'];
        return $ReturnArr;
    }

    public function Hide($NickCharacter, $Time)
    {
        if ($this->AccountOnline)
        {
            return false;
        }
        if (App::$Post->selected_char = '')
            return false;
        
        $HideInfoConfig = json_decode(file_get_contents("configs/modules/DB_" . $_SESSION['cabinet_db'] . "/HideInfo.json"),true);   
        if (!$HideInfoConfig['Enable'])
            return false;

        $Character = static::GetActivePlayerInfo($NickCharacter);
        $Character = $Character[0];
        $Block = false;
        if($Character['cLevel'] < $HideInfoConfig['NeedLevel']){
            $Block = true;
            Messages::Add("Вы слишком маленький уровень.");
        }
        if($Character['Resets'] < $HideInfoConfig['NeedReset']){
            $Block = true;
            Messages::Add("У вас не хватает ресетов");
        }
        if ($Time <= 0 && !is_numeric($Time)){
            $Block = true;
            Messages::Add("У вас недостаточно денег");
        }
        
        if ($Character['HideInfoTime'] > time())
            $FinalTime = $Character['HideInfoTime'] + ($Time * 60 * 60);
        else
            $FinalTime = time() + ($Time * 60 * 60);
        
        if ($Block == false) {
            if (static::CheckFive($HideInfoConfig['Take']['Valutes'][0]*$Time, $HideInfoConfig['Take']['Valutes'][1]*$Time, $HideInfoConfig['Take']['Valutes'][2]*$Time, $HideInfoConfig['Take']['Valutes'][3]*$Time, $HideInfoConfig['Take']['Valutes'][4]*$Time)) {
                if (App::$DBs[$_SESSION['cabinet_db']]->where('Name', $Character['Name'])->update('Character', array('HideInfoTime' => $FinalTime))) {
                    static::TakeFive($HideInfoConfig['Take']['Valutes'][0]*$Time, $HideInfoConfig['Take']['Valutes'][1]*$Time, $HideInfoConfig['Take']['Valutes'][2]*$Time, $HideInfoConfig['Take']['Valutes'][3]*$Time, $HideInfoConfig['Take']['Valutes'][4]*$Time);

                    Logs::WriteLog("Module: [HideInfo][".date('d.m.Y H:i:s')."], Account [{$_SESSION['cabinet_login']}]. Success HideInfo({$Time} Hour)", 'Modules.log');
                    Messages::Add('Вы успешно закрыли информацию');
                    return true;
                }
            }
        }
        Logs::WriteLog("Module: [HideInfo][".date('d.m.Y H:i:s')."], Account [{$_SESSION['cabinet_login']}]. Fail HideInfo", 'Modules.log');
        Messages::Add('Неудачная попытка');
        return false;
    }
    /**
     * @param int $Valute {@min 0}{@max 4}
     * @param int $Count
     * @return bool
     */
    public static function Check($Valute, $Count)
    {
        if ($Valute < 0 || $Valute > 4) return false;
        if ($Count == 0) return true;

        $read = file_get_contents("configs/DB_" . $_SESSION['cabinet_db'] . "/ValuteManager.json");
        if (($ValuteManagerConfig = json_decode($read,true)) !== null)
        {
            if ($ValuteManagerConfig[$Valute]['Name'] == ''
                || $ValuteManagerConfig[$Valute]['Table'] == ''
                || $ValuteManagerConfig[$Valute]['Column'] == '') return true;

            if ($ValuteManagerConfig[$Valute]['CharacterNameColumn'] != '')
            {

                $res = App::$DBs[$_SESSION['cabinet_db']]->select(array($ValuteManagerConfig[$Valute]['CharacterNameColumn'] , $ValuteManagerConfig[$Valute]['Column']))->from($ValuteManagerConfig[$Valute]['Table'])->where($ValuteManagerConfig[$Valute]['CharacterNameColumn'],$_SESSION['ActivePlayer'])->get()->result_array();
                if ($res[0][$ValuteManagerConfig[$Valute]['Column']] >= $Count)
                {
                    return true;
                }
            }
            else if($ValuteManagerConfig[$Valute]['AccountNameColumn'] != '')
            {
                $res = App::$DBs[$_SESSION['cabinet_db']]->select(array($ValuteManagerConfig[$Valute]['AccountNameColumn'] , $ValuteManagerConfig[$Valute]['Column']))->from($ValuteManagerConfig[$Valute]['Table'])->where($ValuteManagerConfig[$Valute]['AccountNameColumn'],$_SESSION['cabinet_login'])->get()->result_array();
                if ($res[0][$ValuteManagerConfig[$Valute]['Column']] >= $Count)
                {
                    return true;
                }
            }
        }
        Messages::Add('incorect_count_valute', $ValuteManagerConfig[$Valute]['Name']);
        return false;
    }
    /**
     * Check All Valutes
     * @param $One int
     * @param $Two int
     * @param $Three int
     * @param $Four int
     * @param $Five int
     * @return bool
     */
    public static function CheckFive($One,$Two,$Three, $Four, $Five)
    {
        if ($One != 0) if(!self::Check(0,$One)) return false;
        if ($Two != 0) if(!self::Check(1,$Two)) return false;
        if ($Three != 0) if(!self::Check(2,$Three)) return false;
        if ($Four != 0) if(!self::Check(3,$Four)) return false;
        if ($Five != 0) if(!self::Check(4,$Five)) return false;
        
        return true;
    }
    /**
     * @param int $Valute {@min 0}{@max 4}
     * @param int $Count
     * @return bool
     */
    public static function Take($Valute, $Count)
    {
        if ($Valute < 0 || $Valute > 4) return false;
        if ($Count == 0) return true;

        $read = file_get_contents("configs/DB_" . 0 . "/ValuteManager.json");
        if (($ValuteManagerConfig = json_decode($read,true)) !== null)
        {
            if ($ValuteManagerConfig[$Valute]['Name'] == ''
                || $ValuteManagerConfig[$Valute]['Table'] == ''
                || $ValuteManagerConfig[$Valute]['Column'] == '') return true;

            if ($ValuteManagerConfig[$Valute]['CharacterNameColumn'] != '')
            {
                $res = App::$DBs[$_SESSION['cabinet_db']]->select(array($ValuteManagerConfig[$Valute]['CharacterNameColumn'] , $ValuteManagerConfig[$Valute]['Column']))->from($ValuteManagerConfig[$Valute]['Table'])->where($ValuteManagerConfig[$Valute]['CharacterNameColumn'],$_SESSION['ActivePlayer'])->get()->result_array();
                if ($res[0][$ValuteManagerConfig[$Valute]['Column']] >= $Count)
                {
                    if(
                    App::$DBs[$_SESSION['cabinet_db']]->set($ValuteManagerConfig[$Valute]['Column'], $ValuteManagerConfig[$Valute]['Column'] . '-' . $Count, FALSE)->where($ValuteManagerConfig[$Valute]['CharacterNameColumn'], $_SESSION['ActivePlayer'])->update($ValuteManagerConfig[$Valute]['Table'])
                    ) {
                        return true;
                    }
                }
            }
            else if($ValuteManagerConfig[$Valute]['AccountNameColumn'] != '') {
                $res = App::$DBs[$_SESSION['cabinet_db']]->select(array($ValuteManagerConfig[$Valute]['AccountNameColumn'] , $ValuteManagerConfig[$Valute]['Column']))->from($ValuteManagerConfig[$Valute]['Table'])->where($ValuteManagerConfig[$Valute]['AccountNameColumn'],$_SESSION['cabinet_login'])->get()->result_array();

                if ($res[0][$ValuteManagerConfig[$Valute]['Column']] >= $Count) {
                    if (
                    App::$DBs[$_SESSION['cabinet_db']]->set($ValuteManagerConfig[$Valute]['Column'], $ValuteManagerConfig[$Valute]['Column'] . '-' . $Count, FALSE)->where($ValuteManagerConfig[$Valute]['AccountNameColumn'], $_SESSION['cabinet_login'])->update($ValuteManagerConfig[$Valute]['Table'])
                ) {
                        return true;
                    }
                }
            }
        }
        Messages::Add('incorect_count_valute', $ValuteManagerConfig[$Valute]['Name']);
        return false;
    }

    /**
     * @param $One int
     * @param $Two int
     * @param $Three int
     * @param $Four int
     * @param $Five int
     */
    public static function TakeFive($One,$Two,$Three, $Four, $Five)
    {
        if ($One != 0) self::Take(0,$One);
        if ($Two != 0) self::Take(1,$Two);
        if ($Three != 0) self::Take(2,$Three);
        if ($Four != 0) self::Take(3,$Four);
        if ($Five != 0) self::Take(4,$Five);
    }
/**
     * @param int $Valute {@min 0}{@max 4}
     * @param int $Count
     * @return bool
     */
    public static function Reward($Valute, $Count, $Account = null)
    {
        if ($Valute < 0 || $Valute > 4) return false;
        if ($Count == 0) return true;

        $read = file_get_contents("configs/DB_" . 0 . "/ValuteManager.json");
        if (($ValuteManagerConfig = json_decode($read,true)) !== null)
        {
            if ($ValuteManagerConfig[$Valute]['Name'] == ''
                || $ValuteManagerConfig[$Valute]['Table'] == ''
                || $ValuteManagerConfig[$Valute]['Column'] == '') return false;

            if ($Account != null) {
                if ($ValuteManagerConfig[$Valute]['CharacterNameColumn'] != '') {
                    if (App::$DBs[$_SESSION['cabinet_db']]->set($ValuteManagerConfig[$Valute]['Column'], $ValuteManagerConfig[$Valute]['Column'] . '+' . $Count, FALSE)->where($ValuteManagerConfig[$Valute]['CharacterNameColumn'], $_SESSION['ActivePlayer'])->update($ValuteManagerConfig[$Valute]['Table'])) {
                        return true;
                    } else {
                        return false;
                    }
                } else if ($ValuteManagerConfig[$Valute]['AccountNameColumn'] != '') {
                    if (App::$DBs[$_SESSION['cabinet_db']]->set($ValuteManagerConfig[$Valute]['Column'], $ValuteManagerConfig[$Valute]['Column'] . '+' . $Count, FALSE)->where($ValuteManagerConfig[$Valute]['AccountNameColumn'], $Account)->update($ValuteManagerConfig[$Valute]['Table'])) {
                        return true;
                    } else {
                        return false;
                    }
                } else {
                    return false;
                }
            } else {
                if ($ValuteManagerConfig[$Valute]['CharacterNameColumn'] != '') {
                     if (App::$DBs[$_SESSION['cabinet_db']]->set($ValuteManagerConfig[$Valute]['Column'], $ValuteManagerConfig[$Valute]['Column'] . '+' . $Count, FALSE)->where($ValuteManagerConfig[$Valute]['CharacterNameColumn'], $_SESSION['ActivePlayer'])->update($ValuteManagerConfig[$Valute]['Table'])) {
                        return true;
                    } else {
                        return false;
                    }
                } else if ($ValuteManagerConfig[$Valute]['AccountNameColumn'] != '') {
                    if (App::$DBs[$_SESSION['cabinet_db']]->set($ValuteManagerConfig[$Valute]['Column'], $ValuteManagerConfig[$Valute]['Column'] . '+' . $Count, FALSE)->where($ValuteManagerConfig[$Valute]['AccountNameColumn'], $_SESSION['cabinet_login'])->update($ValuteManagerConfig[$Valute]['Table'])) {
                        return true;
                    } else {
                        return false;
                    }
                } else {
                    return false;
                }
            }
        }
        return false;
    }

    /**
     * @param int $One
     * @param int $Two
     * @param int $Three
     * @param int $Four
     * @param int $Five
     */
    public static function RewardFive($One,$Two,$Three, $Four, $Five)
    {
        if ($One != 0) self::Reward(0,$One);
        if ($Two != 0) self::Reward(1,$Two);
        if ($Three != 0) self::Reward(2,$Three);
        if ($Four != 0) self::Reward(3,$Four);
        if ($Five != 0) self::Reward(4,$Five);
    }

    public static function GetActivePlayerInfo($Nick = null, $Account = null)
    {
        
        $res = 0;
        if ($Nick == null && $Account == null)
        {
            $res = App::$DBs[$_SESSION['cabinet_db']]
                ->select(array('Name', 'cLevel', App::$DBs[$_SESSION['cabinet_db']]->column_names['Resets'], App::$DBs[$_SESSION['cabinet_db']]->column_names['GrandResets'], 'LevelUpPoint', 'Strength', 'Dexterity', 'Vitality', 'Energy', 'Leadership', 'HideInfoTime', 'Inventory'))
                ->from('Character')
                ->where('AccountID = ', $_SESSION['cabinet_login'])
                ->order_by(App::$DBs[$_SESSION['cabinet_db']]->column_names['GrandResets'],'DESC')
                ->order_by(App::$DBs[$_SESSION['cabinet_db']]->column_names['Resets'],'DESC')
                ->order_by('cLevel','DESC')
                ->get();
        }
        else if ($Nick != null)
        {
            $res = App::$DBs[$_SESSION['cabinet_db']]
                ->select(array('Name', 'cLevel', App::$DBs[$_SESSION['cabinet_db']]->column_names['Resets'], App::$DBs[$_SESSION['cabinet_db']]->column_names['GrandResets'], 'LevelUpPoint', 'Strength', 'Dexterity', 'Vitality', 'Energy', 'Leadership', 'HideInfoTime', 'Inventory'))
                ->from('Character')
                ->where('Name = ', $Nick)
                ->where('AccountID = ', $_SESSION['cabinet_login'])
                ->order_by(App::$DBs[$_SESSION['cabinet_db']]->column_names['GrandResets'],'DESC')
                ->order_by(App::$DBs[$_SESSION['cabinet_db']]->column_names['Resets'],'DESC')
                ->order_by('cLevel','DESC')
                ->get();
            
        }
        else if ($Account != null)
        {
            $res = App::$DBs[$_SESSION['cabinet_db']]
                ->select(array('Name', 'cLevel', App::$DBs[$_SESSION['cabinet_db']]->column_names['Resets'], App::$DBs[$_SESSION['cabinet_db']]->column_names['GrandResets'], 'LevelUpPoint', 'Strength', 'Dexterity', 'Vitality', 'Energy', 'Leadership', 'HideInfoTime', 'Inventory'))
                ->from('Character')
                ->where('AccountID = ', $Account)
                ->order_by(App::$DBs[$_SESSION['cabinet_db']]->column_names['GrandResets'],'DESC')
                ->order_by(App::$DBs[$_SESSION['cabinet_db']]->column_names['Resets'],'DESC')
                ->order_by('cLevel','DESC')
                ->get();
        }
        else
        {
            return false;
        }
        
        $ResultArr = $res->result_array();

        //Replace to standart index
        if (App::$DBs[$_SESSION['cabinet_db']]->column_names['Resets'] != 'Resets')
            $ResultArr[0]['Resets'] = $ResultArr[0][App::$DBs[$_SESSION['cabinet_db']]->column_names['Resets']];
        if (App::$DBs[$_SESSION['cabinet_db']]->column_names['GrandResets'] != 'GrandResets')
            $ResultArr[0]['GrandResets'] = $ResultArr[0][App::$DBs[$_SESSION['cabinet_db']]->column_names['GrandResets']];
        
        if ($res->num_rows())
        {
            $ResultArr['Valutes'] = static::GetAllValutes($_SESSION['cabinet_db']);
            $_SESSION['active_char'] = $ResultArr[0]['Name'];
            $_SESSION['ActivePlayer'] = $ResultArr[0]['Name'];
           
            return $ResultArr;
        }
        else{
            if ($Account == null) {
                Messages::Add('character_not_found');
            }
            return false;
        }
    }
    public function BuyPrem($Type, $Count)
    {

         if ($this->AccountOnline)
        {
            return false;
        }

        if ($Type < 1 && $Type > 3)
            return false;
        

        //$Character = static::GetActivePlayerInfo($NickCharacter);
        //$Character = $Character[0];
        $Block = false;

        if ($Count <= 0 && !is_numeric($Count)){
            $Block = true;
            Messages::Add("У вас недостаточно Денег");
        }
        if ($Count != 7 && $Count != 14 && $Count != 30){
            $Block = true;
            Messages::Add("Купить можно только 7/14/30 дней");
        }
            $AccountExpireDate = App::$DBs[$_SESSION['cabinet_db']]
                        ->select('AccountExpireDate, AccountLevel')->from('MEMB_INFO')->where('memb___id', $_SESSION['cabinet_login'])->get()->result_array();
            $AccountLevel = $AccountExpireDate[0]['AccountLevel'];
            $AccountExpireDate = strtotime($AccountExpireDate[0]['AccountExpireDate']);

        if ($AccountLevel >= $Type){
            $Block = true;
            Messages::Add("Покупка невозможна, у вас VIP на уровень выше.");
        }  

        if ($AccountExpireDate > time())
            $FinalTime = $AccountExpireDate + ($Count * 60 * 60 * 24);
        else
            $FinalTime = time() + ($Count * 60 * 60 * 24);
         /*  1 Lvl 7 day = 350 RUB
1 Lvl 14 day = 550 RUB
1 Lvl 30  day = 850 RUB

2 Lvl 7 day = 500 RUB
2 Lvl 14 day = 900 RUB
2 Lvl 30  day = 1350 RUB

3 Lvl 7 day = 800 RUB
3 Lvl 14 day = 1350 RUB
3 Lvl 30  day = 2000 RUB*/
        $Price = 0;
        if ($Type == 1) {
            if ($Count == 7) {
                $Price = 350;
            } else if ($Count == 14) {
                $Price = 550;
            } else if ($Count == 30) {
                $Price = 850;
            } else {
                Messages::Add("Купить можно только 7/14/30 дней");
            }
        } else if ($Type == 2) {
            if ($Count == 7) {
                $Price = 500;
            } else if ($Count == 14) {
                $Price = 900;
            } else if ($Count == 30) {
                $Price = 1350;
            } else {
                Messages::Add("Купить можно только 7/14/30 дней");
            }
        } else if ($Type == 3) {
            if ($Count == 7) {
                $Price = 800;
            } else if ($Count == 14) {
                $Price = 1350;
            } else if ($Count == 30) {
                $Price = 2000;
            } else {
                Messages::Add("Купить можно только 7/14/30 дней");
            }
        } else {
            return false;
        }

        if ($Block == false) {
            ///!!!!!!!!!!!!!!!!!!!!!!
            $WCoinC = App::$DBs[$_SESSION['cabinet_db']]->select('WCoinC')->from('CashShopData')->where('AccountID', $_SESSION['cabinet_login'])->get()->result_array();
            $WCoinC = $WCoinC[0]['WCoinC'];

            if ($WCoinC >= $Price) {
                if (App::$DBs[$_SESSION['cabinet_db']]->where('memb___id', $_SESSION['cabinet_login'])->set('AccountLevel', $Type)->set('AccountExpireDate', date("Y-m-d H:i:s", $FinalTime))->update('MEMB_INFO')) {
                    App::$DBs[$_SESSION['cabinet_db']]->set('WCoinC', ($WCoinC - $Price) )->where('AccountID', $_SESSION['cabinet_login'])->update('CashShopData');
                    Logs::WriteLog("Module: [BuyPrem][".date('d.m.Y H:i:s')."], Account [{$_SESSION['cabinet_login']}]. Success BuyPrem({$Count} Days)", 'Modules.log');
                    Messages::Add('Вы успешно приобрели VIP');
                    return true;
                }
            }
        }
        Logs::WriteLog("Module: [BuyPrem][".date('d.m.Y H:i:s')."], Account [{$_SESSION['cabinet_login']}]. Fail BuyPrem", 'Modules.log');
        Messages::Add('Неудачная попытка покупки VIP');
        return false;
    }

     public function ParseTxtMMOTop($url, $Account)
    {
        $handle = fopen($url, "r");
        $count = 0;
        while ($userinfo = fscanf($handle, "%s\t%s\t%s\t%s\t%s\t%s")) {
            //list ($id, $date, $time, $ip, $login, $type) = $userinfo;
            if ($userinfo[4] == $Account) {
                $List[] = $userinfo;
                $count++;
            }
        }
        fclose($handle);
        return $List;
    }

    public function GetListMMOTop()
    {
        $AccountID = $_SESSION['cabinet_login'];
        if (!$this->VoteConfig['MMOTop']['Enable']) {
            return false;
        }
        $ListTxt = $this->ParseTxtMMOTop($this->VoteConfig['MMOTop']['Link'] , $AccountID);

        $ListSql = App::$DBs[$_SESSION['cabinet_db']]->select('*')->from('mmotop_vote')->where('vote_acc', $AccountID)->get()->result_array();

        if (!empty($ListSql)) {
            for ($i=0; $i < count($ListSql); $i++) {
                foreach ($ListTxt as $key => $value) {
                    if ($value[0] == $ListSql[$i]['vote_id']) {
                        unset($ListTxt[$key]);
                        sort($ListTxt);
                    }
                }
            }
        }
        for ($i=0; $i < count($ListTxt); $i++) {
            if ($ListTxt[$i][5] == 1) {
                $ListTxt[$i]['Valutes']['Count'] = $this->VoteConfig['MMOTop']['Reward']['Normal']['Valutes'];
                $ListTxt[$i]['Valutes']['Type'] = 'Normal';
            }
            else if ($ListTxt[$i][5] == 2) {
                $ListTxt[$i]['Valutes']['Count'] = $this->VoteConfig['MMOTop']['Reward']['SMS']['Valutes'];
                $ListTxt[$i]['Valutes']['Type'] = 'SMS';
            }
        }
        return $ListTxt;
    }

    public function GetRewardMMOTop($id)
    {
        if ($this->AccountOnline)
        {
            return false;
        }
        if (!$this->VoteConfig['MMOTop']['Enable'])
            return false;

        $AccountID = $_SESSION['cabinet_login'];

        $ListTxt = $this->ParseTxtMMOTop($this->VoteConfig['MMOTop']['Link'] , $AccountID);

        foreach ($ListTxt as $key => $value) {
            if ($id == $value[0]) {
                if (! App::$DBs[$_SESSION['cabinet_db']]->from('mmotop_vote')->where(array('vote_acc' => $AccountID, 'vote_id' => $id, 'vote_time' => strtotime($value[1]. " " .$value[2])))->count_all_results() ) {

                    if (App::$DBs[$_SESSION['cabinet_db']]
                        ->insert('mmotop_vote', array('vote_id'=>$id, 'vote_time'=> strtotime($value[1]. " " .$value[2] ), 'vote_ip' => $value[3], 'vote_acc'=> $value[4], 'vote_type' =>  $value[5] ))) {

                        if ($value[5] == 1) {
                            static::RewardFive($this->VoteConfig['MMOTop']['Reward']['Normal']['Valutes'][0],$this->VoteConfig['MMOTop']['Reward']['Normal']['Valutes'][1],$this->VoteConfig['MMOTop']['Reward']['Normal']['Valutes'][2],$this->VoteConfig['MMOTop']['Reward']['Normal']['Valutes'][3],$this->VoteConfig['MMOTop']['Reward']['Normal']['Valutes'][4]);
                            Messages::Add('success_vote_mmotop_normal');
                            Logs::WriteLog("Account: [{$AccountID}] Success get reward to vote. Top: [MMOTop], Type: [Normal], ID: [{$value[0]}]","Modules.log");
                            return true;
                        }
                        else if ($value[5] == 2) {
                            static::RewardFive($this->VoteConfig['MMOTop']['Reward']['SMS']['Valutes'][0],$this->VoteConfig['MMOTop']['Reward']['SMS']['Valutes'][1],$this->VoteConfig['MMOTop']['Reward']['SMS']['Valutes'][2],$this->VoteConfig['MMOTop']['Reward']['SMS']['Valutes'][3],$this->VoteConfig['MMOTop']['Reward']['SMS']['Valutes'][4]);
                            Messages::Add('success_vote_mmotop_sms');
                            Logs::WriteLog("Account: [{$AccountID}] Success get reward to vote. Top: [MMOTop], Type: [SMS], ID: [{$value[0]}]","Modules.log");
                            return true;
                        }
                    }
                }
            }
        }
        Messages::Add('fail_vote_mmotop');
        Logs::WriteLog("Account: [{$AccountID}] Fail to get vote reward. Top: [MMOTop], ID: [{$value[0]}]","Modules.log");
        return false;
    }

    public function ParseTxtQTop($url, $Account)
    {
        $handle = fopen($url, "r");
        $count = 0;
        $List = array();
        while (!feof($handle)) {
            # Считываем построчно данные из блокнота
            $str = fgets($handle, 1024);
            # Разбиваем строку $str на отдельные элементы, используя в качестве разделителя ||
            list($vote['id'], $vote['date'], $vote['time'], $vote['ip'], $vote['user_name'], $vote['type']) = explode('||', $str);

            $vote['type'] = trim($vote['type']);

            if ($vote['user_name'] == $Account) {
                $List[] = $vote;
                $count++;
            }
        }
        fclose($handle);
        return $List;

    }
    public function GetListQTop()
    {
        $AccountID = $_SESSION['cabinet_login'];
        /*if (!file_exists($this->VoteConfig['QTop']['Link'])) {
            return false;
        }*/
        if (!$this->VoteConfig['QTop']['Enable']) {
            return false;
        }
        $ListTxt = $this->ParseTxtQTop($this->VoteConfig['QTop']['Link'] , $AccountID);

        $ListSql = App::$DBs[$_SESSION['cabinet_db']]->select('*')->from('qtop_vote')->where('v_username', $AccountID)->get()->result_array();

        if (!empty($ListSql)) {
            for ($i=0; $i < count($ListSql); $i++) {
                foreach ($ListTxt as $key => $value) {
                    if ($value['id'] == $ListSql[$i]['v_id']) {
                        unset($ListTxt[$key]);
                        sort($ListTxt);
                    }
                }
            }
        }
        for ($i=0; $i < count($ListTxt); $i++) {
            if ($ListTxt[$i]['type'] == 1) {
                $ListTxt[$i]['Valutes'] = $this->VoteConfig['QTop']['Reward']['Normal']['Valutes'];
                $ListTxt[$i]['Valutes']['Type'] = 'Normal';
            }
            else if ($ListTxt[$i]['type'] == 2) {
                $ListTxt[$i]['Valutes'] = $this->VoteConfig['QTop']['Reward']['SMS']['Valutes'];
                $ListTxt[$i]['Valutes']['Type'] = 'SMS';
            }
        }
        return $ListTxt;
    }

    public function GetRewardQTop($id)
    {
        if ($this->AccountOnline)
        {
            return false;
        }
        if (!$this->VoteConfig['QTop']['Enable'])
            return false;

        $AccountID = $_SESSION['cabinet_login'];

        /*if (!file_exists($this->VoteConfig['QTop']['Link'])) {
            return false;
        }*/
        $ListTxt = $this->ParseTxtQTop($this->VoteConfig['QTop']['Link'] , $AccountID);

        foreach ($ListTxt as $key => $value) {
            if ($id == $value['id']) {
                if (! App::$DBs[$_SESSION['cabinet_db']]->from('qtop_vote')->where(array('v_username' => $AccountID, 'v_id' => $id, 'v_time' => strtotime($value['date']. " " .$value['time'])))->count_all_results() ) {

                    if (App::$DBs[$_SESSION['cabinet_db']]
                        ->insert('qtop_vote', array('v_id'=>$id, 'v_time'=> strtotime($value['date']. " " .$value['time'] ), 'v_ip' => $value['ip'], 'v_username'=> $value['user_name'], 'v_type' =>  $value['type'] ))) {

                        if ($value['type'] == 1) {
                            static::RewardFive($this->VoteConfig['QTop']['Reward']['Normal']['Valutes'][0],$this->VoteConfig['QTop']['Reward']['Normal']['Valutes'][1],$this->VoteConfig['QTop']['Reward']['Normal']['Valutes'][2],$this->VoteConfig['QTop']['Reward']['Normal']['Valutes'][3],$this->VoteConfig['QTop']['Reward']['Normal']['Valutes'][4]);
                            Messages::Add('success_vote_qtop_normal');
                            Logs::WriteLog("Account: [{$AccountID}] Success get reward to vote. Top: [QTop], Type: [Normal], ID: [{$value['id']}]","Modules.log");
                            return true;
                        }
                        else if ($value['type'] == 2) {
                            static::RewardFive($this->VoteConfig['QTop']['Reward']['SMS']['Valutes'][0],$this->VoteConfig['QTop']['Reward']['SMS']['Valutes'][1],$this->VoteConfig['QTop']['Reward']['SMS']['Valutes'][2],$this->VoteConfig['QTop']['Reward']['SMS']['Valutes'][3],$this->VoteConfig['QTop']['Reward']['SMS']['Valutes'][4]);
                            Messages::Add('success_vote_qtop_sms');
                            Logs::WriteLog("Account: [{$AccountID}] Success get reward to vote. Top: [QTop], Type: [SMS], ID: [{$value['id']}]","Modules.log");
                            return true;
                        }
                    }
                }
            }

        }
        Messages::Add('fail_vote_qtop');
        Logs::WriteLog("Account: [{$AccountID}] Fail to get vote reward. Top: [QTop], ID: [{$value['id']}]","Modules.log");
        return false;
    }
    
     public function NeedToChangeClass(){
        if($this->AccountOnline)
        {
            return;
        }
        $ChangeClassConfig = json_decode(file_get_contents("configs/modules/DB_" . $_SESSION['cabinet_db'] . "/ChangeClass.json"),true);     
        if (!$ChangeClassConfig['Enable'])
            return;

        $ReturnArr = array();
        $ReturnArr['NeedLevel'] = $ChangeClassConfig['NeedLevel'];
        $ReturnArr['NeedReset'] = $ChangeClassConfig['NeedReset'];
        $ReturnArr['NeedEmptyInv'] = $ChangeClassConfig['NeedEmptyInv'];
        $ReturnArr['Classes'] = $ChangeClassConfig['Classes'];
        
        $ReturnArr['Take']['Valutes'] = $ChangeClassConfig['Take']['Valutes'];

        return $ReturnArr;

    }
    public function ChangeClass($NickCharacter, $Class)
    {
        if ($this->AccountOnline)
        {
            return;
        }

        $ChangeClassConfig = json_decode(file_get_contents("configs/modules/DB_" . $_SESSION['cabinet_db'] . "/ChangeClass.json"),true);    
        if (!$ChangeClassConfig['Enable'])
            return;

        $Character = static::GetActivePlayerInfo($NickCharacter);
        $Character = $Character[0];
        $Block = false;
        if($Character['cLevel'] < $ChangeClassConfig['NeedLevel']){
            $Block = true;
            Messages::Add("block_change_class_need_level");
        }
        if($Character['Resets'] < $ChangeClassConfig['NeedReset']){
            $Block = true;
            Messages::Add("block_change_class_need_reset");
        }
        if($ChangeClassConfig['NeedEmptyInv'] && !Character::EmptyInventory($Character)){
            $Block = true;
            Messages::Add("block_change_class_empty_inv");
        }else if ($Class == 'DW' && !$ChangeClassConfig['Classes']['DW'])
        {
            $Class = 0;
            $Block = true;
            Messages::Add("block_change_class_no_correct_class");
        }else if ($Class == 'DK' && !$ChangeClassConfig['Classes']['DK'])
        {
            $Class = 16;
            $Block = true;
            Messages::Add("block_change_class_no_correct_class");
        }else if ($Class == 'ELF' && !$ChangeClassConfig['Classes']['ELF'])
        {
            $Class = 32;
            $Block = true;
            Messages::Add("block_change_class_no_correct_class");
        }else if ($Class == 'MG' && !$ChangeClassConfig['Classes']['MG'])
        {
            $Class = 48;
            $Block = true;
            Messages::Add("block_change_class_no_correct_class");
        }else if ($Class == 'SUM' && !$ChangeClassConfig['Classes']['SUM'])
        {
            $Class = 80;
            $Block = true;
            Messages::Add("block_change_class_no_correct_class");
        }else if ($Class == 'DL' && !$ChangeClassConfig['Classes']['DL'])
        {
            $Class = 64;
            $Block = true;
            Messages::Add("block_change_class_no_correct_class");
        }else if ($Class == 'RF' && !$ChangeClassConfig['Classes']['RF'])
        {
            $Class = 96;
            $Block = true;
            Messages::Add("block_change_class_no_correct_class");
        }

        if ($Class == 'DW') {$Class = 0;}
        else if ($Class == 'DK') {$Class = 16;}
        else if ($Class == 'ELF') {$Class = 32;}
        else if ($Class == 'MG') {$Class = 48;}
        else if ($Class == 'SUM') {$Class = 80;}
        else if ($Class == 'DL') {$Class = 64;}
        else if ($Class == 'RF') {$Class = 96;}


        if ($Block == false) {
            if (static::CheckFive($ChangeClassConfig['Take']['Valutes'][0], $ChangeClassConfig['Take']['Valutes'][1], $ChangeClassConfig['Take']['Valutes'][2], $ChangeClassConfig['Take']['Valutes'][3], $ChangeClassConfig['Take']['Valutes'][4])) {

                if (
                    App::$DBs[$_SESSION['cabinet_db']]->where('Name', $Character['Name'])->set('MagicList', 'NULL', false)->set('Quest', 'NULL', false)->set('Class',$Class)->update('Character')// &&

                    //App::$DBs[$_SESSION['cabinet_db']]->where('CHAR_NAME', $Character['Name'])->set('MASTER_LEVEL','0')->set('ML_EXP','0')->set('ML_NEXTEXP','0')->set('ML_POINT','0')->update('T_SkillTree_Info')
                    ) {
                    static::TakeFive($ChangeClassConfig['Take']['Valutes'][0], $ChangeClassConfig['Take']['Valutes'][1], $ChangeClassConfig['Take']['Valutes'][2], $ChangeClassConfig['Take']['Valutes'][3], $ChangeClassConfig['Take']['Valutes'][4]);

                    Logs::WriteLog("Module: [ChangeClass][".date('d.m.Y H:i:s')."], Account [{$_SESSION['cabinet_login']}]. Success change class({$Class})", 'Modules.log');
                    Messages::Add('Класс успешно сменён');
                    return true;
                }
            }
        }
        Logs::WriteLog("Module: [ChangeClass][".date('d.m.Y H:i:s')."], Account [{$_SESSION['cabinet_login']}]. Fail change class", 'Modules.log');
        Messages::Add('Ошибка смены класса');
        return false;
    }

}