<?php

class Statistic
{
    public static function TopPlayers($Class = null, $Db)
    {
        if($Db === null)
            $Db = 0;

        $WhereClassArr = null;
        if ($Class == "dw") {
            $WhereClassArr = array(0,1,2,3);
        } elseif ($Class == "dk") {
            $WhereClassArr = array(16,17,18,19);
        } elseif ($Class == "elf") {
            $WhereClassArr = array(32,33,34,35);
        } elseif ($Class == "sum") {
            $WhereClassArr = array(80,81,82,83);
        } elseif ($Class == "mg") {
            $WhereClassArr = array(48,49,50);
        } elseif ($Class == "dl") {
            $WhereClassArr = array(64,65,66);
        } elseif ($Class == "rf") {
            $WhereClassArr = array(96,97,98);
        }

        //---------------
        $Res = App::$DBs[$Db]
            ->select(array('Name', 'Class', 'cLevel', App::$DBs[$Db]->column_names['Resets'],  'Strength', 'Dexterity', 'Vitality', 'Energy', 'Leadership', 'AccountID', App::$DBs[$Db]->column_names['GrandResets'], 'HideInfoTime', 'AccountCharacter.GameIDC', 'MEMB_STAT.Connectstat', 'MEMB_STAT.ConnectTM', 'MEMB_STAT.DisConnectTM', 'MEMB_INFO.AccountExpireDate', 'MEMB_INFO.AccountLevel'))
            ->from('Character')->where('CtlCode != ', 1)->where('CtlCode != ', 17)
            ->where_in('Class', $WhereClassArr)
            ->where('MEMB_STAT.ConnectTM > ', date("Y-m-d 00:00:00", strtotime("-3 days")) )
            ->order_by(App::$DBs[$Db]->column_names['GrandResets'], 'DESC')->order_by(App::$DBs[$Db]->column_names['Resets'], 'DESC')->order_by('cLevel', 'DESC')->order_by('Name', 'ASC')
            ->join('MEMB_STAT', 'MEMB_STAT.memb___id = Character.AccountID COLLATE DATABASE_DEFAULT', 'left', false)
            ->join('MEMB_INFO', 'MEMB_INFO.memb___id = Character.AccountID COLLATE DATABASE_DEFAULT AND MEMB_INFO.AccountExpireDate > GETDATE()', 'left', false)
            ->join('AccountCharacter', 'AccountCharacter.ID = Character.AccountID COLLATE DATABASE_DEFAULT AND AccountCharacter.GameIDC != \'\'', 'left', false)
            ->limit(20)->get();

          $ResultArr = $Res->result_array();
     
        for ($i = 0; $i < $Res->num_rows(); $i++) {
            if ($ResultArr[$i]['Connectstat'] == 1 && $ResultArr[$i]['GameIDC'] != '')
                $ResultArr[$i]['status'] = 1;
            else
                $ResultArr[$i]['status'] = 0;


            if ($ResultArr[$i]['HideInfoTime'] > time())
                $ResultArr[$i]['Hide'] = 1;
            else
                $ResultArr[$i]['Hide'] = 0;


            $ResultArr[$i]['Guild'] = App::$DBs[$Db]->select('G_Name')->from('GuildMember')->where('Name',$ResultArr[$i]['Name'])->get()->result_array();
            $ResultArr[$i]['Guild'] = $ResultArr[$i]['Guild'][0]['G_Name'];
            $ClassID = $ResultArr[$i]['Class'];
            $ResultArr[$i]['Class'] = Character::GetClassName($ClassID);

            $ResultArr[$i]['Class2'] = Character::GetClassNameShort($ClassID);

            if (App::$DBs[$Db]->column_names['Resets'] != 'Resets')
                $ResultArr[$i]['Resets'] = $ResultArr[$i][App::$DBs[$Db]->column_names['Resets']];
            if (App::$DBs[$Db]->column_names['GrandResets'] != 'GrandResets')
                $ResultArr[$i]['GrandResets'] = $ResultArr[$i][App::$DBs[$Db]->column_names['GrandResets']];
        }

        return $ResultArr;
    }

