<?php
require_once '../utils/helpers.php';
?>
<!DOCTYPE html>
<html lang="es">

<head>
    <meta charset="UTF-8">
    <meta property="og:title" content="<?= htmlspecialchars(($tournament['name'] ?? '')) ?>">
    <meta property="og:description" content="¡Descubre más sobre este torneo de pádel!">
    <meta property="og:image" content="https://padelbull.cl/app/public/img/tournament/banner-<?= htmlspecialchars(($tournament['pic'] ?? '')) ?>.webp">
    <meta property="og:url" content="https://padelbull.cl/app/tournament?id=<?= htmlspecialchars(($tournament['id'] ?? '')) ?>">
    <meta property="og:type" content="website">
    <meta property="og:site_name" content="PadelBull">
    <title><?= htmlspecialchars(($tournament['name'] ?? '')) ?></title>
    <link rel="stylesheet" href="../public/css/style.css">
    <link rel="stylesheet" href="../public/css/tournament.css">
</head>

<body>
    <div class="head displayRowSpaceBetween">
        <div class="displayRow">
            <?php if (!empty($entity['pic'])): ?>
                <img class="icon" src="../public/img/entity/<?= htmlspecialchars($entity['pic']) ?>.webp" alt="<?= htmlspecialchars($entity['name']) ?>" loading="lazy">
            <?php endif; ?>
            <div>
                <div class="tittle"><?= htmlspecialchars($tournament['name'] ?? '') ?></div>
                <div class="subTittle"><?= htmlspecialchars(($club['name'] ?? '')) ?></div>
            </div>
        </div>
        <a href="../public/manager.php?id=<?= htmlspecialchars(($entity['id'] ?? '')) ?>">
            <div class="pic img iClose"></div>
        </a>
    </div>
    <div class="wb img">
        <?php if (!empty($ads)): ?>
            <div class="carruselImg displayRow" id="adsOutput">
                <div class="carruselImg-track">
                    <?php foreach ($ads as $ad): ?>
                        <a href="<?= htmlspecialchars($ad['link']) ?>">
                            <img src="../public/img/ads/<?= htmlspecialchars($ad['ad_name']) ?>.webp" alt="<?= htmlspecialchars($ad['sponsor_name']) ?>" loading="lazy">
                        </a>
                    <?php endforeach; ?>
                    <?php foreach ($ads as $ad): ?>
                        <a href="<?= htmlspecialchars($ad['link']) ?>">
                            <img src="../public/img/ads/<?= htmlspecialchars($ad['ad_name']) ?>.webp" alt="<?= htmlspecialchars($ad['sponsor_name']) ?>" loading="lazy">
                        </a>
                    <?php endforeach; ?>
                </div>
            </div>
        <?php endif; ?>

        <?php
        $finalGame = null;
        $currentDateTime = new DateTime();

        foreach ($games as $game) {
            $endDateTime = new DateTime($game['end']);
            if (($game['groups'] === 'F' || $game['groups'] === 'FO') && $endDateTime < $currentDateTime) {
                $finalGame = $game;
                break;
            }
        }

        function calculateWinner($game)
        {
            $setsWonTeam1 = 0;
            $setsWonTeam2 = 0;

            if (!is_null($game['s1t1']) && !is_null($game['s1t2'])) {
                $setsWonTeam1 += $game['s1t1'] > $game['s1t2'] ? 1 : 0;
                $setsWonTeam2 += $game['s1t2'] > $game['s1t1'] ? 1 : 0;
            }
            if (!is_null($game['s2t1']) && !is_null($game['s2t2'])) {
                $setsWonTeam1 += $game['s2t1'] > $game['s2t2'] ? 1 : 0;
                $setsWonTeam2 += $game['s2t2'] > $game['s2t1'] ? 1 : 0;
            }
            if (!is_null($game['s3t1']) && !is_null($game['s3t2'])) {
                $setsWonTeam1 += $game['s3t1'] > $game['s3t2'] ? 1 : 0;
                $setsWonTeam2 += $game['s3t2'] > $game['s3t1'] ? 1 : 0;
            }

            return $setsWonTeam1 > $setsWconTeam2 ? 'team1' : 'team2';
        }

        function calculateTeamStats($games, $teamId)
        {
            $matchesWon = 0;
            $matchesLost = 0;
            $setsWon = 0;
            $setsLost = 0;

            foreach ($games as $game) {
                $setsWonInGame = 0;
                $setsLostInGame = 0;
                if (!is_null($game['s1t1']) && !is_null($game['s1t2'])) {
                    if ($game['s1t1'] > $game['s1t2']) {
                        $setsWonInGame += $game['t1'] == $teamId ? 1 : 0;
                        $setsLostInGame += $game['t2'] == $teamId ? 1 : 0;
                    } elseif ($game['s1t2'] > $game['s1t1']) {
                        $setsWonInGame += $game['t2'] == $teamId ? 1 : 0;
                        $setsLostInGame += $game['t1'] == $teamId ? 1 : 0;
                    }
                }

                if (!is_null($game['s2t1']) && !is_null($game['s2t2'])) {
                    if ($game['s2t1'] > $game['s2t2']) {
                        $setsWonInGame += $game['t1'] == $teamId ? 1 : 0;
                        $setsLostInGame += $game['t2'] == $teamId ? 1 : 0;
                    } elseif ($game['s2t2'] > $game['s2t1']) {
                        $setsWonInGame += $game['t2'] == $teamId ? 1 : 0;
                        $setsLostInGame += $game['t1'] == $teamId ? 1 : 0;
                    }
                }

                if (!is_null($game['s3t1']) && !is_null($game['s3t2'])) {
                    if ($game['s3t1'] > $game['s3t2']) {
                        $setsWonInGame += $game['t1'] == $teamId ? 1 : 0;
                        $setsLostInGame += $game['t2'] == $teamId ? 1 : 0;
                    } elseif ($game['s3t2'] > $game['s3t1']) {
                        $setsWonInGame += $game['t2'] == $teamId ? 1 : 0;
                        $setsLostInGame += $game['t1'] == $teamId ? 1 : 0;
                    }
                }
                if ($setsWonInGame > $setsLostInGame) {
                    $matchesWon++;
                } elseif ($setsLostInGame > $setsWonInGame) {
                    $matchesLost++;
                }

                $setsWon += $setsWonInGame;
                $setsLost += $setsLostInGame;
            }

            return [
                'matchesWon' => $matchesWon,
                'matchesLost' => $matchesLost,
                'setsWon' => $setsWon,
                'setsLost' => $setsLost
            ];
        }

        if ($finalGame) {
            $winnerTeam = calculateWinner($finalGame);
            $winnerTeamId = $winnerTeam === 'team1' ? $finalGame['t1'] : $finalGame['t2'];

            $stats = calculateTeamStats($games, $winnerTeamId);
        } else {
            $winnerTeam = null;
            $winnerTeamId = null;
            $stats = [];
        }
        ?>
        <?php if ($finalGame): ?>
            <img src="../public/img/padelBall.webp" class="winnerBall img rotate" loading="lazy">
            <div class="winners displayColumnCenter">
                <div class="circle radiusCircle displayColumnCenter displayContentCenter">
                    <div class="container displayColumnCenter">
                        <div class="tittle">PRIMER LUGAR</div>
                        <div class="players displayRowSpaceBetween">
                            <?php if ($winnerTeam === 'team1'): ?>
                                <a href="../public/player.php?id=<?= htmlspecialchars($finalGame['p1']) ?>">
                                    <div class="player displayColumnCenter">
                                        <img class="pic radiusCircle" src="../public/img/user/player_<?= htmlspecialchars($finalGame['p1_pic'] . '.webp' ?? 'user.png') ?>" loading="lazy">
                                        <div class="name">
                                            <span class="first-row"><?= htmlspecialchars($finalGame['p1_pNombre']) ?></span>
                                            <span class="last-row"><?= htmlspecialchars($finalGame['p1_pApellido']) ?></span>
                                        </div>
                                    </div>
                                </a>
                                <a href="../public/player.php?id=<?= htmlspecialchars($finalGame['p2']) ?>">
                                    <div class="player displayColumnCenter">
                                        <img class="pic radiusCircle" src="../public/img/user/player_<?= htmlspecialchars($finalGame['p2_pic'] . '.webp' ?? 'user.png') ?>" loading="lazy">
                                        <div class="name">
                                            <span class="first-row"><?= htmlspecialchars($finalGame['p2_pNombre']) ?></span>
                                            <span class="last-row"><?= htmlspecialchars($finalGame['p2_pApellido']) ?></span>
                                        </div>
                                    </div>
                                </a>
                            <?php else: ?>
                                <a href="../public/player.php?id=<?= htmlspecialchars($finalGame['p3']) ?>">
                                    <div class="player displayColumnCenter">
                                        <img class="pic radiusCircle" src="../public/img/user/player_<?= htmlspecialchars($finalGame['p3_pic'] . '.webp' ?? 'user.png') ?>" loading="lazy">
                                        <div class="name">
                                            <span class="first-row"><?= htmlspecialchars($finalGame['p3_pNombre']) ?></span>
                                            <span class="last-row"><?= htmlspecialchars($finalGame['p3_pApellido']) ?></span>
                                        </div>
                                    </div>
                                </a>
                                <a href="../public/player.php?id=<?= htmlspecialchars($finalGame['p4']) ?>">
                                    <div class="player displayColumnCenter">
                                        <img class="pic radiusCircle" src="../public/img/user/player_<?= htmlspecialchars($finalGame['p4_pic'] . '.webp' ?? 'user.png') ?>" loading="lazy">
                                        <div class="name">
                                            <span class="first-row"><?= htmlspecialchars($finalGame['p4_pNombre']) ?></span>
                                            <span class="last-row"><?= htmlspecialchars($finalGame['p4_pApellido']) ?></span>
                                        </div>
                                    </div>
                                </a>
                            <?php endif; ?>
                        </div>
                        <div class="stats displayRowSpaceEvenly">
                            <div class="item">
                                <div class="value"><?= htmlspecialchars($stats['matchesWon']) ?></div>
                                <div class="name">
                                    <span class="first-row">Partidos</span>
                                    <span class="last-row">Ganados</span>
                                </div>
                            </div>
                            <div class="item">
                                <div class="value"><?= htmlspecialchars($stats['matchesLost']) ?></div>
                                <div class="name">
                                    <span class="first-row">Partidos</span>
                                    <span class="last-row">Perdidos</span>
                                </div>
                            </div>
                            <div class="item">
                                <div class="value"><?= htmlspecialchars($stats['setsWon']) ?></div>
                                <div class="name">
                                    <span class="first-row">Sets</span>
                                    <span class="last-row">Ganados</span>
                                </div>
                            </div>
                            <div class="item">
                                <div class="value"><?= htmlspecialchars($stats['setsLost']) ?></div>
                                <div class="name">
                                    <span class="first-row">Sets</span>
                                    <span class="last-row">Perdidos</span>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="border-circle"></div>
            </div>
            <div class="winnersAir"></div>
        <?php endif; ?>
        <?php if (!empty($games)): ?>
    <div class="playOffs" id="playOffs">
        <div class="tittle">PLAYOFFS</div>
        <?php foreach ($games as $game): ?>
            <?php if (!is_numeric($game['groups'])):
                $setsT1 = ($game['s1t1'] > $game['s1t2']) + ($game['s2t1'] > $game['s2t2']) + ($game['s3t1'] > $game['s3t2']);
                $setsT2 = ($game['s1t1'] < $game['s1t2']) + ($game['s2t1'] < $game['s2t2']) + ($game['s3t1'] < $game['s3t2']);
                $isDraw = $setsT1 === $setsT2; // Verifica si es un empate
                $winner = !$isDraw && $setsT1 > $setsT2; // Determina si hay un ganador
            ?>
                <a href="../public/game.php?id=<?= $game['id'] ?>&tournament=<?= $tournament['id'] ?>">
                    <div class="gameCard">
                        <div class="gameCardHead displayRow">
                            <img class="padelBall" loading="lazy" src="../public/img/padelBall.webp">
                            <div class="info displayColumn">
                                <div class="date"><?= formatDateAbbreviated($game['date']) ?></div>
                                <div class="name"><?= htmlspecialchars($game['desc']) ?></div>
                            </div>
                        </div>
                        <div class="gameCardBody displayRowSpaceBetween">
                            <div class="players displayColumn">
                                <?php for ($i = 1; $i <= 2; $i++): ?>
                                    <div class="team displayRow">
                                        <div class="pics displayRow">
                                            <img class="pic radiusCircle <?= $isDraw ? '' : ($i === 1 ? ($winner ? 'winner' : '') : ($winner ? '' : 'winner')) ?>" 
                                                 src="../public/img/user/<?= $game['p' . ($i * 2 - 1) . '_pic'] ? 'player_' . htmlspecialchars($game['p' . ($i * 2 - 1) . '_pic']) . '.webp' : 'user.png' ?>" 
                                                 loading="lazy">
                                            <img class="pic radiusCircle <?= $isDraw ? '' : ($i === 1 ? ($winner ? 'winner' : '') : ($winner ? '' : 'winner')) ?>" 
                                                 src="../public/img/user/<?= $game['p' . ($i * 2) . '_pic'] ? 'player_' . htmlspecialchars($game['p' . ($i * 2) . '_pic']) . '.webp' : 'user.png' ?>" 
                                                 loading="lazy">
                                        </div>
                                        <div class="names displayColumn">
                                            <div class="name <?= $isDraw ? '' : ($i === 1 ? ($winner ? 'winner' : '') : ($winner ? '' : 'winner')) ?>">
                                                <?= htmlspecialchars($game['p' . ($i * 2 - 1) . '_pNombre']) . ' ' . htmlspecialchars($game['p' . ($i * 2 - 1) . '_pApellido']) ?>
                                            </div>
                                            <div class="name <?= $isDraw ? '' : ($i === 1 ? ($winner ? 'winner' : '') : ($winner ? '' : 'winner')) ?>">
                                                <?= htmlspecialchars($game['p' . ($i * 2) . '_pNombre']) . ' ' . htmlspecialchars($game['p' . ($i * 2) . '_pApellido']) ?>
                                            </div>
                                        </div>
                                    </div>
                                <?php endfor; ?>
                            </div>
                            <div class="sets displayColumn">
                                <div class="set <?= $isDraw ? '' : ($winner ? 'winner' : '') ?>"><?= $game['s1t1'] . ' ' . $game['s2t1'] . ' ' . $game['s3t1']; ?></div>
                                <div class="set <?= $isDraw ? '' : ($winner ? '' : 'winner') ?>"><?= $game['s1t2'] . ' ' . $game['s2t2'] . ' ' . $game['s3t2']; ?></div>
                            </div>
                        </div>
                    </div>
                </a>
            <?php endif; ?>
        <?php endforeach; ?>
    </div>
