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

    public static function IssetAccount($Character = null, $Db = 0)
    {
        if (App::$DBs[$Db]
            ->select('AccountID')
            ->from('Character')
            ->where('Name',$Character)
            ->count_all_results()) {
            return true;
        } else {
            return false;
        }
    }

    public static 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->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();
                            
            if (App::$Configs->customs['madmu'])
                $RegisterArr['sno__numb'] = 1;
            else
                $RegisterArr['sno_numb'] = 1;

            if ( App::$DBs[$Db]->insert('MEMB_INFO', $RegisterArr)) {

                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);
                Logs::WriteLog("Account [{$login}] Register Success Referrer -- {$referer} IP: [{$_SERVER['REMOTE_ADDR']}] DB: [{$Db}]", 'User.log');
            } else {
                Logs::WriteLog("Account [{$login}] Register Fail Referrer -- {$referer} IP: [{$_SERVER['REMOTE_ADDR']}] DB: [{$Db}]", 'User.log');
                Messages::Add('register_fail');
            }
        }
    }

    public static 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['login'] = $login;
            $_SESSION['user_db'] = $Db;
            $_SESSION['in_login'] = true;
            Logs::WriteLog("Account [{$login}] Success Login IP: [{$_SERVER['REMOTE_ADDR']}] DB: [{$Db}]", 'User.log');
            return true;
        }
        Logs::WriteLog("Account [{$login}] Login Fail IP: [{$_SERVER['REMOTE_ADDR']}] DB: [{$Db}]", 'User.log');
        Messages::Add('login_pass_incorect');        
        return false;

    }
    public static function Logout()
    {
        unset($_SESSION['login']);
        unset($_SESSION['user_db']);
        unset($_SESSION['in_login']);

        Logs::WriteLog("Account [{$_SESSION['login']}] Logout IP: [{$_SERVER['REMOTE_ADDR']}] DB: [{$Db}]", 'User.log');
        session_unset();
        session_destroy();
        setcookie(session_name(),'');
    }
    public static function isLogin()
    {
        if (isset($_SESSION['login']) && $_SESSION['login'] != "")
            return true;
        else
            return false;
    }
    public static function GetUserPanelInfo()
    {
        $Select = array();
        $Select[] = 'mail_addr';
        $Select[] = 'rdate';
       
        if (App::$Configs->user['NeedName'])
            $Select[] = 'memb_name';
        
        $res = App::$DBs[$_SESSION['user_db']]
            ->select($Select)
            ->where('memb___id',$_SESSION['login'])
            ->from('MEMB_INFO')
            ->get();

        if ($res->num_rows())
        {
            return $res->result_array();
        }
        else
        {
            return false;
        }


    }
    public static function GetListPlayerToAcc($Account = null)
    {
        if ($Account == null)
        {
            $Account = $_SESSION['login'];
        }
        $res = App::$DBs[$_SESSION['user_db']]
            ->select('Name, AccountID')
            ->from('Character')
            ->where('AccountID', $Account)
            ->get();
        if ($res->num_rows())
        {
            return $res->result_array();
        }
        else
        {
            return false;
        }
    }
    public static function ExistsEmail($Db = 0, $email = "")
    {
        $email = App::Validate($email);
        if (strlen($email) > 3 && strlen($email) <= 30) {
            if (!App::$DBs[$Db]->select('mail_addr')->where('mail_addr', $email)->from('MEMB_INFO')->get()->num_rows() )
                return 1;
        }
        return 0;
    }
    public static function ExistsLogin($Db = 0, $login = "")
    {
        $login = App::Validate($login);
        if (strlen($login) > 3 && strlen($login) <= 10) {
            if (!App::$DBs[$Db]->select('memb___id')->where('memb___id', $login)->from('MEMB_INFO')->get()->num_rows() )
                return 1;
        }
        return 0;
    }
    public static function AccountOnline($Acc = null, $Db = null)
    {
        if ($Acc != null) {
            $Acc = App::Validate($Acc);
            if ($Acc != '') {
                if ($Db != null) {
                    if (App::$DBs[$Db]
                        ->select('memb___id')
                        ->from('MEMB_STAT')
                        ->where('ConnectStat', 1)
                        ->where('memb___id', $Acc)
                        ->count_all_results()
                    ) {
                        return true;
                    }
                }else {
                    if (App::$DBs[$_SESSION['user_db']]
                        ->select('memb___id')
                        ->from('MEMB_STAT')
                        ->where('ConnectStat', 1)
                        ->where('memb___id', $Acc)
                        ->count_all_results()
                    ) {
                        return true;
                    }
                }
            }
        }
        else if (isset($_SESSION['login'])) {
            if (App::$DBs[$_SESSION['user_db']]
                ->select('memb___id')
                ->from('MEMB_STAT')
                ->where('ConnectStat',1)
                ->where('memb___id', $_SESSION['login'])
                ->count_all_results()
            )
            {
                return true;
            }
        }
        return false;
    }
    public static function RestorePassword($Db)
    {
        $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)->count_all_results();
        $EmailCheck = App::$DBs[$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!');
        }
        elseif ($EmailCheck <= 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: EvoMU.ru@gmail.com";
            $Message = "Восстановление пароля на сервере EvoMU.ru\r\n".
                "Вы получили это письмо, поскольку был сделан запрос на восстановление вашего пароля на сайте.\r\n\r\n".
                "Ваш новый пароль: ".$Password."\r\n".
                "Приятной вам игры на нашем сервере!\r\n\r\n".
                "Пожалуйста не отвечайте на это сообщение. Сообщение отправлено роботом, который не сможет Вам ответить.\r\n\r\n".
                "С уважением, EvoMU.ru";
            mail($Email, $Title, $Message, $From);

            Messages::Add('Письмо с паролем было отправлено вам на электронную почту');
        }
    }
}