<?php

$webUrl = 'http://mywebsite.com/stats';
$nodeUrl = 'http://mywebsite.com:8089/list';
$nodeKey = 'xxxxxxxxxxxxxxxx';

function cmpPlayers($a, $b)
{
    if ($a->players == $b->players) {
        return 0;
    }
    return ($a->players > $b->players) ? -1 : 1;
}

function cmpNames($a, $b)
{
    return strnatcmp($a->name, $b->name);
}

function get_list($url, $key)
{
    $ch = curl_init();

    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POSTFIELDS, "serverKey=$key");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    $contents = curl_exec($ch);
    curl_close($ch);

    return $contents;
}

function main($web, $url, $key, $sort)
{
    $result = get_list($url, $key);
    $data = json_decode($result);
    $servers = $data->servers;

    if ($sort == "names") {
        usort($servers, "cmpNames");
    } else {
        usort($servers, "cmpPlayers");
    }

    echo "<table>";

    echo "<tr>";
    echo "<td><a href='$web&sort=names'>NAME</a></td>";
    echo "<td><a href='$web&sort=players'>PLAYERS</a></td>";
    echo "<td>CAPACITY</td>";
    echo "<td>MAP</td>";
    echo "<td>COUNTRY</td>";
    echo "<td>MAX PING</td>";
    echo "<td>VERSION</td>";
    echo "</tr>";

    if (count($servers)) {

        foreach ($servers as $idx => $server) {
            $extras = json_decode(base64_decode($server->extras));
            echo "<tr>";
            echo "<td>$server->name</td>";
            echo "<td>$server->players</td>";
            echo "<td>$server->capacity</td>";
            echo "<td>$extras->_map</td>";
            echo "<td>$extras->_country</td>";
            echo "<td>$extras->_maxPing</td>";
            echo "<td>$extras->_version</td>";
            echo "</tr>";
        }
    }
    echo "</table>";
}

$sort = "players";
if (isset($_GET['sort'])) {
    $sort = $_GET['sort'];
}

main($webUrl, $nodeUrl, $nodeKey, $sort);

?>