<?php endif; ?>

        <?php if (!empty($teams)): ?>
    <div class="groups displayColumnCenter">
        <div class="tittle">FASE DE GRUPOS</div>
        <?php ksort($teams); // Ordena los grupos por clave de manera ascendente ?>
        <?php foreach ($teams as $group => $groupTeams): ?>
            <div class="group">Grupo <?= htmlspecialchars($group) ?></div>
            <table class="stdTable">
                <thead>
                    <tr>
                        <th>Equipo</th>
                        <th></th>
                        <th onclick="alert('Puntaje')">P</th>
                        <th onclick="alert('Victorias')">V</th>
                        <th onclick="alert('Derrotas')">D</th>
                        <th onclick="alert('Empates')">E</th>
                        <th onclick="alert('Sets Ganados')">SG</th>
                        <th onclick="alert('Sets Perdidos')">SP</th>
                        <th onclick="alert('Diferencia')">D</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($groupTeams as $team): ?>
                        <tr>
                            <td>
                                <img src="../public/img/user/<?= htmlspecialchars($team['p1_pic'] ? 'player_' . $team['p1_pic'] . '.webp' : 'user.png') ?>" loading="lazy" class="pic radiusCircle">
                                <img src="../public/img/user/<?= htmlspecialchars($team['p2_pic'] ? 'player_' . $team['p2_pic'] . '.webp' : 'user.png') ?>" loading="lazy" class="pic radiusCircle">
                            </td>
                            <td>
                                <div class="displayColumnLeft name">
                                    <div><?= htmlspecialchars($team['p1_lastname']) ?></div>
                                    <div><?= htmlspecialchars($team['p2_lastname']) ?></div>
                                </div>
                            </td>
                            <td><?= htmlspecialchars($team['points']) ?></td>
                            <td><?= htmlspecialchars($team['wins']) ?></td>
                            <td><?= htmlspecialchars($team['losses']) ?></td>
                            <td><?= htmlspecialchars($team['draws']) ?></td>
                            <td><?= htmlspecialchars($team['sets_won']) ?></td>
                            <td><?= htmlspecialchars($team['sets_lost']) ?></td>
                            <td><?= htmlspecialchars($team['goal_difference']) ?></td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
            <div class="gameBtn radiusCircle" onclick="toggleGames(<?= htmlspecialchars($group) ?>)" id="toggleButton<?= htmlspecialchars($group) ?>">Ver Partidos</div>
            <div id="gamesGroup<?= htmlspecialchars($group) ?>" class="gamesContainer hidden">
                <?php foreach ($games as $game): ?>
                    <?php 
                    if ($game['groups'] == $group):
                        $isDraw = ($game['s1t1'] === null || $game['s1t1'] == 0) && ($game['s1t2'] === null || $game['s1t2'] == 0) &&
                                  ($game['s2t1'] === null || $game['s2t1'] == 0) && ($game['s2t2'] === null || $game['s2t2'] == 0) &&
                                  ($game['s3t1'] === null || $game['s3t1'] == 0) && ($game['s3t2'] === null || $game['s3t2'] == 0);

                        if (!$isDraw) {
                            $setsT1 = ($game['s1t1'] > $game['s1t2']) + ($game['s2t1'] > $game['s2t2']) + ($game['s3t1'] > $game['s3t2']);
                            $setsT2 = ($game['s1t1'] < $game['s1t2']) + ($game['s2t1'] < $game['s2t2']) + ($game['s3t1'] < $game['s3t2']);
                            $winner = $setsT1 > $setsT2;
                        } else {
                            $winner = null;
                        }
                    ?>
                        <a href="../public/game.php?id=<?= $game['id'] ?>&tournament=<?= $tournament['id'] ?>">
                            <div class="gameCard">
                                <div class="gameCardHead displayRow">
                                    <img class="padelBall" loading="lazy" src="../public/img/padelBall.webp">
                                    <div class="info displayColumn">
                                        <div class="date"><?= formatDateAbbreviated($game['date']) ?></div>
                                        <div class="name"><?= htmlspecialchars($game['desc']) ?></div>
                                    </div>
                                </div>
                                <div class="gameCardBody displayRowSpaceBetween">
                                    <div class="players displayColumn">
                                        <?php for ($i = 1; $i <= 2; $i++): ?>
                                            <div class="team displayRow">
                                                <div class="pics displayRow">
                                                    <img class="pic radiusCircle <?= $winner === null ? '' : ($i === 1 ? ($winner ? 'winner' : '') : ($winner ? '' : 'winner')) ?>" src="../public/img/user/<?= $game['p' . ($i * 2 - 1) . '_pic'] ? 'player_' . htmlspecialchars($game['p' . ($i * 2 - 1) . '_pic']) . '.webp' : 'user.png' ?>" loading="lazy">
                                                    <img class="pic radiusCircle <?= $winner === null ? '' : ($i === 1 ? ($winner ? 'winner' : '') : ($winner ? '' : 'winner')) ?>" src="../public/img/user/<?= $game['p' . ($i * 2) . '_pic'] ? 'player_' . htmlspecialchars($game['p' . ($i * 2) . '_pic']) . '.webp' : 'user.png' ?>" loading="lazy">
                                                </div>
                                                <div class="names displayColumn">
                                                    <div class="name <?= $winner === null ? '' : ($i === 1 ? ($winner ? 'winner' : '') : ($winner ? '' : 'winner')) ?>">
                                                        <?= htmlspecialchars($game['p' . ($i * 2 - 1) . '_pNombre']) . ' ' . htmlspecialchars($game['p' . ($i * 2 - 1) . '_pApellido']) ?>
                                                    </div>
                                                    <div class="name <?= $winner === null ? '' : ($i === 1 ? ($winner ? 'winner' : '') : ($winner ? '' : 'winner')) ?>">
                                                        <?= htmlspecialchars($game['p' . ($i * 2) . '_pNombre']) . ' ' . htmlspecialchars($game['p' . ($i * 2) . '_pApellido']) ?>
                                                    </div>
                                                </div>
                                            </div>
                                        <?php endfor; ?>
                                    </div>
                                    <div class="sets displayColumn">
                                        <div class="set <?= $winner === null ? '' : ($setsT1 > $setsT2 ? 'winner' : '') ?>"><?= htmlspecialchars($game['s1t1']) . ' ' . htmlspecialchars($game['s2t1']) . ' ' . htmlspecialchars($game['s3t1']); ?></div>
                                        <div class="set <?= $winner === null ? '' : ($setsT2 > $setsT1 ? 'winner' : '') ?>"><?= htmlspecialchars($game['s1t2']) . ' ' . htmlspecialchars($game['s2t2']) . ' ' . htmlspecialchars($game['s3t2']); ?></div>
                                    </div>
                                </div>
                            </div>
                        </a>
                    <?php endif; ?>
                <?php endforeach; ?>
            </div>
        <?php endforeach; ?>
    </div>
<?php endif; ?>

</body>
<script>
    function toggleGames(group) {
        const gamesContainer = document.getElementById(`gamesGroup${group}`);
        const toggleButton = document.getElementById(`toggleButton${group}`);

        if (gamesContainer.classList.contains('hidden')) {
            gamesContainer.classList.remove('hidden');
            toggleButton.textContent = "Ocultar Partidos";
        } else {
            gamesContainer.classList.add('hidden');
            toggleButton.textContent = "Ver Partidos";
        }
    }
</script>

</html>