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

// Table name and page
$table_name = "leaguestable";
$page = "leagues_widget.php";

$api_key = getApiKey();

// Fetch the leagues data from the JSON endpoint
$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);

// Group leagues by sports for filtering and sorting leagues A-Z
$sports = [];
foreach ($leagues['leagues'] as $league) {
    $sports[$league['strSport']][] = $league;
}

// Sort leagues by their names (A-Z) within each sport
foreach ($sports as &$leaguesInSport) {
    usort($leaguesInSport, function($a, $b) {
        return strcmp($a['strLeague'], $b['strLeague']);
    });
}

// Fetching table data from the database (already added leagues)
$res = $db->select($table_name, '*', '', '');

// Handling form submission to save a new league
if (isset($_POST['submit'])) {
    $leagueName = $_POST['league'];
    $leagueId = $_POST['leagueId'];
    
    // Ensure both fields are not empty before saving
    if (!empty($leagueName) && !empty($leagueId)) {
        $db->insert($table_name, [
            'league' => $leagueName,
            'leagueId' => $leagueId,
        ]);
        $db->close();
        echo "<script>window.location.href='".$page."?status=1'</script>"; // Redirect after successful submission
    }
}

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

<div class="modal fade" id="confirm-delete" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"
    aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content" style="background-color: black;">
            <div class="modal-header">
                <h2 style="color: white;">Confirm</h2>
            </div>
            <div class="modal-body" style="color: white;">
                Do you really want to delete?
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-primary" data-dismiss="modal">Cancel</button>
                <a style="color: white;" class="btn btn-danger btn-ok">Delete</a>
            </div>
        </div>
    </div>
</div>

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

<div class="col-md-12 mx-auto ctmain-table">
    <div class="card-body">
        <div class="card ctcard">
            <div class="card-header card-header-warning">
                <center>
                    <h2><i class="icon icon-bullhorn"></i> Create League ID</h2>
                </center>
            </div>

            <div class="card-body">
                <div class="col-12">
                    <h3>Select Sport to View Leagues</h3>
                </div>

                <!-- Dropdown for Sports -->
                <div class="form-group">
                    <label for="sportSelect">Choose a Sport:</label>
                    <select id="sportSelect" class="form-control" onchange="showLeagues(this)" style="background-color: #333; color: white; border: 1px solid #555;">
                        <option value="">Select a sport</option>
                        <?php foreach (array_keys($sports) as $sport): ?>
                        <option value="<?= htmlspecialchars($sport) ?>"><?= htmlspecialchars($sport) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <!-- League Dropdown will appear after choosing a sport -->
                <form method="post">
                    <div class="form-group" id="leagueContainer" style="display:none;">
                        <label for="leagueSelect">Choose a League:</label>
                        <select name="league" id="leagueSelect" class="form-control" onchange="updateLeagueId(this)" style="background-color: #333; color: white; border: 1px solid #555;">
                        </select>
                    </div>

                    <div class="form-group">
                        <label class="form-label" for="leagueId">League ID</label>
                        <input class="form-control" id="leagueId" name="leagueId" placeholder="League ID" type="text" readonly />
                    </div>

                    <div class="form-group ctinput">
                        <center>
                            <button class="btn btn-info" name="submit" type="submit">
                                <i class="icon icon-check"></i> Submit
                            </button>
                        </center>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<?php 
} else {
?>

<div class="col-md-12 mx-auto ctmain-table">
    <div class="card-body">
        <div class="card ctcard">
            <div class="card-header card-header-warning">
                <center>
                    <h2><i class="icon icon-commenting"></i> League Widget</h2>
                </center>
            </div>
            <div class="card-body">
                <div class="col-12">
                    <center>
                        <a id="button" href="./<?=$page ?>?create" class="btn btn-info">Add New League</a>
                    </center>
                </div>
                <br>
                <div class="table-responsive">
                    <table class="table table-striped table-sm">
                        <thead style="color:white!important">
                            <tr>
                                <th>League name</th>
                                <th>League ID</th>
                                <th>Delete</th>
                            </tr>
                        </thead>
                        <?php foreach ($res as $row) { ?>
                        <tbody>
                            <tr>
                                <td><?=$row['league'] ?></td>
                                <td><?=$row['leagueId'] ?></td>
                                <td>
                                    &nbsp&nbsp&nbsp
                                    <a class="btn btn-danger btn-ok" href="#"
                                        data-href="<?=$page ?>?delete=<?=$row['id'] ?>" data-toggle="modal"
                                        data-target="#confirm-delete"><i class="fa fa-trash-o"></i></a>
                                </td>
                            </tr>
                        </tbody>
                        <?php } ?>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<?php } ?>

<script>
// Data for all sports and leagues
const sportsData = <?= json_encode($sports) ?>;

function updateLeagueId(selectElement) {
    var leagueId = selectElement.options[selectElement.selectedIndex].dataset.idleague;
    document.getElementById('leagueId').value = leagueId;
}

// Show leagues when a sport is selected
function showLeagues(selectElement) {
    var sport = selectElement.value;
    var leagueSelect = document.getElementById('leagueSelect');
    var leagueContainer = document.getElementById('leagueContainer');

    leagueSelect.innerHTML = ''; // Clear any previous leagues

    if (sport && sportsData[sport]) {
        sportsData[sport].forEach(function(league) {
            var option = document.createElement('option');
            option.value = league.strLeague;
            option.text = league.strLeague;
            option.dataset.idleague = league.idLeague;
            leagueSelect.appendChild(option);
        });

        leagueContainer.style.display = 'block'; // Show the league dropdown
    } else {
        leagueContainer.style.display = 'none'; // Hide the league dropdown if no sport is selected
    }
}

window.onload = function() {
    var selectElement = document.getElementById('leagueSelect');
    updateLeagueId(selectElement);
};
</script>

<?php include ('includes/footer.php'); ?>