<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Game;
use App\Tournament;

class TournamentController extends Controller
{
    public function index($args = []) {
        $games = Game::select('titre', 'id_game')->get();
        $args['games']=$games;
        return view('create-tournament', $args);
    }

    public function createTournament(Request $request){
        
        $tournament = new Tournament();
        $tournament->description=$request->input('description');
        $year= $request->input('year-begin');
        $month= $request->input('month-begin');
        $day= $request->input('day-begin');
        $tournament->tournament_date=$year . '-' . $month . '-' . $day;
        $tournament->id_game=$request->input('select-game');
        $tournament->created_at=date('Y-m-d');
        try {
            $tournament->save();
        } catch (Exception $e) {
            return $this->index(['post'=>false]);
        }
        return $this->index(['post'=>true]);
    }

    public function displayTournaments(){
        $tournaments=Tournament::select('description','tournament_date','id_game')->get();
        $games = Game::select('id_game','titre')->get();
        $gamesTitles = [];
        foreach ($games as $game) {
            $gamesTitles[$game->id_game]=$game->titre;
        }
        foreach ($tournaments as $tournament) {
            $tournament->titre=$gamesTitles[$tournament->id_game];
        }
        return view('home', ['tournaments'=>$tournaments]);
    }
}