<?php 
include ('includes/header.php');
include ('api/APIkey.php');

// nome da tabela
$table_name = "leaguesx";
$page = "hot_sports.php";

// busca dados da API
$json_url = "https://www.thesportsdb.com/api/v1/json/$api_key/all_leagues.php";
$json_data = file_get_contents($json_url);
$leagues = json_decode($json_data, true);

// busca registros da tabela
$res = $db->select($table_name, '*', '', '');

// busca registro para atualização
@$resU = $db->select($table_name, '*', 'id = :id', '', [':id' => $_GET['update']]);

// atualizar registro
if(isset($_POST['submitU'])){
	unset($_POST['submitU']);
	$updateData = $_POST;
	$db->update($table_name, $updateData, 'id = :id',[':id' => $_GET['update']]);
	echo "<script>window.location.href='".$page."?status=1'</script>";
}

// adicionar novo registro
if (isset($_POST['submit'])){
	unset($_POST['submit']);
	$db->insert($table_name, $_POST);
	$db->close();
	echo "<script>window.location.href='".$page."?status=1'</script>";
}

// deletar registro
if(isset($_GET['delete'])){
	$db->delete($table_name, 'id = :id',[':id' => $_GET['delete']]);
	echo "<script>window.location.href='".$page."?status=2'</script>";
}

?>

<?php if (isset($_GET['create'])){?>

<!-- Início do Formulário -->
<div class="container-fluid pt-4 px-4">
    <div class="row g-4">
        <div class="col-12">
            <div class="bg-secondary rounded h-100 p-4">
                <h2 class="mb-4">Criar ID de Liga Quente</h2>
                <form method="post">
                    <div class="mb-3">
                        <label class="form-label">Liga</label>
                        <select name="league" id="league" class="form-select mb-3" onchange="updateLeagueId(this)">
                            <?php foreach ($leagues['leagues'] as $league): ?>
                            <option value="<?= htmlspecialchars($league['strLeague']) ?>"
                                data-idleague="<?= htmlspecialchars($league['idLeague']) ?>"
                                data-idsport="<?= htmlspecialchars($league['strSport']) ?>"
                                <?= (isset($updateData['leagueId']) && $updateData['leagueId'] === $league['strLeague']) ? 'selected' : '' ?>>
                                <?= htmlspecialchars($league['strLeague']) ?>
                            </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label class="form-label" for="leagueId">ID da Liga</label>
                        <input class="form-control" id="leagueId" name="leagueId" placeholder="ID da Liga"
                               type="text" readonly />
                    </div>
                    <div class="mb-3">
                        <label class="form-label" for="lsports">Esporte</label>
                        <input class="form-control" id="lsports" name="lsports" placeholder="Esporte"
                               type="text" readonly />
                    </div>
                    <button type="submit" name="submit" class="btn btn-primary">Salvar</button>
                </form>
            </div>
        </div>
    </div>
</div>

<?php }else{?>

<!-- Início da Tabela -->
<div class="container-fluid pt-4 px-4">
    <div class="row g-4">
        <div class="col-12">
            <div class="bg-secondary rounded h-100 p-4">
                <h2 class="mb-4">Ligas Quentes</h2>
                <div class="text-end">
                    <a type="button" href="./<?=$page ?>?create" class="btn btn-square btn-primary m-2">
                        <i class="fa fa-plus"></i>
                    </a>
                </div>
                <div class="table-responsive">
                    <table class="table">
                        <thead>
                            <tr>
                                <th>#</th>
                                <th>Nome da Liga</th>
                                <th>ID da Liga</th>
                                <th>Esporte</th>
                                <th>Deletar</th>
                            </tr>
                        </thead>
                        <?php foreach ($res as $row) { ?>
                        <tbody>
                            <tr>
                                <td><?=$row['id']; ?></td>
                                <td><?=$row['league'] ?></td>
                                <td><?=$row['leagueId'] ?></td>
                                <td><?=$row['lsports'] ?></td>
                                <td>
                                    <a class="btn btn-square btn-primary m-2" href="#"
                                       data-href="<?php echo $page; ?>?delete=<?php echo $row['id']; ?>"
                                       data-bs-toggle="modal" data-bs-target="#confirm-delete">
                                       <i class="fa fa-trash"></i>
                                    </a>
                                </td>
                            </tr>
                        </tbody>
                        <?php } ?>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>
<!-- Fim da Tabela -->

<?php } ?>

<script>
function updateLeagueId(selectElement) {
    var leagueId = selectElement.options[selectElement.selectedIndex].dataset.idleague;
    var sport = selectElement.options[selectElement.selectedIndex].dataset.idsport;
    document.getElementById('leagueId').value = leagueId;
    document.getElementById('lsports').value = sport;
}

// chama a função ao carregar a página para definir valores iniciais
window.onload = function() {
    var selectElement = document.getElementById('league');
    updateLeagueId(selectElement);
};
</script>

<?php include ('includes/footer.php');?>
<!-- Footer End -->
</body>
</html>