    public static function TopGuilds($Db)
    {
        $topguilds = App::$DBs[$Db]
            ->select('Guild.G_Name, G_Score, G_Mark, G_Master, G_Union, Number, COUNT(GuildMember.Name) AS CountMember')
            //->limit(10)
            ->from('Guild')
            ->join('GuildMember','GuildMember.G_Name = Guild.G_Name')
            ->group_by('Guild.G_Name, G_Score, G_Mark, G_Master, G_Union, Number')
            ->order_by('CountMember', 'DESC')
            ->limit(50)
            ->get()->result_array();
        for ($i = 0; $i < count($topguilds); $i++)
        {
            $topguilds[$i]['G_Mark'] = Guild::Logo($topguilds[$i]['G_Mark'], $topguilds[$i]['G_Name'], 24);
        }
        return $topguilds;
    }

    public static function TopPk($Db)
    {
        $TopPk = App::$DBs[$Db]
            ->select(array('Name','Class', 'cLevel', App::$DBs[$Db]->column_names['Resets'], App::$DBs[$Db]->column_names['GrandResets'], 'PkLevel', 'PkCount'))
            ->where('PkLevel >', 3)
            ->order_by('PkCount','DESC')
            ->limit(50)
            ->from('Character')
            ->get()->result_array();
        for ($i = 0; $i < count($TopPk); $i++) {
            $TopPk[$i]['Class'] = Character::GetClassName($TopPk[$i]['Class']);
            if (App::$DBs[$Db]->column_names['Resets'] != 'Resets')
                $TopPk[$i]['Resets'] = $TopPk[$i][App::$DBs[$Db]->column_names['Resets']];
            if (App::$DBs[$Db]->column_names['GrandResets'] != 'GrandResets')
                $TopPk[$i]['GrandResets'] = $TopPk[$i][App::$DBs[$Db]->column_names['GrandResets']];
        }

        $ReturnArr = $TopPk;
        return $ReturnArr;
    }
    public static function Castle($Db)
    {
        $castle = App::$DBs[$Db]
            ->select('CONVERT(CHAR(19), SIEGE_START_DATE, 120) AS StartDate,CONVERT(CHAR(19), SIEGE_END_DATE, 120) AS EndDate,OWNER_GUILD,MONEY,TAX_RATE_CHAOS,TAX_RATE_STORE,TAX_HUNT_ZONE, Guild.G_Master, Guild.G_Mark')
            ->join('Guild','Guild.G_Name = MuCastle_DATA.OWNER_GUILD')
            ->from('MuCastle_DATA')->get()->result_array();
        $castle = $castle[0];

        $start_date	= $castle['StartDate'];
        $end_date 	= $castle['EndDate'];
        $ownerg		= $castle['OWNER_GUILD'];
        $money 		= $castle['MONEY'];
        $chaos_tax 	= $castle['TAX_RATE_CHAOS'];
        $store_tax 	= $castle['TAX_RATE_STORE'];
        $zone_tax 	= $castle['TAX_HUNT_ZONE'];

         $owner		= $castle['G_Master'];

        $mark		= Guild::Logo($castle['G_Mark'],$ownerg,48);

        $cs_start 		= date("d.m.Y",strtotime($start_date));
        $cs_end 		=date("d.m.Y",strtotime($end_date));
        $Current_Time = time();
        if		((strtotime($start_date)+172800)	> $Current_Time)	{ 	$cs_period = "Register Period";	}	/* 0 00:00 - 0 23:59 */
        elseif	((strtotime($start_date)+432000)	> $Current_Time)	{ 	$cs_period = "Register Mark Of The Lord";	}	/* 1 00:00 - 4 23:59 */
        elseif	((strtotime($start_date)+500400)	> $Current_Time)	{ 	$cs_period = "Castle Attack Guild Notification";	}	/* 5 00:00 - 5 19:00 */
        elseif	((strtotime($start_date)+586800)	> $Current_Time)	{	$cs_period = "Ready For Castle Siege";	}	/* 5 19:00 - 6 19:00 */
        elseif	((strtotime($start_date)+590400)	> $Current_Time)	{	$cs_period = "Castle Siege Start";	}	/* 6 19:00 - 6 21:00 */
        else															{	$cs_period = "Truce Period"; }

        $reglista	= App::$DBs[$Db]
            ->select('REG_SIEGE_GUILD,REG_MARKS,SEQ_NUM')
            ->from('MuCastle_REG_SIEGE')
            ->order_by('SEQ_NUM', 'DESC')
            ->get();
        $reglistb 	= $reglista->num_rows();
        $reglist	= $reglista->result_array();
        if ($reglistb > 0) {
            for ($i=0; $i < $reglistb; ++$i) {
                $ReturnArr['g_registed'][$i]['guild']	= $reglist[$i]['REG_SIEGE_GUILD'];
                $ReturnArr['g_registed'][$i]['marks']	= $reglist[$i]['REG_MARKS'];
                $ReturnArr['g_registed'][$i]['marks'] = Guild::Logo($ReturnArr['g_registed'][$i]['marks'],$ReturnArr['g_registed'][$i]['guild'], 24);
                $ReturnArr['g_registed'][$i]['seqnum']  = $reglist[$i]['SEQ_NUM'];
            }
        }
        else $ReturnArr['g_registed'] = 0;

        $ReturnArr['start_date'] = $start_date;


        $ReturnArr['start_date'] = $start_date;
        $ReturnArr['end_date'] = $end_date;
        $ReturnArr['ownerg'] = $ownerg;
        $ReturnArr['money'] = $money;
        $ReturnArr['chaos_tax'] = $chaos_tax;
        $ReturnArr['store_tax'] = $store_tax;
        $ReturnArr['zone_tax'] = $zone_tax;

        $ReturnArr['owner'] = $owner;
        $ReturnArr['mark'] = $mark;

        $ReturnArr['cs_start'] = $cs_start;
        $ReturnArr['cs_end'] = $cs_end;
        $ReturnArr['cs_period'] = $cs_period;
        return $ReturnArr;
    }
    public static function ServerStatistic($Db)
    {
        $ResultArr = array();

        $ResultArr['Online'] = App::$DBs[$Db]
            ->select('memb___id')
            ->from('MEMB_STAT AS ms')
            ->where('ConnectStat', '1')
            ->count_all_results();
        /*->select('memb___id')
            ->from('MEMB_STAT AS ms')
            ->join('AccountCharacter AS ac', 'ac.Id = ms.memb___id COLLATE DATABASE_DEFAULT AND ac.GameIDC != \'\' AND ConnectStat = \'1\'','left', false)
            ->count_all_results();*/

        $ResultArr['Accounts'] = App::$DBs[$Db]->count_all('MEMB_INFO');
        $ResultArr['Players'] = App::$DBs[$Db]->count_all('Character');
        $ResultArr['Guilds'] = App::$DBs[$Db]->count_all('Guild');


        $ResultArr['Count']['DW'] = App::$DBs[$Db]->from('Character')->where('Class', 0)->count_all_results();
        $ResultArr['Count']['SM'] = App::$DBs[$Db]->from('Character')->where('Class', 1)->count_all_results();
        $ResultArr['Count']['GM'] = App::$DBs[$Db]->from('Character')->where('Class', 2)->or_where('Class', 3)->count_all_results();

        $ResultArr['Count']['DK'] = App::$DBs[$Db]->from('Character')->where('Class', 16)->count_all_results();
        $ResultArr['Count']['BK'] = App::$DBs[$Db]->from('Character')->where('Class', 17)->count_all_results();
        $ResultArr['Count']['BM'] = App::$DBs[$Db]->from('Character')->where('Class', 18)->or_where('Class', 19)->count_all_results();

        $ResultArr['Count']['FE'] = App::$DBs[$Db]->from('Character')->where('Class', 32)->count_all_results();
        $ResultArr['Count']['ME'] = App::$DBs[$Db]->from('Character')->where('Class', 33)->count_all_results();
        $ResultArr['Count']['HE'] = App::$DBs[$Db]->from('Character')->where('Class', 34)->or_where('Class', 35)->count_all_results();

        $ResultArr['Count']['SUM'] = App::$DBs[$Db]->from('Character')->where('Class', 80)->count_all_results();
        $ResultArr['Count']['BS'] = App::$DBs[$Db]->from('Character')->where('Class', 81)->count_all_results();
        $ResultArr['Count']['DiM'] = App::$DBs[$Db]->from('Character')->where('Class', 82)->or_where('Class', 83)->count_all_results();


        $ResultArr['Count']['MG'] = App::$DBs[$Db]->from('Character')->where('Class', 48)->count_all_results();
        $ResultArr['Count']['DM'] = App::$DBs[$Db]->from('Character')->where('Class', 49)->or_where('Class', 50)->count_all_results();

        $ResultArr['Count']['DL'] = App::$DBs[$Db]->from('Character')->where('Class', 64)->count_all_results();
        $ResultArr['Count']['LE'] = App::$DBs[$Db]->from('Character')->where('Class', 65)->or_where('Class', 66)->count_all_results();



        //$ResultArr['Crywolf'] = App::$DBs[$Db]->select('CRYWOLF_STATE')->from(App::$DBs[$Db]->column_names['CrywolfTable'])->get()->result_array();
        //$ResultArr['Crywolf'] = $ResultArr['Crywolf'][0]['CRYWOLF_STATE'];

        return $ResultArr;
    }
    public static function PlayerInfo($Nick, $Db)
    {
        $Nick = App::Validate($Nick);

        $row = App::$DBs[$Db]
            ->select(array('Character.Name' ,'Class', 'cLevel', App::$DBs[$Db]->column_names['Resets'],  'Strength', 'Dexterity', 'Vitality', 'Energy', 'Leadership', 'AccountID', App::$DBs[$Db]->column_names['GrandResets'], 'MapNumber', 'HideInfoTime', 'PkLevel', 'PkCount', 'GuildMember.G_Name', 'MEMB_STAT.Connectstat', 'AccountCharacter.GameIDC'))
            ->where('Character.Name', $Nick)
            ->from('Character')
            ->join('GuildMember', '[GuildMember].[Name]  = [Character].[Name] COLLATE DATABASE_DEFAULT','left', false)
            ->join('MEMB_STAT', 'MEMB_STAT.memb___id = Character.AccountID COLLATE DATABASE_DEFAULT' ,'left', false)
            ->join('AccountCharacter', 'AccountCharacter.ID = Character.AccountID COLLATE DATABASE_DEFAULT', 'left',false)
            ->get()->result_array();
        if (empty($row[0])) {
            Messages::Add("Персонаж не найден");
            return;
        }
        //ArrStats($row);
        if ($row[0]['HideInfoTime'] > time())
            $row[0]['Hide'] = 1;
        else
            $row[0]['Hide'] = 0;

        if ($row[0]['Connectstat'] == 1 && $row[0]['GameIDC'] != '')
            $row[0]['Online'] = 1;
        else
            $row[0]['Online'] = 0;

        $result = App::$DBs[$Db]->select()->from('AccountCharacter')->where('ID', $row[0]['AccountID'])->get()->result_array();
        for ($i=1; $i <= 5; $i++) {
            $chars[] = $result[0]['GameID'.$i];
        }
        $row[0]['chars'] = $chars;
/*
        if ($row[0]['HideInfoTime'] > time() &&  $row[0]['AccountID'] == $_SESSION['cabinet_login'])
            $row[0]['Hide'] = 1;
        else
            $row[0]['Hide'] = 0;
*/

        if (App::$DBs[$Db]->column_names['Resets'] != 'Resets')
            $row[0]['Resets'] = $row[0][App::$DBs[$Db]->column_names['Resets']];
        if (App::$DBs[$Db]->column_names['GrandResets'] != 'GrandResets')
            $row[0]['GrandResets'] = $row[0][App::$DBs[$Db]->column_names['GrandResets']];

        $Items = new Item();
        $Items->LoadItemBase();
        $row[0]['Inv'] = $Items->GetCharInv($Nick, $row[0]['Class'],  $row[0]['Hide'], $Db);
        $row[0]['Image'] = Character::GetImageCharacter($row[0]['Class']);
        $row[0]['MapNumber'] = Help::MapName($row[0]['MapNumber']);
        $row[0]['ClassID'] = $row[0]['Class'];
        $row[0]['Class'] = Character::GetClassName($row[0]['Class']);
        $row[0]['PkLevel'] = Character::PkLevel($row[0]['PkLevel']);
        $row[0]['Guild'] = $row[0]['G_Name'];
        if ($row[0]['Guild'] == "")
        {
            $row[0]['Guild'] = "-/-";
        }
         return $row;
    }
    public static function GuildInfo($Name, $Db)
    {
        $Name = App::Validate($Name);

        $Guild = App::$DBs[$Db]
            ->select('MainGuild.G_Name,MainGuild.G_Score,MainGuild.G_Mark,MainGuild.G_Master,MainGuild.G_Union,MainGuild.Number, 
                Guild.G_Name AS Aliance, GuildMember.Name AS Members, GuildMember.G_Status,
                AccountCharacter.GameIDC, MEMB_STAT.Connectstat,
                 Character.Name, Character.Class, Character.'. App::$DBs[$Db]->column_names['GrandResets'] .', Character.'. App::$DBs[$Db]->column_names['Resets'] .', Character.cLevel, Character.AccountID, Character.HideInfoTime')
            ->from('Guild AS MainGuild')
            ->join('Guild', 'Guild.G_Name <> MainGuild.G_Name AND Guild.G_Union = MainGuild.G_Union AND Guild.G_Union <> 0' ,'left', false )
            ->join('GuildMember','GuildMember.G_Name = MainGuild.G_Name COLLATE DATABASE_DEFAULT', 'left', false)
            ->join('Character', 'Character.Name = GuildMember.Name COLLATE DATABASE_DEFAULT','left',false)
            ->join('MEMB_STAT', 'MEMB_STAT.memb___id = Character.AccountID COLLATE DATABASE_DEFAULT', 'left', false)
            ->join('AccountCharacter', 'AccountCharacter.ID = Character.AccountID COLLATE DATABASE_DEFAULT', 'left', false)
            ->where('MainGuild.G_Name',$Name)
            ->order_by('ConnectStat','DESC')->order_by(App::$DBs[$Db]->column_names['GrandResets'], 'DESC')->order_by(App::$DBs[$Db]->column_names['Resets'], 'DESC')
            ->get();

        if($Guild->num_rows()){
            $ResultArr = $Guild->result_array();
            $ResultArr[0]['G_Mark'] = Guild::Logo($ResultArr[0]['G_Mark'], $ResultArr[0]['G_Name'], 64);

            for ($i = 0; $i < $Guild->num_rows(); $i++) {
                if ($ResultArr[$i]['Connectstat'] == 1 && $ResultArr[$i]['GameIDC'] != '')
                    $ResultArr[$i]['Online'] = 1;
                else
                    $ResultArr[$i]['Online'] = 0;
                $ResultArr[$i]['G_Status'] = Guild::GuildStatus($ResultArr[$i]['G_Status']);

                if ($ResultArr[$i]['HideInfoTime'] > time())
                    $ResultArr[$i]['Hide'] = true;
                else
                    $ResultArr[$i]['Hide'] = false;


                if (App::$DBs[$Db]->column_names['Resets'] != 'Resets')
                    $ResultArr[$i]['Resets'] = $ResultArr[$i][App::$DBs[$Db]->column_names['Resets']];
                if (App::$DBs[$Db]->column_names['GrandResets'] != 'GrandResets')
                    $ResultArr[$i]['GrandResets'] = $ResultArr[$i][App::$DBs[$Db]->column_names['GrandResets']];
            }
            return $ResultArr;
        }
        else{
            return false;
        }

    }

    public static function ParseTxtMMOTop($url)
    {
        $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;
            $List[] = $userinfo;
            $count++;
        }
        fclose($handle);
        return $List;
    }




