<?php
$filepath = __FILE__;
$action = $_GET["action"] ?? "index";
$users = array_map(function ($f) { return basename(dirname($f)); }, glob("/home/*/.ring"));

if ($action !== "index") {
    // handle webring redirects
    $me = $_GET["me"] ?? "";
    $i = array_search($me, $users) ?? 0;

    switch ($action) {
    case "random":
        $notme = array_diff($users, [$me]);
        $user = $notme[array_rand($notme)];
        break;
    case "next":
        $user = $users[$i + 1] ?? reset($users);
        break;
    case "prev":
        $user = $users[$i - 1] ?? end($users);
        break;
    default:
        die("invalid action");
    }

    header("Location: https://tilde.team/~$user/");
    die();
}
else {
    // keep this as a string so we can escape it easily with htmlspecialchars()
    $snippet = '<!-- tilde.team ring fragment-->
<div id="newring">
<center>
[<a href="https://tilde.team/ring/?action=prev&me=USERNAME">previous</a>]
[<a href="https://tilde.team/ring/?action=random&me=USERNAME">random</a>]
[<a href="https://tilde.team/ring/?action=next&me=USERNAME">next</a>]
<br>
<a href="https://tilde.team/ring/">how to join this webring</a>
</center>
</div>';

    $title = "webring - how to join";
    include __DIR__ . '/../header.php';
?>
    <h1>how to join the webring</h1>

    <p>this webring can be joined by any user on tilde.team.</p>
    <p>first, add the following links to your page, replacing USERNAME by your username (no ~):</p>

    <pre><?=htmlspecialchars($snippet)?></pre>

    <p>you may edit the code however you want. it should work as long as the URLs are kept in place and have your user in them.</p>

    <p>then create a .ring file in your ~ to be added in the webring:</p>
    <pre>$ touch ~/.ring</pre>

    <h3>explore webring</h3>
    <p><a href="?action=random">jump to random page</a></p>
    <p>all members:</p>
    <ul>
    <?php foreach ($users as $user): ?>
        <li><a href="https://tilde.team/~<?=$user?>/">~<?=$user?></a></li>
    <?php endforeach; ?>
    </ul>

    <p>it will probably work if you copy it to your own <code>~/public_html</code> and adjust the links accordingly.</p>
<?php 
    include __DIR__ . '/../footer.php';
}
