public function storeForTournament($id, Request $request)
 {
     $t = KTournament::findOrFail($id);
     $comment = \Input::get('body');
     if ($comment == '') {
         return \Redirect::back();
     }
     if ($request->user()->muted) {
         return \Redirect::back()->with('error', 'You are muted.');
     }
     $t->comments()->create(['body' => $comment, 'user_id' => Auth::user()->id]);
     // Create notification
     $not = new Notification();
     $not->from($request->user())->withType('UserCommentOnTournament')->withSubject('A comment is done on tournament')->withBody(link_to_route('user.show', $request->user()->displayName(), $request->user()->username) . " has commented on " . link_to_route('tournament.show', $t->name, $t->slug) . " tournament")->withStream(true)->regarding($t)->deliver();
     return \Redirect::back()->with('success', 'Success!');
 }
 /**
  * @param $slug
  * @param $id
  * @param Request $request
  * @return $this|\Illuminate\Http\RedirectResponse
  */
 public function postCalculateMatchFinal($slug, $id, Request $request)
 {
     $tournament = KTournament::enabled()->whereSlug($slug)->first();
     $match = KMatch::find($id);
     if (!$tournament || !$match) {
         abort(404);
     }
     //If has enough permissions or not
     if (!$request->user()->canManageTournament($tournament)) {
         return redirect()->home();
     }
     if ($match->has_been_played) {
         return redirect()->route('tournament.bracket.show', [$tournament->slug])->with('error', "Error! Already calculated, Plz contact admin for support");
     }
     if ($request->overall_winner_id == "0" && $tournament->bracket_type > 0) {
         return redirect()->route('tournament.bracket.show', [$tournament->slug])->with('error', "Error! Tie only supported in Round Robin Tournament");
     }
     // Check is On. Turn off only for testing
     if (true) {
         //Check if all team1_p1_score is present
         foreach ($request->team1_p1_score as $x) {
             if ($x == null || $x == "") {
                 return redirect()->route('tournament.match.getcalculate', [$tournament->slug, $match->id])->with('error', "Error! Something is not correct. Please retry.");
             }
         }
         //Check if all team1_p2_score is present
         foreach ($request->team1_p2_score as $x) {
             if ($x == null || $x == "") {
                 return redirect()->route('tournament.match.getcalculate', [$tournament->slug, $match->id])->with('error', "Error! Something is not correct. Please retry.");
             }
         }
         //Check if all team2_p1_score is present
         foreach ($request->team2_p1_score as $x) {
             if ($x == null || $x == "") {
                 return redirect()->route('tournament.match.getcalculate', [$tournament->slug, $match->id])->with('error', "Error! Something is not correct. Please retry.");
             }
         }
         //Check if all team2_p2_score is present
         foreach ($request->team2_p2_score as $x) {
             if ($x == null || $x == "") {
                 return redirect()->route('tournament.match.getcalculate', [$tournament->slug, $match->id])->with('error', "Error! Something is not correct. Please retry.");
             }
         }
         if ($tournament->tournament_type == 2) {
             //Check if all team1_p3_score is present
             foreach ($request->team1_p3_score as $x) {
                 if ($x == null || $x == "") {
                     return redirect()->route('tournament.match.getcalculate', [$tournament->slug, $match->id])->with('error', "Error! Something is not correct. Please retry.");
                 }
             }
             //Check if all team2_p3_score is present
             foreach ($request->team2_p3_score as $x) {
                 if ($x == null || $x == "") {
                     return redirect()->route('tournament.match.getcalculate', [$tournament->slug, $match->id])->with('error', "Error! Something is not correct. Please retry.");
                 }
             }
         }
         //Check if all team1_p1_score is present
         foreach ($request->winner as $x) {
             if ($x == null || $x == "") {
                 return redirect()->route('tournament.match.getcalculate', [$tournament->slug, $match->id])->with('error', "Error! Something is not correct. Please retry.");
             }
         }
     }
     // Now Insertions will be here...
     //First insert game_id in Match Table
     //Check if all game_id is present
     $i = 1;
     foreach ($request->game_id as $x) {
         $match->{"game" . $i . "_id"} = $x;
         $i++;
     }
     /**
      * GAME WIN OUTCOMES
      * 0 -> Team 1 Wins
      * 1 -> Team 2 Wins
      * 2 -> A Tie
      * 3 -> None
      */
     $team1_w = 0;
     $team2_w = 0;
     $tie_w = 0;
     $no_w = 0;
     $i = 1;
     foreach ($request->winner as $x) {
         $match->{"game" . $i . "_id_outcome"} = $x;
         $i++;
         switch ($x) {
             case 0:
                 $team1_w++;
                 break;
             case 1:
                 $team2_w++;
                 break;
             case 2:
                 $tie_w++;
                 break;
             case 3:
                 $no_w++;
                 break;
             default:
                 break;
         }
     }
     if ($team1_w > $team2_w) {
         $match->winner_team_won_by = $team1_w . " - " . $team2_w;
     } else {
         $match->winner_team_won_by = $team2_w . " - " . $team1_w;
     }
     /*$collection = collect($request->winner);
             $items = ($collection->groupBy(function($item,$key){
                 return $item;
             }));
     
             dd($match->winner_team_won_by);
             foreach($items as $item)
             {
                 dd($item->count());
             }*/
     /**
      * If tournament type is 3v3 then take 3 players else only 2
      * @TODO: Change if 1v1 implemented
      */
     if ($tournament->tournament_type == 2) {
         $team1_p1_score_sum = array_sum($request->team1_p1_score);
         $team1_p2_score_sum = array_sum($request->team1_p2_score);
         $team1_p3_score_sum = array_sum($request->team1_p3_score);
         $team2_p1_score_sum = array_sum($request->team2_p1_score);
         $team2_p2_score_sum = array_sum($request->team2_p2_score);
         $team2_p3_score_sum = array_sum($request->team2_p3_score);
         $team1_total_score = $team1_p1_score_sum + $team1_p2_score_sum + $team1_p3_score_sum;
         $team2_total_score = $team2_p1_score_sum + $team2_p2_score_sum + $team2_p3_score_sum;
     } else {
         $team1_p1_score_sum = array_sum($request->team1_p1_score);
         $team1_p2_score_sum = array_sum($request->team1_p2_score);
         $team2_p1_score_sum = array_sum($request->team2_p1_score);
         $team2_p2_score_sum = array_sum($request->team2_p2_score);
         $team1_total_score = $team1_p1_score_sum + $team1_p2_score_sum;
         $team2_total_score = $team2_p1_score_sum + $team2_p2_score_sum;
     }
     $match->k_team1_total_score = $team1_total_score;
     $match->k_team2_total_score = $team2_total_score;
     if ($request->overall_winner_id != "-1" && $request->overall_winner_id != "0" && $request->overall_winner_id != $match->team1->id && $request->overall_winner_id != $match->team2->id) {
         return redirect()->home()->with("error", "Error! Don't mess up with codes.");
     }
     $match->winner_team_id = $request->overall_winner_id;
     $match->has_been_played = true;
     //SAVE MATCH
     $match->save();
     $team1 = $match->team1;
     $team2 = $match->team2;
     $team1->total_score += $team1_total_score;
     $team2->total_score += $team2_total_score;
     //If winner is team 1
     if ($request->overall_winner_id == $team1->id) {
         $team1->total_wins += 1;
         $team2->total_lost += 1;
         $team1->points += 2;
         $team2->points -= 2;
     } elseif ($request->overall_winner_id == $team2->id) {
         $team2->total_wins += 1;
         $team1->total_lost += 1;
         $team2->points += 2;
         $team1->points -= 2;
     } elseif ($request->overall_winner_id == "0") {
         $team2->total_tie += 1;
         $team1->total_tie += 1;
         $team1->points += 1;
         $team2->points += 1;
     } else {
     }
     //SAVE TEAMS
     $team1->save();
     $team2->save();
     //SAVE INDI PLAYER STATS
     if ($tournament->tournament_type == 0) {
         $team1_p1 = $match->team1->playerselected->first();
         $team1_p2 = $match->team1->playerselected->last();
         $team2_p1 = $match->team2->playerselected->first();
         $team2_p2 = $match->team2->playerselected->last();
         $match->team1->givescoretouser($team1_p1, $team1_p1_score_sum);
         $match->team1->givescoretouser($team1_p2, $team1_p2_score_sum);
         $match->team2->givescoretouser($team2_p1, $team2_p1_score_sum);
         $match->team2->givescoretouser($team2_p2, $team2_p2_score_sum);
     } else {
         if ($tournament->tournament_type == 2) {
             $i = 1;
             foreach ($match->team1->playerselected as $player) {
                 //${'team1_p'.$i} = $player;
                 $match->team1->givescoretouser($player, ${'team1_p' . $i . '_score_sum'});
                 $i++;
             }
             $y = 1;
             foreach ($match->team2->playerselected as $player) {
                 //${'team2_p'.$i} = $player;
                 $match->team2->givescoretouser($player, ${'team2_p' . $y . '_score_sum'});
                 $y++;
             }
         }
     }
     //@TODO: Add else here for 1v1
     //FOR DE/SE ONLY
     //Check all match id (TBA) and change to team id as per match schedule
     if ($tournament->bracket_type > 0) {
         // Check for all matches with has this match index for team 1...
         $team1_from_match_indexes = KMatch::where('team1_from_match_index', $match->match_index)->get();
         foreach ($team1_from_match_indexes as $team1_from_match_index) {
             if ($team1_from_match_index->team1_from_match_rank == 1) {
                 $team1_from_match_index->k_team1_id = $match->winner_team_id;
                 $team1_from_match_index->save();
             } elseif ($team1_from_match_index->team1_from_match_rank == 2) {
                 $team1_from_match_index->k_team1_id = $team1->id == $match->winner_team_id ? $team2->id : $team1->id;
                 $team1_from_match_index->save();
             }
         }
         // Check for all matches with has this match index for team 2...
         $team2_from_match_indexes = KMatch::where('team2_from_match_index', $match->match_index)->get();
         foreach ($team2_from_match_indexes as $team2_from_match_index) {
             if ($team2_from_match_index->team2_from_match_rank == 1) {
                 $team2_from_match_index->k_team2_id = $match->winner_team_id;
                 $team2_from_match_index->save();
             } elseif ($team2_from_match_index->team2_from_match_rank == 2) {
                 $team2_from_match_index->k_team2_id = $team1->id == $match->winner_team_id ? $team2->id : $team1->id;
                 $team2_from_match_index->save();
             }
         }
     }
     //Dispatch Notifications
     //If match is cancelled
     if ($request->winner_team_id == "-1") {
         // Create notification with Stream
         $not = new Notification();
         $not->from($request->user())->withType('TournamentMatchCancelled')->withSubject('Match is cancelled in a tournament')->withBody(link_to_route('tournament.show', $tournament->name, $tournament->slug) . " : Match between " . link_to_route('tournament.team.show', $match->team1->name, [$tournament->slug, $match->team1->id]) . " and " . link_to_route('tournament.team.show', $match->team2->name, [$tournament->slug, $match->team2->id]) . " was <span class='text-danger notify-bold'>cancelled</span>")->withStream(true)->regarding($tournament)->deliver();
     } else {
         if ($request->winner_team_id == "0") {
             $not = new Notification();
             $not->from($request->user())->withType('TournamentMatchTie')->withSubject('Match is tie in a tournament')->withBody(link_to_route('tournament.show', $tournament->name, $tournament->slug) . " : Match between " . link_to_route('tournament.team.show', $match->team1->name, [$tournament->slug, $match->team1->id]) . " and " . link_to_route('tournament.team.show', $match->team2->name, [$tournament->slug, $match->team2->id]) . " <span class='text-danger notify-bold'>tied</span> by " . $request->winner_team_won_by)->withStream(true)->regarding($tournament)->deliver();
         } else {
             $not = new Notification();
             $not->from($request->user())->withType('TournamentMatchPlayed')->withSubject('Match is played in a tournament')->withBody(link_to_route('tournament.show', $tournament->name, $tournament->slug) . " : " . $match->getWinningTextForNotifications())->withStream(true)->regarding($tournament)->deliver();
         }
     }
     //RANK THE TEAMS
     //@TODO: Its TEMP CHANGE IT
     $teams = KTeam::where('team_status', 1)->orderBy('points', 'desc')->orderBy('total_wins', 'desc')->orderBy('total_lost', 'asc')->orderBy('total_tie', 'desc')->orderBy('total_score', 'desc')->get();
     $i = 0;
     foreach ($teams as $team) {
         $team->team_position = ++$i;
         $team->save();
     }
     return redirect()->route('tournament.show', [$tournament->slug])->with('message', "Success! Match data has been recorded.");
 }
 /**
  * Return match details.
  *
  * @param $slug
  * @param $id
  * @param Request $request
  * @return $this
  */
 public function getTournamentMatch($slug, $id, Request $request)
 {
     $tournament = KTournament::whereSlug($slug)->firstOrFail();
     $match = KMatch::findOrFail($id);
     $games = [];
     for ($i = 1; $i <= 6; $i++) {
         if ($match->{"game" . $i . "_id"} != null) {
             $game = Game::findOrFail($match->{"game" . $i . "_id"});
             $game->game_index = $i;
             array_push($games, $game);
         }
     }
     return view('tournament.showmatch')->with('tournament', $tournament)->with('match', $match)->with('games', $games);
 }
 /**
  * Roast DE Matches for a Tournament
  * @param KTournament $tournament
  * @param bool $forced
  * @return string
  */
 public function roastDoubleElimination(KTournament $tournament, $forced = false)
 {
     $tour = $tournament;
     //If tournament can show brackets
     if (!$tour->canShowBrackets()) {
         return "Tournament {$tour->id} cannot show bracket\n";
     }
     // if already roasted
     if ($tour->matches()->first() && $forced == false) {
         return "Tournament {$tour->id} already roasted\n";
     }
     // If forced then deleted the roasted matches first
     if ($forced == true) {
         $tour->matches()->delete();
     }
     // Turn to not eligible all teams having less than minimum required players.
     foreach ($tour->teams()->qualified()->get() as $teamx) {
         if ($teamx->isFull()) {
             continue;
         }
         $teamx->team_status = 3;
         //Not Eligible
         $teamx->save();
     }
     // Team taking PART (only their respected IDs)
     $competitors = $tour->teams()->qualified()->get(['id'])->lists('id')->toArray();
     // Total no. of rounds to be played
     $rounds = log(count($competitors), 2) + 1;
     // round one
     for ($i = 0; $i < log(count($competitors), 2); $i++) {
         $seeded = array();
         foreach ($competitors as $competitor) {
             $splice = pow(2, $i);
             $seeded = array_merge($seeded, array_splice($competitors, 0, $splice));
             $seeded = array_merge($seeded, array_splice($competitors, -$splice));
         }
         $competitors = $seeded;
     }
     $events = array_chunk($seeded, 2);
     if ($rounds > 2) {
         $round_index = count($events);
         // second round
         for ($i = 0; $i < count($competitors) / 2; $i++) {
             array_push($events, array(array('from_event_index' => $i, 'from_event_rank' => 1), array('from_event_index' => ++$i, 'from_event_rank' => 1)));
         }
         $round_matchups = array();
         for ($i = 0; $i < count($competitors) / 2; $i++) {
             array_push($round_matchups, array(array('from_event_index' => $i, 'from_event_rank' => 2), array('from_event_index' => ++$i, 'from_event_rank' => 2)));
         }
         $events = array_merge($events, $round_matchups);
         for ($i = 0; $i < count($round_matchups); $i++) {
             array_push($events, array(array('from_event_index' => $i + count($competitors) / 2, 'from_event_rank' => 2), array('from_event_index' => $i + count($competitors) / 2 + count($competitors) / 2 / 2, 'from_event_rank' => 1)));
         }
     }
     if ($rounds > 3) {
         // subsequent rounds
         for ($i = 0; $i < $rounds - 3; $i++) {
             $round_events = pow(2, $rounds - 3 - $i);
             $total_events = count($events);
             for ($j = 0; $j < $round_events; $j++) {
                 array_push($events, array(array('from_event_index' => $j + $round_index, 'from_event_rank' => 1), array('from_event_index' => ++$j + $round_index, 'from_event_rank' => 1)));
             }
             for ($j = 0; $j < $round_events; $j++) {
                 array_push($events, array(array('from_event_index' => $j + $round_index + $round_events * 2, 'from_event_rank' => 1), array('from_event_index' => ++$j + $round_index + $round_events * 2, 'from_event_rank' => 1)));
             }
             for ($j = 0; $j < $round_events / 2; $j++) {
                 array_push($events, array(array('from_event_index' => $j + $total_events, 'from_event_rank' => 2), array('from_event_index' => $j + $total_events + $round_events / 2, 'from_event_rank' => 1)));
             }
             $round_index = $total_events;
         }
     }
     if ($rounds > 1) {
         // finals
         array_push($events, array(array('from_event_index' => count($events) - 3, 'from_event_rank' => 1), array('from_event_index' => count($events) - 1, 'from_event_rank' => 1)));
     }
     // Now save this to DB
     $starts_at_glob = $tournament->tournament_starts_at->addHour(1);
     $i = 0;
     foreach (array_chunk($events, 2) as $eventx) {
         foreach ($eventx as $event) {
             //Create new Match;
             $match = new KMatch();
             // Time
             $match->starts_at = $starts_at_glob;
             $starts_at_glob->addHour(2);
             //Adding of TEAM-1 of Match
             $team1 = $event[0];
             //If team is directly given ID -- in Round 1 generally
             if (!is_array($team1)) {
                 $match->k_team1_id = $team1;
             } else {
                 $match->team1_from_match_rank = $team1['from_event_rank'];
                 $match->team1_from_match_index = $team1['from_event_index'];
             }
             //Adding of TEAM-2 of Match
             $team2 = $event[1];
             //If team is directly given ID -- in Round 1 generally
             if (!is_array($team2)) {
                 $match->k_team2_id = $team2;
             } else {
                 $match->team2_from_match_rank = $team2['from_event_rank'];
                 $match->team2_from_match_index = $team2['from_event_index'];
             }
             $match->match_index = $i++;
             $tournament->matches()->create($match->toArray());
         }
         $starts_at_glob = $starts_at_glob->addDay();
         $starts_at_glob = $starts_at_glob->subHour(4);
     }
     return "New DE tournaments roasted!\n";
 }