/**
  * Deletes old player_totals table and reload everything from
  * scratches into it.
  *
  * @return string
  */
 public function calculate()
 {
     \DB::table('player_totals')->truncate();
     $aliases = Alias::with('players')->whereNotIn('name', DeletedPlayer::lists('player_name'))->get();
     $totalServerScore = Player::sum('score');
     foreach ($aliases as $alias) {
         $playerTotal = new PlayerTotal();
         $playerTotal->name = $alias->name;
         $playerTotal->alias_id = $alias->id;
         $playerTotal->profile_id = $alias->profile_id;
         /*$playerTotal->last_loadout_id = $alias->profile->loadout_id;*/
         $playerTotal->last_team = $alias->profile->team;
         //$playerTotal->first_game_id = $alias->profile->game_first;
         //$playerTotal->last_game_id = $alias->profile->game_last;
         $playerTotal->country_id = $alias->players->last()->country_id;
         $playersCollection = $alias->players;
         //Permanent Solution
         if ($alias->profile->loadout->kyaKhali()) {
             foreach ($playersCollection->reverse() as $item) {
                 if (!$item->loadout->kyaKhali()) {
                     $playerTotal->last_loadout_id = $item->loadout_id;
                     break;
                 } else {
                     $playerTotal->last_loadout_id = $item->loadout_id;
                 }
             }
         } else {
             $playerTotal->last_loadout_id = $alias->profile->loadout_id;
         }
         $playerTotal->first_game_id = $playersCollection->min('game_id');
         $playerTotal->last_game_id = $playersCollection->max('game_id');
         $playerTotal->is_admin = $playersCollection->max('is_admin');
         $playerTotal->total_score = $playersCollection->sum('score');
         $playerTotal->highest_score = $playersCollection->max('score');
         $playerTotal->total_time_played = $playersCollection->sum('time_played');
         $playerTotal->total_kills = $playersCollection->sum('kills');
         $playerTotal->total_team_kills = $playersCollection->sum('team_kills');
         $playerTotal->total_deaths = $playersCollection->sum('deaths');
         $playerTotal->total_suicides = $playersCollection->sum('suicides');
         $playerTotal->total_arrests = $playersCollection->sum('arrests');
         $playerTotal->total_arrested = $playersCollection->sum('arrested');
         $playerTotal->best_killstreak = $playersCollection->max('kill_streak');
         $playerTotal->best_deathstreak = $playersCollection->max('death_streak');
         $playerTotal->best_arreststreak = $playersCollection->max('arrest_streak');
         $playerTotal->total_round_played = $playersCollection->unique('game_id')->count('game_id');
         $playerTotal->last_ip_address = $alias->ip_address;
         $playerTotal->killdeath_ratio = $playerTotal->total_deaths == 0 ? $playerTotal->total_kills : round($playerTotal->total_kills / $playerTotal->total_deaths, 2);
         $playerTotal->arr_ratio = $playerTotal->total_arrested == 0 ? $playerTotal->total_arrests : round($playerTotal->total_arrests / $playerTotal->total_arrested, 2);
         $playerTotal->score_per_min = $playerTotal->total_time_played == 0 ? $playerTotal->total_score : round($playerTotal->total_score / $playerTotal->total_time_played * 60, 2);
         $playerTotal->score_percentile = $playerTotal->total_score == 0 || $totalServerScore == 0 ? 0 : round($playerTotal->total_score / $totalServerScore * 100, 2);
         $won = 0;
         $lost = 0;
         $draw = 0;
         foreach ($playersCollection->unique('game_id') as $player) {
             switch ($player->game->isWinner($player->team)) {
                 case 0:
                     $lost++;
                     break;
                 case 1:
                     $won++;
                     break;
                 case -1:
                     $draw++;
                     break;
                 default:
                     break;
             }
         }
         $playerTotal->game_won = $won;
         $playerTotal->game_lost = $lost;
         $playerTotal->game_draw = $draw;
         $playerTotal->total_points = max($playerTotal->total_kills * 4 + $playerTotal->total_arrests * 13 - $playerTotal->total_deaths - $playerTotal->total_arrested * 3 - $playerTotal->total_team_kills * 2, 0);
         /**
          * This give extra points to the player from PlayerPoints Model
          */
         $playerPoints = PlayerPoint::where('name', $playerTotal->name)->get();
         if (!$playerPoints->isEmpty()) {
             $pointsToGive = $playerPoints->sum('points');
             $playerTotal->total_points += $pointsToGive;
         }
         /**
          * Calculation of player_rating
          *
          * Calculate only if player with this alias has played more than 10 hours in server
          * and also is active and seen in last 7 days
          */
         $last_seen_game = Game::find($playerTotal->last_game_id);
         if ($playerTotal->total_time_played > 60 * 60 * 10 && \Carbon\Carbon::now()->timestamp - $last_seen_game->updated_at->timestamp <= 60 * 60 * 24 * 7) {
             $playerTotal->player_rating = max($playerTotal->killdeath_ratio + $playerTotal->arr_ratio + $playerTotal->score_per_min * 1.25, 0);
             $playerTotal->player_rating = min($playerTotal->player_rating, 10);
         }
         /**
          * Calculation of rank_id using total_points and Rank table
          *
          * Add this if want time played(rank_seconds) also used to calculate ranks
          * ->where('rank_seconds', '<=' ,$playerTotal->total_time_played)
          *
          * Make sure that there are ranks in ranks table if not,
          * Run php artisan db:seed
          */
         $playerTotal->rank_id = Rank::where('rank_points', '>=', $playerTotal->total_points)->orderBy('rank_points')->first()->id;
         $playerTotal->save();
     }
     /**
      * Getting all PlayerTotal and updating its position one by one.
      */
     $pTs = PlayerTotal::orderBy('player_rating', 'DESC')->orderBy('total_points', 'DESC')->orderBy('total_score', 'DESC')->get();
     $position = 0;
     foreach ($pTs as $pT) {
         $pT->position = ++$position;
         $pT->save();
     }
     // Put to Top Player so that some bugs are fixed.
     $topPlayers = PlayerTotal::with(['country', 'rank'])->orderBy('position')->limit(10)->get();
     Cache::put('top_players', $topPlayers, 31);
     return "Players total has been logged into player_total table successfully!";
 }
 public function getTop10()
 {
     $top10KD = PlayerTotal::where('total_kills', '>', '99')->with('country', 'rank', 'lastGame')->orderBy('killdeath_ratio', 'DESC')->limit(10)->get();
     $top10AAR = PlayerTotal::where('total_arrests', '>', '49')->with('country', 'rank', 'lastGame')->orderBy('arr_ratio', 'DESC')->limit(10)->get();
     $top10Score = PlayerTotal::orderBy('total_score', 'DESC')->with('country', 'rank', 'lastGame')->limit(10)->get();
     $top10Round = PlayerTotal::orderBy('total_round_played', 'DESC')->with('country', 'rank', 'lastGame')->limit(10)->get();
     $top10HighestScore = PlayerTotal::orderBy('highest_score', 'DESC')->with('country', 'rank', 'lastGame')->limit(10)->get();
     $top10Winners = PlayerTotal::orderBy('game_won', 'DESC')->with('country', 'rank', 'lastGame')->limit(10)->get();
     $top10KillStreak = PlayerTotal::orderBy('best_killstreak', 'DESC')->with('country', 'rank', 'lastGame')->limit(10)->get();
     $top10ArrestStreak = PlayerTotal::orderBy('best_arreststreak', 'DESC')->with('country', 'rank', 'lastGame')->limit(10)->get();
     $array = ['top10KD' => $top10KD, 'top10AAR' => $top10AAR, 'top10Score' => $top10Score, 'top10Round' => $top10Round, 'top10HighestScore' => $top10HighestScore, 'top10Winners' => $top10Winners, 'top10KillStreak' => $top10KillStreak, 'top10ArrestStreak' => $top10ArrestStreak, 'position1' => 1, 'position2' => 1, 'position3' => 1, 'position4' => 1, 'position5' => 1, 'position6' => 1, 'position7' => 1, 'position8' => 1];
     return view('statistics.top10', $array);
 }
 /**
  * Query API for Gameserver to query for Players
  *
  * @param Request $request
  * @return $this|void
  */
 public function whois(Request $request)
 {
     $data = $request->data;
     $data = explode("\$\$", $data);
     $playerName = $data[0];
     $playerIp = $data[1];
     $bOffline = $data[2];
     $key = $data[3];
     if ($data == NULL || empty($data) || env('SERVER_QUERY_KEY') != $key) {
         return;
     }
     /**
      * Stats Query System
      * Like Top 10 Player etc.
      */
     if ($playerName == "top 10") {
         $players = PlayerTotal::orderBy('position')->limit(10)->get();
         $i = 1;
         $pl = "";
         foreach ($players as $player) {
             if ($i % 2 == 0) {
                 $pl = $pl . "[c=FFFFFF][b]#{$player->position}[\\c] [c=FFFF00][b]{$player->name}[\\b][\\c]\n";
             } else {
                 $pl = $pl . "[c=FFFFFF][b]#{$player->position}[\\c] [c=FFFF00][b]{$player->name}[\\b][\\c][c=00ff00][b]  -  [\\b][\\c]";
             }
             $i++;
         }
         printf("[c=00ffdd][b][u]Top #10 Players of Server[\\u][\\b][\\c]\n");
         printf("%s", $pl);
         exit;
     }
     /**
      * Player Query System
      */
     /**
      * If the Searched Name is Not Present in Server
      *
      */
     if ($bOffline == "yes") {
         $players = PlayerTotal::where('name', 'LIKE', "%{$playerName}%")->get();
         /**
          * If Not Found
          */
         if ($players->isEmpty() || is_null($players)) {
             return view('api.whois.notfound')->with('playerName', $playerName);
         } elseif ($players->count() == 1) {
             $player = $players->first();
             /*$data = [
                   'player' => $player,
                   'playerAddr' => $player->country->countryName,
               ];*/
             printf("[c=FFFF00][b][u]%s[\\u][\\b][\\c] is from [b][c=EBFFFF]%s[\\c][\\b]\n", $player->name, $player->country->countryName);
             printf("[b][c=FFFF00][u]%s[\\u][\\c][\\b]'s Position: [c=FFFEEB][b][u]#%d[\\u][\\b][\\c] [c=00FF00]-[\\c] Score: [c=FFFEEB][b][u]%d[\\u][\\b][\\c] [c=00FF00]-[\\c] Rank: [c=FFFEEB][b][u]%s[\\u][\\b][\\c]\n", $player->name, $player->position, $player->total_score, $player->rank->name);
             printf("Score Per Min: [c=FFFEEB][b][u]%.2f points[\\u][\\b][\\c] [c=00FF00]-[\\c] Highest Score: [c=FFFEEB][b][u]%d[\\u][\\b][\\c]\n", round($player->score_per_min, 2), $player->highest_score);
             printf("Time Played: [c=FFFEEB][b][u]%s[\\u][\\b][\\c] [c=00ff00]-[\\c] Last Seen: [c=00FF00][b][u]%s[\\u][\\b][\\c]", gmdate("H\\h i\\m", $player->total_time_played), $player->lastGame->created_at->diffForHumans());
             exit;
             //return view('api.whois.onefound', $data);
         } else {
             $playerss = PlayerTotal::where('name', 'LIKE', "{$playerName}")->get();
             // Display single one
             if ($playerss->count() == 1) {
                 $player = $playerss->first();
                 printf("[c=FFFF00][b][u]%s[\\u][\\b][\\c] is from [b][c=EBFFFF]%s[\\c][\\b]\n", $player->name, $player->country->countryName);
                 printf("[b][c=FFFF00][u]%s[\\u][\\c][\\b]'s Position: [c=FFFEEB][b][u]#%d[\\u][\\b][\\c] [c=00FF00]-[\\c] Score: [c=FFFEEB][b][u]%d[\\u][\\b][\\c] [c=00FF00]-[\\c] Rank: [c=FFFEEB][b][u]%s[\\u][\\b][\\c]\n", $player->name, $player->position, $player->total_score, $player->rank->name);
                 printf("Score Per Min: [c=FFFEEB][b][u]%.2f points[\\u][\\b][\\c] [c=00FF00]-[\\c] Highest Score: [c=FFFEEB][b][u]%d[\\u][\\b][\\c]\n", round($player->score_per_min, 2), $player->highest_score);
                 printf("Time Played: [c=FFFEEB][b][u]%s[\\u][\\b][\\c] [c=00ff00]-[\\c] Last Seen: [c=00FF00][b][u]%s[\\u][\\b][\\c]", gmdate("H\\h i\\m", $player->total_time_played), $player->lastGame->created_at->diffForHumans());
                 exit;
                 /*$data = [
                       'player' => $player,
                       'playerAddr' => $player->country->countryName,
                   ];
                   return view('api.whois.onefound', $data);*/
             } else {
                 $playerlist = "";
                 $i = 1;
                 foreach ($players->take(2) as $player) {
                     // If the limit exceed 4 players then only show 2
                     $playerlist = $playerlist . "[c=FFFF00]" . $player->name . "[\\c][c=00ff00] - [\\c]";
                 }
                 $playerlist = substr($playerlist, 0, -17);
                 printf("Found [b]%s[\\b] players matching [b]%s[\\b]:\\n [b]%s[\\b]", $players->count(), $playerName, $playerlist);
                 exit;
                 /*$data = [
                       'players' => $players,
                       'searchQuery' => $playerName
                   ];
                   return view('api.whois.manyfound', $data);*/
             }
         }
     } else {
         if ($bOffline == "no") {
             $players = PlayerTotal::where('name', 'LIKE', "{$playerName}")->get();
             $geoip = \App::make('geoip');
             $playerCountryName = "[c=d3d3d3]Unknown Territory[\\c]";
             try {
                 if ($player_geoip = $geoip->city($playerIp)) {
                     //$playerCountryName = $player_geoip->country->names['en'];
                     $playerCountryName = $player_geoip->city->names['en'] == "" ? "" : $player_geoip->city->names['en'] . ", ";
                     $playerCountryName = $playerCountryName . $player_geoip->country->names['en'];
                 }
             } catch (\Exception $e) {
                 switch ($e) {
                     case $e instanceof \InvalidArgumentException:
                         $playerCountryName = "[c=d3d3d3]Unknown Territory[\\c]";
                         break;
                     case $e instanceof \GeoIp2\Exception\AddressNotFoundException:
                         $playerCountryName = "[c=d3d3d3]Unknown Territory[\\c]";
                         break;
                     default:
                         $playerCountryName = "[c=d3d3d3]Unknown Territory[\\c]";
                         break;
                 }
             }
             /**
              * Player has never played in this server before
              */
             if ($players->count() <= 0) {
                 printf("[c=FFFF00][b][u]%s[\\u][\\b][\\c] is from [b][c=EBFFFF]%s[\\c][\\b]", $playerName, $playerCountryName);
                 exit;
             } else {
                 $player = $players->first();
                 printf("[c=FFFF00][b][u]%s[\\u][\\b][\\c] is from [b][c=EBFFFF]%s[\\c][\\b]\n", $player->name, $playerCountryName);
                 printf("[b][c=FFFF00][u]%s[\\u][\\c][\\b]'s Position: [c=FFFEEB][b][u]#%d[\\u][\\b][\\c] [c=00FF00]-[\\c] Score: [c=FFFEEB][b][u]%d[\\u][\\b][\\c] [c=00FF00]-[\\c] Rank: [c=FFFEEB][b][u]%s[\\u][\\b][\\c]\n", $player->name, $player->position, $player->total_score, $player->rank->name);
                 printf("Score Per Min: [c=FFFEEB][b][u]%.2f points[\\u][\\b][\\c] [c=00FF00]-[\\c] Highest Score: [c=FFFEEB][b][u]%d[\\u][\\b][\\c]\n", round($player->score_per_min, 2), $player->highest_score);
                 printf("Time Played: [c=FFFEEB][b][u]%s[\\u][\\b][\\c] [c=00ff00]-[\\c] Last Seen: [c=00FF00][b][u]%s[\\u][\\b][\\c]", gmdate("H\\h i\\m", $player->total_time_played), $player->lastGame->created_at->diffForHumans());
                 exit;
                 /*$data = [
                       'player' => $player,
                       'playerAddr' => $playerCountryName,
                   ];
                   return view('api.whois.onefound', $data);*/
             }
         } elseif ($bOffline == "justjoined") {
             $players = PlayerTotal::where('name', 'LIKE', "{$playerName}")->get();
             $geoip = \App::make('geoip');
             $playerCountryName = "[c=d3d3d3]Unknown Territory[\\c]";
             try {
                 if ($player_geoip = $geoip->city($playerIp)) {
                     //$playerCountryName = $player_geoip->country->names['en'];
                     $playerCountryName = $player_geoip->city->names['en'] == "" ? "" : $player_geoip->city->names['en'] . ", ";
                     $playerCountryName = $playerCountryName . $player_geoip->country->names['en'];
                 }
             } catch (\Exception $e) {
                 switch ($e) {
                     case $e instanceof \InvalidArgumentException:
                         $playerCountryName = "[c=d3d3d3]Unknown Territory[\\c]";
                         break;
                     case $e instanceof \GeoIp2\Exception\AddressNotFoundException:
                         $playerCountryName = "[c=d3d3d3]Unknown Territory[\\c]";
                         break;
                     default:
                         $playerCountryName = "[c=d3d3d3]Unknown Territory[\\c]";
                         break;
                 }
             }
             /**
              * Player has never played in this server before
              */
             if ($players->count() <= 0) {
                 printf("[c=FFFF00][b][u]%s[\\u][\\b][\\c] is coming from [b][c=EBFFFF]%s[\\c][\\b]", $playerName, $playerCountryName);
                 exit;
             } else {
                 $player = $players->first();
                 printf("[c=FFFF00][b][u]%s[\\u][\\b][\\c] is coming from [b][c=EBFFFF]%s[\\c][\\b]\n", $player->name, $playerCountryName);
                 printf("[b][c=FFFF00][u]%s[\\u][\\c][\\b]'s Position: [c=FFFEEB][b][u]#%d[\\u][\\b][\\c] [c=00FF00]-[\\c] Score: [c=FFFEEB][b][u]%d[\\u][\\b][\\c] [c=00FF00]-[\\c] Rank: [c=FFFEEB][b][u]%s[\\u][\\b][\\c]\n", $player->name, $player->position, $player->total_score, $player->rank->name);
                 printf("Score Per Min: [c=FFFEEB][b][u]%.2f points[\\u][\\b][\\c] [c=00FF00]-[\\c] Highest Score: [c=FFFEEB][b][u]%d[\\u][\\b][\\c]\n", round($player->score_per_min, 2), $player->highest_score);
                 printf("Time Played: [c=FFFEEB][b][u]%s[\\u][\\b][\\c] [c=00ff00]-[\\c] Last Seen: [c=00FF00][b][u]%s[\\u][\\b][\\c]", gmdate("H\\h i\\m", $player->total_time_played), $player->lastGame->created_at->diffForHumans());
                 exit;
                 /*$data = [
                       'player' => $player,
                       'playerAddr' => $playerCountryName,
                   ];
                   return view('api.whois.justjoined', $data);*/
             }
         }
     }
 }