tippspiel/pfosten/app/Http/Controllers/TippsController.php

128 lines
3.2 KiB
PHP

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Season;
use App\Round;
use App\Game;
use App\Tipp;
use Auth;
use Log;
use DB;
class TippsController extends Controller
{
public function createTipps() {
$activeSeason = Season::getCurrent();
$user=Auth::user();
// Log::info($user->id);
// Log::info("** Start: createTipps for " . $activeSeason->name . "**");
$rounds = Round::all()->where('season_id', '=', $activeSeason->id);
foreach($rounds as $round) {
$games=Game::all()->where('round_id','=',$round->id);
foreach($games as $game) {
// Tipp erzeugen wenn noch nicht vorhanden
$tipp = DB::table('tipps')->where([
['game_id','=',$game->id],
['user_id','=',$user->id]]
)->first();
if (! $tipp) {
//Log::info('Creating missing tip: game_id=' . $game->id . ", user_id=" . $user->id);
$tipp=Tipp::create([
'user_id' => $user->id,
'game_id'=> $game->id,
'score1'=> -1,
'score2'=> -1,
'joker'=> false
]);
$tipp->save();
}
}
}
}
public function index()
{
$activeSeason = Season::getCurrent();
$rounds = null;
$user = Auth::user();
$this->createTipps(); // ggfs. fehlender Tipp Eintraege einfügen
if ($activeSeason) {
$activeSeasonId = Season::getCurrent()->id;
$rounds = Round::all()->where('season_id', '=', $activeSeasonId);
}
return view('tipps.index', compact('rounds', 'activeSeason', 'user'));
}
public function edit($tipp_id) {
$tipp = Tipp::where('id','=',$tipp_id)->first();
$game = Game::where('id','=',$tipp->game_id)->first();
return view('tipps.edit',compact('tipp','game'));
}
public function store() {
// Validate form
$this->validate(request(), [
'id' => 'required',
'score1' => 'required',
'score2' => 'required',
'round_id' => 'required'
]);
$user=Auth::user();
// Fetch, modify, save Tipp
$tipp = Tipp::where('id', request('id'))->first();
$tipp->score1= request('score1');
$tipp->score2= request('score2');
if (request()->has('joker')) {
$tipp->joker=true;
} else {
$tipp->joker=false;
}
$tipp->save();
// Joker gesetzt ? Dann Jokerflag für alle Tipps der selben Runde entfernen
if ($tipp->joker){
$games = DB::table('games')->where('round_id','=',request('round_id'))->get();
foreach($games as $game) {
$tipp = Tipp::where('user_id',$user->id)->where('game_id',$game->id)->first();
if ($tipp->id != request('id')) {
$tipp->joker=false;
$tipp->save();
}
}
}
// Redirect to the Rounds Index
return redirect('/tipps');
}
}