<?php
namespace App\Controller\Api;
use App\Entity\ConvocatoriaPlayer;
use App\Entity\Customer;
use App\Entity\ExerciseCalendar;
use App\Entity\Game;
use App\Entity\Player;
use App\Entity\PlayerJustification;
use App\Entity\PlayerSportsInjuries;
use App\Entity\SeasonPlayer;
use App\Entity\TrainingAsist;
use App\Helper\UploadedBase64File;
use App\Repository\GameRepository;
use App\Services\Api\PlayerManager;
use App\Services\Api\GameManager;
use DateTime;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
use Psr\Log\LoggerInterface;
class GameController extends ApiController
{
/** @var GameManager $gameManager */
protected $gameManager;
/** @var PlayerManager $playerManager */
protected $playerManager;
/**
* @param GameManager $gameManager
*/
public function __construct(EntityManagerInterface $em, ParameterBagInterface $parameterBag, GameManager $gameManager, PlayerManager $playerManager)
{
parent::__construct($em, $parameterBag);
$this->gameManager = $gameManager;
$this->playerManager = $playerManager;
}
/**
* @param Request $request
* @return JsonResponse
*
* @Route("/game/list", name="api_game_list", methods={"POST"})
*/
public function listGames(Request $request)
{
$prefixFile = $this->getParameter("app.path.game_images");
$baseurl = $request->getScheme() . '://' . $request->getHttpHost() . $request->getBasePath();
$request = $this->transformJsonBody($request);
$games = [];
/** @var Customer $customer */
$customer = $this->getUser();
$season = $customer->getSeasonActive();
if (!empty($season)) {
$filter = [
"season" => $season->getId()
];
/** @var Game $game */
foreach ($this->em->getRepository(Game::class)->findAllActiveGames($filter, ["day" => "DESC"]) as $game) {
$games[] = $game->__toArray($baseurl . $prefixFile . "/");
}
}
return $this->response($games);
}
/**
* @param Request $request
* @return JsonResponse
*
* @Route("/game/list/recycling", name="api_game_list_recycling", methods={"POST"})
*/
public function listGamesRecycling(Request $request)
{
$prefixFile = $this->getParameter("app.path.game_images");
$baseurl = $request->getScheme() . '://' . $request->getHttpHost() . $request->getBasePath();
$request = $this->transformJsonBody($request);
$games = [];
/** @var Customer $customer */
$customer = $this->getUser();
$season = $customer->getSeasonActive();
if (!empty($season)) {
$filter = [
"season" => $season->getId(),
];
/** @var Game $game */
foreach ($this->em->getRepository(Game::class)->findAllRecyclingGames($filter, ["day" => "DESC"]) as $game) {
$games[] = $game->__toArray($baseurl . $prefixFile . "/");
}
}
return $this->response($games);
}
/**
* @param Request $request
* @return JsonResponse
*
* @Route("/game/stats", name="api_game_stats", methods={"POST"})
*/
public function statsGames()
{
$victory = 0;
$tied = 0;
$loser = 0;
$percent = 0;
$total = 0;
$totalPlus = 0;
$future = 0;
$leagueMinutes = 0;
$cupMinutes = 0;
/** @var Customer $customer */
$customer = $this->getUser();
$season = $customer->getSeasonActive();
if (!empty($season)) {
$filter = [
"season" => $season->getId()
];
/** @var Game $game */
foreach ($this->em->getRepository(Game::class)->findBy($filter, ["day" => "DESC"]) as $game) {
if ((!is_null($game->getGoals())) && !is_null($game->getRivalGoals())) {
$gameDate = $game->getDate()->format("Y-m-d-H-i-s");
$currentDate = date("Y-m-d-H-i-s");
$totalPlus++;
if ($currentDate > $gameDate) {
$total++;
// Update competition-specific minutes
$competition = $game->getCompetition();
if ($competition !== null) {
if ($competition->getId() === 1) { // League games
$leagueMinutes += $game->getTimeMatch();
} elseif ($competition->getId() === 2) { // Cup games
$cupMinutes += $game->getTimeMatch();
}
}
if ($game->getGoals() > $game->getRivalGoals())
$victory++;
else if ($game->getGoals() < $game->getRivalGoals())
$loser++;
else {
$tied++;
}
}
}
}
}
$percent = $total > 0 ? round($victory * 100 / $total) : 0;
$stats = [
'victory' => $victory,
'tied' => $tied,
'loser' => $loser,
'percent' => $percent,
'total' => $total,
'future' => $totalPlus - $total,
'leagueMinutes' => $leagueMinutes,
'cupMinutes' => $cupMinutes,
];
return $this->response($stats);
}
/**
* @param Request $request
* @return JsonResponse
*
* @Route("/game/delete/{game}/permanent", name="api_game_delete_permanent", methods={"POST"})
*/
public function deleteGamePermanent(Game $game, Request $request)
{
$prefixFile = $this->getParameter("app.path.game_images");
$baseurl = $request->getScheme() . '://' . $request->getHttpHost() . $request->getBasePath();
$urlFiles = $baseurl . $prefixFile . "/";
$response = $this->gameManager->deleteGamePermanent($game, $urlFiles);
$this->setStatusCode($response["code"]);
return $this->response($response);
}
/**
* @param Request $request
* @return JsonResponse
*
* @Route("/game/delete/{game}", name="api_game_delete", methods={"POST"})
*/
public function deleteGame(Game $game, Request $request)
{
$response = $this->gameManager->deleteGame($game);
$this->setStatusCode($response["code"]);
return $this->response($response);
}
/**
* @param Request $request
* @return JsonResponse
*
* @Route("/game/restore/{game}", name="api_game_restore", methods={"POST"})
*/
public function restoreGame(Game $game, Request $request)
{
$response = $this->gameManager->restoreGame($game);
$this->setStatusCode($response["code"]);
return $this->response($response);
}
/**
* @param Request $request
* @return JsonResponse
*
* @Route("/game/convocatoria/{game}", name="api_game_convocatoria", methods={"POST"})
*/
public function convocatoriaGame(Game $game, Request $request)
{
$players = [];
$prefixFile = $this->getParameter("app.path.player_images");
$baseurl = $request->getScheme() . '://' . $request->getHttpHost() . $request->getBasePath();
/** @var Customer $customer */
$customer = $this->getUser();
$season = $customer->getSeasonActive();
if (!empty($season)) {
$seasonId = $season->getId();
if (!empty($game)) {
$convocatoria = $game->getConvocatoria();
$filter = [
"season" => $seasonId,
];
$convocatoriaPlayerRepository = $this->em->getRepository(ConvocatoriaPlayer::class);
/** @var SeasonPlayer $seasonPlayer */
foreach ($this->em->getRepository(SeasonPlayer::class)->findBy($filter, ["dorsal" => "ASC"]) as $seasonPlayer) {
/** @var Player $player */
$player = $seasonPlayer->getPlayer();
$seasonPlayerActive = !$seasonPlayer->getDeletedAt();
$isActive = $player->getIsActive();
$deletedAt = $player->getDeletedAt();
if ($isActive && $seasonPlayerActive && !$deletedAt) {
$out = [
"id" => $player->getId(),
"seasonPlayer_id" => $seasonPlayer->getId(),
"dorsal" => $seasonPlayer->getDorsal(),
"name" => $player->getName(),
"lastname" => $player->getLastname(),
"position" => !empty($player->getPosition()) ? $player->getPosition()->getSlug() : "",
"image" => !empty($player->getImage()) ? $baseurl . $prefixFile . "/" . $player->getImage() : "",
];
if ($convocatoria) {
/** @var ConvocatoriaPlayer $convocatoriaPlayer */
$convocatoriaPlayer = $convocatoriaPlayerRepository->findOneBy([
"player_id" => $player->getId(),
"convocatoria_id" => $convocatoria->getId(),
]);
if ($convocatoriaPlayer) {
$out = array_merge($out, [
"isOn" => $convocatoriaPlayer->getIsActive(),
"in" => $convocatoriaPlayer->getIsActive(),
"justification_type" => $convocatoriaPlayer->getJustificationType() ? $convocatoriaPlayer->getJustificationType()->getId() : null,
]);
}
if (!$convocatoriaPlayer) {
$out = array_merge($out, [
"isOn" => false,
"in" => false,
"justification_type" => null,
"is_active" => null,
]);
}
}
if (!$convocatoria) {
$out = array_merge($out, [
"isOn" => false,
"in" => false,
"justification_type" => null,
"is_active" => null,
]);
}
$players[] = $out;
}
}
}
}
return $this->response($players);
}
/**
* @param Request $request
* @return JsonResponse
*
* @Route("/game/convocatoria/{game}/edit", name="api_game_convocatoria_edit", methods={"POST"})
*/
public function convocatoriaGameEdit($game, Request $request)
{
$request = $this->transformJsonBody($request);
$players = $request->get('players', null);
if (is_string($players)) {
//INPUT DE JSON
$inputs = json_decode($players, true);
$players = [];
foreach ($inputs as $input) {
if ($input['isOn']) {
$players[] = $input;
}
}
} else if (!is_array($players)) {
$players = [];
}
$response = $this->gameManager->editConvocatoria($game, $players);
$this->setStatusCode($response["code"]);
return $this->response($response);
}
/**
* @param Request $request
* @return JsonResponse
*
* @Route("/game/training/{date}", name="api_game_training", methods={"POST"})
*/
public function trainingGame($date, Request $request)
{
$prefixFile = $this->getParameter("app.path.player_images");
$justificationIconBase = $this->getParameter("app.path.justification_icons");
$baseurl = $request->getScheme() . '://' . $request->getHttpHost() . $request->getBasePath();
$players = [];
/** @var Customer $customer */
$customer = $this->getUser();
$season = $customer->getSeasonActive();
if (!empty($season)) {
$filter = [
"season" => $season->getId(),
"date" => \DateTime::createFromFormat("d-m-Y", $date)
];
/** @var TrainingAsist $trainingAsist */
$trainingAsist = $this->em->getRepository(TrainingAsist::class)->findOneBy($filter);
$filter = [
"season" => $season->getId()
];
/** @var SeasonPlayer $seasonPlayer */
/** @var PlayerJustification $playerjustification */
foreach ($this->em->getRepository(SeasonPlayer::class)->findBy($filter, ["dorsal" => "ASC"]) as $seasonPlayer) {
/** @var Player $player */
$player = $seasonPlayer->getPlayer();
$seasonPlayerActive = !$seasonPlayer->getDeletedAt();
$isActive = $player->getIsActive();
$isDeleted = $player->getDeletedAt();
$justifications = $player->getJustification();
$type = null;
foreach ($justifications as $j) {
if ($j->getDate()->format('d-m-Y') == $date) {
$type = $j->getJustificationType();
}
};
$playerSportInjure = [
[
"prop" => "finish",
"comp" => "=",
"val" => 0
],
[
"prop" => "season",
"comp" => "=",
"val" => $season->getId()
],
[
"prop" => "seasonPlayer",
"comp" => "=",
"val" => $seasonPlayer->getId()
],
[
"prop" => "dateStart",
"comp" => "<=",
"val" => \DateTime::createFromFormat("d-m-Y", $date)->format('Y-m-d')
]
];
$playerInjury = $this->em->getRepository(PlayerSportsInjuries::class)->findOneByOwnCriteria($playerSportInjure);
$filterInjureEnd = [
[
"prop" => "finish",
"comp" => "=",
"val" => 1
],
[
"prop" => "season",
"comp" => "=",
"val" => $season->getId()
],
[
"prop" => "seasonPlayer",
"comp" => "=",
"val" => $seasonPlayer->getId()
],
[
"prop" => "dateStart",
"comp" => "<=",
"val" => \DateTime::createFromFormat("d-m-Y", $date)->format('Y-m-d')
],
[
"prop" => "dateEnd",
"comp" => ">=",
"val" => \DateTime::createFromFormat("d-m-Y", $date)->format('Y-m-d')
]
];
if (!$playerInjury) {
$playerInjury = $this->em->getRepository(PlayerSportsInjuries::class)->findOneByOwnCriteria($filterInjureEnd, [
"sort" => 'dateEnd',
"dir" => "desc"
]);
}
$justification = !is_null($type) ? $type->getId() : null;
$justificationType = !is_null($type) ? $type->__toArray($baseurl . $justificationIconBase . "/") : null;
if ($isActive && !$isDeleted && $seasonPlayerActive) {
$players[] = [
"id" => $player->getId(),
"dorsal" => $seasonPlayer->getDorsal(),
"name" => $player->getName(),
"lastname" => $player->getLastname(),
"position" => !empty($player->getPosition()) ? $player->getPosition()->getSlug() : "",
"image" => !empty($player->getImage()) ? $baseurl . $prefixFile . "/" . $player->getImage() : "",
"isOn" => !empty($trainingAsist) && $trainingAsist->getPlayers()->contains($player),
"in" => !empty($trainingAsist) && $trainingAsist->getPlayers()->contains($player),
"justification" => $justificationType,
"disabled" => $playerInjury ? $playerInjury->__toArray() : null,
];
}
}
}
return $this->response($players);
}
/**
* @param Request $request
* @return JsonResponse
*
* @Route("/game/training/{date}/edit", name="api_game_training_edit", methods={"POST"})
*/
public function trainingGameEdit($date, Request $request)
{
$request = $this->transformJsonBody($request);
$players = json_decode($request->get('players', "[]"), true);
$response = $this->gameManager->editTraining($date, $players);
$this->setStatusCode($response["code"]);
return $this->response($response);
}
/**
* @param Request $request
* @return JsonResponse
*
* @Route("/game/trainings/{date}", name="api_game_trainings", methods={"POST"})
*/
public function trainingsGame(DateTime $date)
{
$trainings = [];
/** @var Customer $customer */
$customer = $this->getUser();
$season = $customer->getSeasonActive();
if (!empty($season)) {
$filter = [
[
"prop" => "season",
"comp" => "=",
"val" => $season->getId()
],
[
"prop" => "date",
"comp" => ">=",
"val" => \DateTime::createFromFormat("Y/m/d", $date->format('Y/m/') . "01")
],
[
"prop" => "date",
"comp" => "<=",
"val" => \DateTime::createFromFormat("Y/m/d", $date->modify('+2 month')->format('Y/m/t'))
],
];
/** @var TrainingAsist $trainingAsist */
foreach ($this->em->getRepository(TrainingAsist::class)->findByOwnCriteria($filter) as $trainingAsist) {
$exercises = $this->em->getRepository(ExerciseCalendar::class)->findBy([
'date' => $trainingAsist->getDate(),
'season' => $season
]);
if (count($exercises) || count($trainingAsist->getPlayers())) {
$trainings[] = [
"id" => $trainingAsist->getId(),
"date" => $trainingAsist->getDate()->format("Y-m-d"),
];
} else {
$this->em->remove($trainingAsist);
$this->em->flush();
}
}
}
return $this->response($trainings);
}
/**
* @param Request $request
* @return JsonResponse
*
* @Route("/game/add", name="api_game_add", methods={"POST"})
*/
public function addGame(Request $request)
{
$request = $this->transformJsonBody($request);
$data = $this->getDataFromRequest($request);
$response = $this->gameManager->add($data, $request);
$this->setStatusCode($response["code"]);
if ($response['code'] == 200) {
$prefixFile = $this->getParameter("app.path.game_images");
$baseurl = $request->getScheme() . '://' . $request->getHttpHost() . $request->getBasePath();
$response['game'] = $response['game']->__toArray($baseurl . $prefixFile . "/");
}
return $this->response($response);
}
/**
* @param Request $request
* @return JsonResponse
*
* @Route("/game/edit/{game}", name="api_game_edit", methods={"POST"})
*/
public function editGame($game, Request $request)
{
$request = $this->transformJsonBody($request);
$data = $this->getDataFromRequest($request);
$response = $this->gameManager->edit($game, $data, $request);
$this->setStatusCode($response["code"]);
return $this->response($response);
}
/**
* @param Request $request
* @return JsonResponse
*
* @Route("/game/editlineup/{id}", name="api_game_editlineup", methods={"POST"})
*/
public function editGameLineUp($id, Request $request, LoggerInterface $logger)
{
$lineup = $request->get('lineup');
$lineup = json_decode($lineup, true);
$logger->info("DATA-GAME " . json_encode($lineup) . " " . $id);
$response = $this->gameManager->editLineUp($id, $lineup);
$this->setStatusCode($response["code"]);
return $this->response($response);
}
/**
* @param Request $request
* @return JsonResponse
*
* @Route("/game/edit/alignment/{id}", name="api_game_edit_alignment", methods={"POST"})
*/
public function editAlignment($id, Request $request, LoggerInterface $logger)
{
$request = $this->transformJsonBody($request);
$timePlayers = $request->get('dataPlayers');
$this->playerManager->updateIsTitularByGame($id);
foreach (json_decode($timePlayers) as $timePlayer) {
$player = $this->em->getRepository(Player::class)->find($timePlayer->id);
$data = [
"gameId" => $id,
"minutes" => $timePlayer->minutes,
"yellowCards" => $timePlayer->yellowCards,
"redCards" => $timePlayer->redCards,
"goals" => $timePlayer->goals,
"goalAssistances" => $timePlayer->goalAssistances,
"isTitular" => $timePlayer->isTitular,
"kilometersTraveled" => $timePlayer->kilometersTraveled,
"shotsOnGoal" => $timePlayer->shotsOnGoal,
'stolenBalls' => $timePlayer->stolenBalls,
'penaltiesCommitted' => $timePlayer->penaltiesCommitted,
'forcedPenalties' => $timePlayer->forcedPenalties,
];
$response = $this->playerManager->updateStats($player, $data);
}
$alignment = [
'tactic' => $request->get('tactic'),
'alignment' => $request->get('alignment'),
'captain' => $request->get('captain'),
];
$response = $this->gameManager->editAlignment($id, $alignment);
$this->setStatusCode($response["code"]);
return $this->response($response);
}
/**
* @param Request $request
* @return JsonResponse
*
* @Route("/game/get/alignment/{id}", name="api_game_get_alignment", methods={"POST"})
*/
public function getAlignment($id, Request $request, LoggerInterface $logger)
{
/** @var Customer $customer */
$customer = $this->getUser();
$season = $customer->getSeasonActive();
if (empty($season))
return [
"messageType" => "danger",
"message" => $this->translator->trans('msg.season_dont_active'),
"code" => 403
];
$filter = [
"season" => $season->getId(),
"id" => $id
];
/** @var Game $game */
$game = $this->em->getRepository(Game::class)->findOneBy($filter);
$alignment = $game->getAlignment();
$gameAlignment = [
'alignment' => isset($alignment) ? json_decode($alignment->getAlignment()) : [],
'tactic' => isset($alignment) ? $alignment->getTactic() : "",
];
return $this->response($gameAlignment);
}
/**
* @param Request $request
* @return JsonResponse
*
* @Route("/game/statsSeason", name="api_game_statsSeason", methods={"POST"})
*/
public function assistancePlayer(Request $request)
{
$customer = $this->getUser();
$season = $customer->getSeasonActive();
/** @var GameRepository $gameRepository */
$gameRepository = $this->em->getRepository(Game::class);
$results = $gameRepository->getStatsBySeason($season);
return $this->response($results);
}
/**
* @return JsonResponse
*
* @Route("/game/lineup/{id}/captain/{playerId}/add", name="api_game_lineup_add_captain", methods={"POST"})
*/
public function addGameCaptain($id, $playerId)
{
$response = $this->gameManager->addGameCaptain($id, $playerId);
$this->setStatusCode($response["code"]);
return $this->response($response);
}
/**
* @return JsonResponse
*
* @Route("/game/lineup/{id}/captain", name="api_game_lineup_captain", methods={"POST"})
*/
public function getCaptain($id)
{
$response = $this->gameManager->getGameCaptain($id);
$this->setStatusCode($response["code"]);
return $this->response($response);
}
protected function getDataFromRequest(Request $request)
{
$date = \DateTime::createFromFormat('d/m/Y', $request->get('date', (new \DateTime())->format('d/m/Y')));
$time = $request->get('time');
$date->setTime(0, 0);
if ($time) {
$times = explode(':', $time);
if (count($times) > 1) {
$date->setTime($times[0], $times[1]);
}
}
$data = [
"rival" => $request->get('rival'),
"localityId" => $request->get('locality_id'),
"day" => $request->get('day'),
"date" => $date,
"goals" => $request->get('goals'),
"rivalGoals" => $request->get('rivalGoals'),
"competitionId" => $request->get('competition_id'),
"timeMatch" => $request->get('timeMatch'),
"category" => $request->get('category'),
"shotsGoal" => $request->get('shotsGoal'),
"shotsOpponent" => $request->get('shotsOpponent'),
"cornersFavor" => $request->get('cornersFavor'),
"cornersAgainst" => $request->get('cornersAgainst'),
"penaltiesFavor" => $request->get('penaltiesFavor'),
"penaltiesAgainst" => $request->get('penaltiesAgainst'),
"foulsFavor" => $request->get('foulsFavor'),
"foulsAgainst" => $request->get('foulsAgainst'),
"rivalTactic" => $request->get('rivalTactic'),
"rivalPlayersFormation" => $request->get('rivalPlayersFormation'),
"totalShots" => $request->get('totalShots'),
"totalShotsAgainst" => $request->get('totalShotsAgainst'),
"yellowCards" => $request->get('yellowCards'),
"yellowCardsAgainst" => $request->get('yellowCardsAgainst'),
"redCards" => $request->get('redCards'),
"redCardsAgainst" => $request->get('redCardsAgainst'),
"currentPositionLeague" => $request->get('currentPositionLeague'),
"opponentCurrentPositionLeague" => $request->get('opponentCurrentPositionLeague'),
"pressureRivalId" => $request->get('pressureRivalId') ?? 0,
];
$image = $request->get('image');
if (!empty($image))
$data["image"] = new UploadedBase64File($image, $request->get('imageFilename'));
return $data;
}
/**
* @param Request $request
* @return JsonResponse
*
* @Route("/games/main-stats", name="api_game_season_stats", methods={"POST"})
*/
public function gameMainStats(Request $request)
{
/** @var Customer $customer */
$customer = $this->getUser();
$season = $customer->getSeasonActive();
/** @var GameRepository $gameRepository */
$gameRepository = $this->em->getRepository(Game::class);
$gameLeagueStats = $gameRepository->getGameSeasonStats($season->getId());
return $this->response($gameLeagueStats);
}
}