<!DOCTYPE html>
<html lang="es">

<head>
    <meta charset="UTF-8">
    <title><?= isset($game) ? 'Editar Juego' : 'Crear Juego' ?></title>
    <link rel="stylesheet" href="../public/css/style.css">
</head>

<body>
    <div class="wb">
        <div class="head">
            <div class="tittle"><?= $game['desc'] ?? 'Crear Juego' ?></div>
            <a href="../public/tournament.php?id=<?= $_GET['tournament'] ?>#games">
                <div class="pic iClose"></div>
            </a>
        </div>
        <div class="scroll-container">
            <section class="section" id="section1">
                <form action="../public/game.php?action=<?= isset($game) ? 'update' : 'store' ?>" method="POST" class="form">
                    <div class="formItem">
                        <input type="text" class="formInput" id="desc" placeholder="Nombre" required autocomplete="off" name="desc" value="<?= $game['desc'] ?? '' ?>" />
                        <label for="desc" class="formLabel">Nombre</label>
                    </div>
                    <div class="formItem">
                        <input list="team1-list" name="t1" id="t1" class="formInput" value="<?= htmlspecialchars($game['t1'] ?? '') ?>">
                        <label for="t1" class="formLabel">
                            <?php
                            if (isset($game['t1'])) {
                                foreach ($teams as $team) {
                                    if ($team['id'] == $game['t1']) {
                                        echo htmlspecialchars($team['p1_lastname'] . ' / ' . $team['p2_lastname']);
                                        break;
                                    }
                                }
                            } else {
                                echo isset($team['p1_lastname']) ? htmlspecialchars($team['p1_lastname'] . ' / ') : 'Jugador 1 / ';
                                echo isset($team['p2_lastname']) ? htmlspecialchars($team['p2_lastname']) : 'Jugador 2';
                            }
                            ?>
                        </label>

                        <datalist id="team1-list">
                            <?php foreach ($teams as $team): ?>
                                <option value="<?= htmlspecialchars($team['id']) ?>">
                                    <?= htmlspecialchars($team['p1_lastname'] . ' / ' . $team['p2_lastname']) ?>
                                </option>
                            <?php endforeach; ?>
                        </datalist>
                    </div>
                    <div class="formItem">
                        <input list="team1-list" name="t2" id="t2" class="formInput" value="<?= htmlspecialchars($game['t2'] ?? '') ?>">
                        <label for="t2" class="formLabel">
                            <?php
                            if (isset($game['t2'])) {
                                foreach ($teams as $team) {
                                    if ($team['id'] == $game['t2']) {
                                        echo htmlspecialchars($team['p1_lastname'] . ' / ' . $team['p2_lastname']);
                                        break;
                                    }
                                }
                            } else {
                                echo isset($team['p1_lastname']) ? htmlspecialchars($team['p1_lastname'] . ' / ') : 'Jugador 1 / ';
                                echo isset($team['p2_lastname']) ? htmlspecialchars($team['p2_lastname']) : 'Jugador 2';
                            }
                            ?>
                        </label>

                        <datalist id="team1-list">
                            <?php foreach ($teams as $team): ?>
                                <option value="<?= htmlspecialchars($team['id']) ?>">
                                    <?= htmlspecialchars($team['p1_lastname'] . ' / ' . $team['p2_lastname']) ?>
                                </option>
                            <?php endforeach; ?>
                        </datalist>
                    </div>


                    <div class="formItem">
                        <label for="date">Fecha:</label>
                        <input type="datetime-local" class="formInput" id="date" name="date" value="<?= $game['date'] ?? '' ?>" step="60" required>
                    </div>

                    <div class="formItem">
                        <label for="date">Termino:</label>
                        <input type="datetime-local" class="formInput" id="end" name="end" value="<?= $game['end'] ?? '' ?>" step="60" required>
                    </div>

                    <!-- Selector de Club -->
                    <div class="formItem">
                        <input list="club-list" name="club" id="club" class="formInput" required value="<?= $game['club'] ?? '' ?>" autocomplete="off">
                        <label for="club" class="formLabel">Club</label>
                        <datalist id="club-list">
                            <?php foreach ($clubs as $club): ?>
                                <option value="<?= htmlspecialchars($club['id']) ?>">
                                    <?= htmlspecialchars($club['name']) ?>
                                </option>
                            <?php endforeach; ?>
                        </datalist>
                    </div>

                    <!-- Selector de Court -->
                    <div class="formItem">
                        <input list="court-list" name="court" id="court" class="formInput" required value="<?= $game['court'] ?? '' ?>" autocomplete="off">
                        <label for="court" class="formLabel">Court</label>
                        <datalist id="court-list">
                            <?php if (!empty($courts)): ?>
                                <?php foreach ($courts as $court): ?>
                                    <option value="<?= htmlspecialchars($court['id']) ?>">
                                        <?= htmlspecialchars($court['name']) ?>
                                    </option>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </datalist>
                    </div>
                    <div class="formItem">
                        <select name="groups" id="groups" class="formSelect" autocomplete="off">
                            <option value="1" <?= isset($game['groups']) && $game['groups'] == '1' ? 'selected' : '' ?>>Grupo 1</option>
                            <option value="2" <?= isset($game['groups']) && $game['groups'] == '2' ? 'selected' : '' ?>>Grupo 2</option>
                            <option value="3" <?= isset($game['groups']) && $game['groups'] == '3' ? 'selected' : '' ?>>Grupo 3</option>
                            <option value="4" <?= isset($game['groups']) && $game['groups'] == '4' ? 'selected' : '' ?>>Grupo 4</option>
                            <option value="PO" <?= isset($game['groups']) && $game['groups'] === 'PO' ? 'selected' : '' ?>>PlayOffs</option>
                            <option value="F" <?= isset($game['groups']) && $game['groups'] === 'FF' ? 'selected' : '' ?>>Final</option>
                            <option value="FO" <?= isset($game['groups']) && $game['groups'] === 'FO' ? 'selected' : '' ?>>Final Oro</option>
                        </select>
                        <label for="groups" class="formLabel">Grupo</label>
                    </div>

                    <div class="sets">
                        <?php
                        function createSelect($name, $selectedValue)
                        {
                            echo "<select style='color: white;' name='$name' class='set'>";
                            echo "<option value='' " . (is_null($selectedValue) || $selectedValue === '' ? 'selected' : '') . "></option>";

                            for ($i = 0; $i <= 15; $i++) {
                                $selected = ($selectedValue !== null && $selectedValue !== '' && $selectedValue == $i) ? 'selected' : '';
                                echo "<option value='$i' $selected>$i</option>";
                            }
                            echo "</select>";
                        }

                        // Crear los selects para el primer equipo
                        createSelect('s1t1', $game['s1t1'] ?? null);
                        createSelect('s2t1', $game['s2t1'] ?? null);
                        createSelect('s3t1', $game['s3t1'] ?? null);
                        ?>
                    </div>

                    <div class="sets">
                        <?php
                        // Crear los selects para el segundo equipo
                        createSelect('s1t2', $game['s1t2'] ?? null);
                        createSelect('s2t2', $game['s2t2'] ?? null);
                        createSelect('s3t2', $game['s3t2'] ?? null);
                        ?>
                    </div>
                    <?php if ($_GET['tournament']): ?>
                        <input type="hidden" name="tournament" value="<?= $_GET['tournament'] ?>" />
                    <?php endif; ?>
                    <?php if (isset($game)): ?>
                        <input type="hidden" name="id" value="<?= $game['id'] ?>" />
                    <?php endif; ?>
                    <button class="button-85" role="button" value="Submit" type="submit">Guardar</button>
                </form>
            </section>
        </div>
    </div>
</body>

<script>
    document.getElementById('date').addEventListener('change', function() {
        document.getElementById('end').value = document.getElementById('date').value;
    })
    document.getElementById('club').addEventListener('change', function() {
        const clubCode = this.value;

        fetch(`../controllers/api/get_courts.php?club_code=${clubCode}`)
            .then(response => response.json())
            .then(data => {
                const courtList = document.getElementById('court-list');
                courtList.innerHTML = ''; // Limpiar el datalist de courts

                data.forEach(court => {
                    const option = document.createElement('option');
                    option.value = court.id;
                    option.text = court.name;
                    courtList.appendChild(option);
                });
            })
            .catch(error => {
                console.error('Error fetching courts:', error);
            });
    });
</script>
<script>
    const game = <?= json_encode($game, JSON_HEX_TAG); ?>;
    console.log(game);
    const team = <?= json_encode($team, JSON_HEX_TAG); ?>;
    console.log(team);
</script>

</html>