    public static function TopVoters($Db)
    {
        if ($Db == null) {
            $Db = 0;
        }
        $MMOTOPList = static::ParseTxtMMOTop("https://mmotop.ru/votes/d4854b01f61a3de25f47049558d21fbef732e164.txt?080c2a7c6ee4ff617387035b230eec18");

        $VotersListMMOTop = array();
        foreach ($MMOTOPList as $key => $value) {
            if (isset($VotersListMMOTop[$value[4]])) {
                $VotersListMMOTop[$value[4]]['CountVote']++;
            } else {
                $VotersListMMOTop[$value[4]]['CountVote'] = 1;
            }
        }
        $VotersList = array();
        foreach ($VotersListMMOTop as $key => $value) {
            if (isset($VotersList[$key])) {
                $VotersList[$key]['CountVote'] += $value['CountVote'];
            } else {
                $VotersList[$key]['CountVote'] = $value['CountVote'];
            }
        }
     uasort($VotersList, function($a, $b){
            return ($b['CountVote'] - $a['CountVote']);
        });
        $ReturnArr = array();
        $i = 0;
        foreach ($VotersList as $key => $value) {
            if ($i >= 20) {
                continue;
            }
            $ReturnArr[$i]['login'] = $key;
            $ReturnArr[$i]['CountVote'] = $value['CountVote'];
            $ReturnArr[$i]['CountVoteMMOTop'] = $VotersListMMOTop[$key]['CountVote'];
            $ReturnArr[$i]['CharInfo'] = App::$DBs[$Db]
                ->select(array('Name', 'cLevel', App::$DBs[$Db]->column_names['Resets'], App::$DBs[$Db]->column_names['GrandResets']))
                ->from('Character')
                ->where('AccountID = ', App::Validate($key))
                ->order_by(App::$DBs[$Db]->column_names['GrandResets'],'DESC')
                ->order_by(App::$DBs[$Db]->column_names['Resets'],'DESC')
                ->order_by('cLevel','DESC')
                ->get()->row_array();
            if ($ReturnArr[$i]['CharInfo'] == null) {
                $ReturnArr[$i]['VoteToNick'] = 1; 
            }
            $i++;
        }

        return $ReturnArr;
    }

    public static function TopBC($Db)
    {
        if ($Db == null) {
            $Db = 0;
        }
        $TopPk = App::$DBs[$Db]
            ->select(array('Name','Score'))
            ->order_by('Score','DESC')
            ->limit(20)
            ->from('RankingBloodCastle')
            ->get()->result_array();

        $ReturnArr = $TopPk;
        return $ReturnArr;
    }
    public static function TopDS($Db)
    {
        if ($Db == null) {
            $Db = 0;
        }
        $TopPk = App::$DBs[$Db]
            ->select(array('Name','Score'))
            ->order_by('Score','DESC')
            ->limit(20)
            ->from('RankingDevilSquare')
            ->get()->result_array();

        $ReturnArr = $TopPk;
        return $ReturnArr;
    }
    public static function TopCC($Db)
    {
        if ($Db == null) {
            $Db = 0;
        }
        $TopPk = App::$DBs[$Db]
            ->select(array('Name','Score'))
            ->order_by('Score','DESC')
            ->limit(20)
            ->from('RankingChaosCastle')
            ->get()->result_array();

        $ReturnArr = $TopPk;
        return $ReturnArr;
    }
}