<?php

require_once $_SERVER['DOCUMENT_ROOT'] . "/includes/init.inc"; global $title; global $isLoggedIn;

if (isset($_POST['deleteAction'])) {
    $data = json_decode(file_get_contents($_SERVER['DOCUMENT_ROOT'] . "/includes/data/actions/actions.json"), true);

    $selected = null;
    $selectedIndex = -1;
    $id = $_POST['action'];

    foreach ($data as $index => $item) {
        if ($item["id"] === $id) {
            $selectedIndex = $index;
            $selected = $item;
            break;
        }
    }

    if ($selected === null) {
        header("Location: /-/actions");
        die();
    }

    unset($data[$selectedIndex]);
    @mkdir($_SERVER['DOCUMENT_ROOT'] . "/includes/data/actions");
    file_put_contents($_SERVER['DOCUMENT_ROOT'] . "/includes/data/actions/" . date('Y-m-d_H-i-s') . ".json", utf8_encode(json_encode($data)));
    file_put_contents($_SERVER['DOCUMENT_ROOT'] . "/includes/data/actions/actions.json", utf8_encode(json_encode($data)));
    header("Location: /-/actions/?d&id=" . $id);
    die();
}

if (isset($_POST['updateAction'])) {
    $data = json_decode(file_get_contents($_SERVER['DOCUMENT_ROOT'] . "/includes/data/actions/actions.json"), true);

    $selected = null;
    $selectedIndex = -1;
    $id = $_POST['action'];

    foreach ($data as $index => $item) {
        if ($item["id"] === $id) {
            $selectedIndex = $index;
            $selected = $item;
            break;
        }
    }

    if ($selected === null) {
        header("Location: /-/actions");
        die();
    }

    if (isset($_POST["consent"])) {
        $selected["consent"] = true;
    } else {
        $selected["consent"] = false;
    }

    if (isset($_POST["name"])) $selected["name"] = strip_tags(trim($_POST["name"]));
    if (isset($_POST["example"])) $selected["example"] = strip_tags(trim($_POST["example"]));
    if (isset($_POST["irl"])) $selected["irl"] = strip_tags(trim($_POST["irl"]));
    if (isset($_POST["keywords"])) $selected["keywords"] = array_map(function ($i) {
        return trim($i);
    }, explode(",", strip_tags(trim($_POST["keywords"]))));
    if (isset($_POST["description"])) $selected["description"] = strip_tags(trim($_POST["description"]));
    if (isset($_POST["type"])) $selected["type"] = match ($_POST["type"]) {
        "0" => "affectionate",
        "1" => "sexual",
        "2" => "mixed"
    };

    if (isset($_POST["relations"])) {
        $ponies = [];

        foreach ($_POST["relations"] as $relation => $d) {
            $ponies[] = [
                "members" => explode("-", $relation),
                "deprecated" => isset($d["deprecated"]),
                "sexual" => isset($d["sexual"])
            ];
        }

        $selected["ponies"] = $ponies;
    }

    global $_PROFILE;
    if ($_PROFILE['login'] === "raindrops" && isset($_POST["verified"])) {
        $selected["verified"] = true;
    } else {
        unset($selected["verified"]);
    }

    if (isset($_POST["untested"])) {
        $selected["untested"] = true;
    } else {
        unset($selected["untested"]);
    }

    $data[$selectedIndex] = $selected;
    @mkdir($_SERVER['DOCUMENT_ROOT'] . "/includes/data/actions");
    file_put_contents($_SERVER['DOCUMENT_ROOT'] . "/includes/data/actions/" . date('Y-m-d_H-i-s') . ".json", utf8_encode(json_encode($data)));
    file_put_contents($_SERVER['DOCUMENT_ROOT'] . "/includes/data/actions/actions.json", utf8_encode(json_encode($data)));

    header("Location: /-/actions/" . $id);
    die();
}

if (isset($_POST['createAction'])) {
    require_once $_SERVER['DOCUMENT_ROOT'] . "/includes/random.inc";
    $data = json_decode(file_get_contents($_SERVER['DOCUMENT_ROOT'] . "/includes/data/actions/actions.json"), true);

    if (!isset($_POST["name"]) || !isset($_POST["type"])) {
        header("Location: /-/actions");
        die();
    }
    if (trim($_POST["name"]) === "" || !is_numeric($_POST["type"])) {
        header("Location: /-/actions");
        die();
    }

    $type = match ($_POST["type"]) {
        "0" => "affectionate",
        "1" => "sexual",
        "2" => "mixed"
    };
    $name = strip_tags(trim($_POST["name"]));
    $id = random();

    $ponies = [];

    if (isset($_POST["relations"])) {
        foreach ($_POST["relations"] as $relation => $_) {
            $ponies[] = [
                "members" => explode("-", $relation),
                "deprecated" => false,
                "sexual" => false
            ];
        }
    }

    if (isset($_POST["consent"])) {
        $consent = true;
    } else {
        $consent = false;
    }

    $data[] = [
        "id" => $id,
        "name" => $name,
        "type" => $type,
        "description" => null,
        "ponies" => $ponies,
        "example" => null,
        "irl" => null,
        "keywords" => [],
        "consent" => $consent
    ];

    @mkdir($_SERVER['DOCUMENT_ROOT'] . "/includes/data/actions");
    file_put_contents($_SERVER['DOCUMENT_ROOT'] . "/includes/data/actions/" . date('Y-m-d_H-i-s') . ".json", utf8_encode(json_encode($data)));
    file_put_contents($_SERVER['DOCUMENT_ROOT'] . "/includes/data/actions/actions.json", utf8_encode(json_encode($data)));
    header("Location: /-/actions/" . $id);
    die();
}

global $pagename;
$parts = explode("/", $pagename);
$data = json_decode(file_get_contents($_SERVER['DOCUMENT_ROOT'] . "/includes/data/actions/actions.json"), true);
$toys = json_decode(file_get_contents($_SERVER['DOCUMENT_ROOT'] . "/includes/data/toys/toys.json"), true);

$selected = null;

if (isset($parts[1])) {
    $id = $parts[1];

    foreach ($data as $item) {
        if ($item["id"] === $id) {
            $selected = $item;
            break;
        }
    }

    if ($selected === null) {
        header("Location: /-/actions/?nf&id=" . $id);
        die();
    } else {
        $title = $selected["name"] . " · " . $title;
    }
}

require_once $_SERVER['DOCUMENT_ROOT'] . '/includes/header.inc';
require_once $_SERVER['DOCUMENT_ROOT'] . '/includes/keywords.inc';

if (!file_exists($_SERVER['DOCUMENT_ROOT'] . "/includes/data/actions/actions.json")) file_put_contents($_SERVER['DOCUMENT_ROOT'] . "/includes/data/actions/actions.json", "[]");

global $_PROFILE;
global $pagename;
$parts = explode("/", $pagename);

?>

<script src="/assets/editor/fuse.js"></script>

<br>
<div class="container">
    <div id="<?= isset($parts[1]) ? "page-content" : "" ?>">
        <?php if (isset($_GET['nf'])): ?>
            <div class="alert alert-danger alert-dismissible">
                <button onclick='window.history.pushState({"html":null,"pageTitle":document.title},"", "/-/actions");' type="button" class="btn-close" data-bs-dismiss="alert" style="filter: none !important;"></button>
                <b>Error: </b> The requested action (<code><?= strip_tags($_GET['id'] ?? "-") ?></code>) was not found, it may have been deleted or has never existed.
            </div>
        <?php endif; ?>

        <?php if (isset($_GET['d'])): ?>
            <div class="alert alert-success alert-dismissible">
                <button onclick='window.history.pushState({"html":null,"pageTitle":document.title},"", "/-/actions");' type="button" class="btn-close" data-bs-dismiss="alert" style="filter: none !important;"></button>
                <b>Success: </b> The action with ID <code><?= strip_tags($_GET['id'] ?? "-") ?></code> has been successfully deleted.
            </div>
        <?php endif; ?>

        <?php if (isset($parts[1])): ?>

        <h2>
            <span style="vertical-align: middle;"><?= $selected["name"] ?></span>
            <a href="/-/actions" class="small btn btn-outline-light" style="float:right;margin-top:5px;vertical-align:middle;opacity:1 !important; color:white;">Back</a>
        </h2>
        <p>
            <a onclick="event.target.blur();" data-bs-toggle="modal" data-bs-target="#editor" href="#">Edit</a> ·
            <?php if ($selected["type"] === "affectionate"): ?>
                <span style="" class="badge rounded-pill bg-primary">Affectionate</span>
            <?php endif; ?>
            <?php if ($selected["type"] === "sexual"): ?>
                <span style="" class="badge rounded-pill bg-danger">Sexual</span>
            <?php endif; ?>
            <?php if ($selected["type"] === "mixed"): ?>
                <span style="" class="badge rounded-pill bg-primary">Affectionate</span> <span style="" class="badge rounded-pill bg-danger">Sexual</span>
            <?php endif; ?>
            <?php if (!isset($item["verified"])): ?><span class="badge bg-warning rounded-pill text-black">Unverified</span><?php endif; ?>
            <?php if (isset($item["untested"])): ?><span class="badge bg-info rounded-pill">Untested</span><?php endif; ?>
        </p>

        <hr>
        <?php if ($selected["consent"] && $selected["type"] !== "affectionate"): ?>
        <div class="alert alert-danger">
            <b>This action requires consent.</b> Since this action constitues a sexual act, verbal consent from both parties is absolutely required. Both parties must be in a mental state where they are able to consent. Furthermore, if one of the parties involved wishes to stop, the request must be immediately honoured.
        </div>
        <?php elseif ($selected["consent"]): ?>
        <div class="alert alert-warning">
            <b>This action is better with consent.</b> This action is extremely personal to all parties involved, and it is best to ask if they wish to do this. If they ask to stop the action, you must stop immediately and reverse any potential effects.
        </div>
        <?php endif; ?>

        <?php if (isset($selected["description"]) && trim($selected["description"]) !== ""): ?>
        <?= replaceKeyWords(str_replace("\n", "<br>", strip_tags($selected["description"]))); ?>
        <?php else: ?>
        <p><i>No description provided for this action. Enter edit mode to add a description to this action.</i></p>
        <?php endif; ?>

        <?php if (isset($selected["toys"]) && $selected["toys"]): ?>
            <hr>
            <p><b>Available toys:</b></p>
            <div id="toys-list">
                <div class="toys-list-inner">
                    <?php

                    $init = [];
                    foreach ($toys as $value) {
                        $init[$value["name"]] = $value;
                    }

                    ksort($init);

                    $sorted = array_values($init);
                    uasort($sorted, function ($a, $b) {
                        $uniquePonies1 = [];

                        foreach ($a["ponies"] as $ponies) {
                            foreach ($ponies["members"] as $member) {
                                $uniquePonies1[$member] = true;
                            }
                        }

                        $uniquePonies2 = [];

                        foreach ($b["ponies"] as $ponies) {
                            foreach ($ponies["members"] as $member) {
                                $uniquePonies2[$member] = true;
                            }
                        }

                        return count($uniquePonies2) - count($uniquePonies1);
                    });

                    foreach ($sorted as $item): ?>
                        <a href="/-/toys/<?= $item["id"] ?>" id="action-<?= $item["id"] ?>" style="color:white !important;">
                            <div>
                                <span><?= $item["name"] ?></span>
                            </div>
                        </a>
                    <?php endforeach; ?>
                </div>
            </div>
        <?php endif; ?>

        <!--<hr>
        <b>Can be done by:</b>
        <?php

        $hasMultipleTypes = false;
        $seenType = "";

        foreach ($selected["ponies"] as $relation) {
            if (isset($relation["sexual"]) && $relation["sexual"]) {
                $type = "sexual";
            } else {
                $type = "affectionate";
            }

            if ($type !== $seenType && $seenType !== "") {
                $hasMultipleTypes = true;
            }

            if (trim($seenType) === "") {
                $seenType = $type;
            }
        }

        ?>
        <?php if ($hasMultipleTypes): ?>
            <ul>
                <li>
                    Affectionately:
                    <ul>
                        <?php foreach ($selected["ponies"] as $relation): if (!$relation["deprecated"] && (!isset($relation["sexual"]) || !$relation["sexual"])):

                            $member1 = getMemberWithoutSystem($relation["members"][0]);
                            $member2 = getMemberWithoutSystem($relation["members"][1]);

                            ?>
                            <li>
                                <img style="vertical-align: middle;width:24px;height:24px;" src="<?= getAsset($systemID, $member1["id"], "heads") ?>">
                                <img style="vertical-align: middle;width:24px;height:24px;" src="<?= getAsset($systemID, $member2["id"], "heads") ?>">

                                <span style="vertical-align: middle;"><?= getMiniName($member1["display_name"] ?? $member1["name"]) ?> and <?= getMiniName($member2["display_name"] ?? $member2["name"]) ?></span>
                            </li>
                        <?php endif; endforeach; ?>
                        <?php foreach ($selected["ponies"] as $relation): if ($relation["deprecated"] && (!isset($relation["sexual"]) || !$relation["sexual"])):

                            $member1 = getMemberWithoutSystem($relation["members"][0]);
                            $member2 = getMemberWithoutSystem($relation["members"][1]);

                            ?>
                            <li>
                                <span style="opacity:.5;">
                                    <img style="vertical-align: middle;width:24px;height:24px;" src="<?= getAsset($systemID, $member1["id"], "heads") ?>">
                                    <img style="vertical-align: middle;width:24px;height:24px;" src="<?= getAsset($systemID, $member2["id"], "heads") ?>">

                                    <span style="vertical-align: middle;"><?= getMiniName($member1["display_name"] ?? $member1["name"]) ?> and <?= getMiniName($member2["display_name"] ?? $member2["name"]) ?></span>
                                </span>
                                <span class="badge bg-danger rounded-pill">Deprecated</span>
                            </li>
                        <?php endif; endforeach; ?>
                    </ul>
                </li>
                <li>
                    Sexually:
                    <ul>
                        <?php foreach ($selected["ponies"] as $relation): if (!$relation["deprecated"] && (isset($relation["sexual"]) && $relation["sexual"])):

                            $member1 = getMemberWithoutSystem($relation["members"][0]);
                            $member2 = getMemberWithoutSystem($relation["members"][1]);

                            ?>
                            <li>
                                <img style="vertical-align: middle;width:24px;height:24px;" src="<?= getAsset($member1["system"], $member1["id"], "heads") ?>">
                                <img style="vertical-align: middle;width:24px;height:24px;" src="<?= getAsset($member2["system"], $member2["id"], "heads") ?>">

                                <span style="vertical-align: middle;"><?= getMiniName($member1["display_name"] ?? $member1["name"]) ?> and <?= getMiniName($member2["display_name"] ?? $member2["name"]) ?></span>
                            </li>
                        <?php endif; endforeach; ?>
                        <?php foreach ($selected["ponies"] as $relation): if ($relation["deprecated"] && (isset($relation["sexual"]) && $relation["sexual"])):

                            $member1 = getMemberWithoutSystem($relation["members"][0]);
                            $member2 = getMemberWithoutSystem($relation["members"][1]);

                            ?>
                            <li>
                                <span style="opacity:.5;">
                                    <img style="vertical-align: middle;width:24px;height:24px;" src="<?= getAsset($member1["system"], $member1["id"], "heads") ?>">
                                    <img style="vertical-align: middle;width:24px;height:24px;" src="<?= getAsset($member2["system"], $member2["id"], "heads") ?>">

                                    <span style="vertical-align: middle;"><?= getMiniName($member1["display_name"] ?? $member1["name"]) ?> and <?= getMiniName($member2["display_name"] ?? $member2["name"]) ?></span>
                                </span>
                                <span class="badge bg-danger rounded-pill">Deprecated</span>
                            </li>
                        <?php endif; endforeach; ?>
                    </ul>
                </li>
            </ul>
        <?php else: ?>
            <ul>
                <?php foreach ($selected["ponies"] as $relation): if (!$relation["deprecated"]):

                    $member1 = getMemberWithoutSystem($relation["members"][0]);
                    $member2 = getMemberWithoutSystem($relation["members"][1]);

                    ?>
                    <li>
                        <img style="vertical-align: middle;width:24px;height:24px;" src="<?= getAsset($member1["system"], $member1["id"], "heads") ?>">
                        <img style="vertical-align: middle;width:24px;height:24px;" src="<?= getAsset($member2["system"], $member2["id"], "heads") ?>">

                        <span style="vertical-align: middle;"><?= getMiniName($member1["display_name"] ?? $member1["name"]) ?> and <?= getMiniName($member2["display_name"] ?? $member2["name"]) ?></span>
                    </li>
                <?php endif; endforeach; ?>
                <?php foreach ($selected["ponies"] as $relation): if ($relation["deprecated"]):

                    $member1 = getMemberWithoutSystem($relation["members"][0]);
                    $member2 = getMemberWithoutSystem($relation["members"][1]);

                    ?>
                    <li>
                        <span style="opacity:.5;">
                            <img style="vertical-align: middle;width:24px;height:24px;" src="<?= getAsset($member1["system"], $member1["id"], "heads") ?>">
                            <img style="vertical-align: middle;width:24px;height:24px;" src="<?= getAsset($member2["system"], $member2["id"], "heads") ?>">

                            <span style="vertical-align: middle;"><?= getMiniName($member1["display_name"] ?? $member1["name"]) ?> and <?= getMiniName($member2["display_name"] ?? $member2["name"]) ?></span>
                        </span>
                        <span class="badge bg-danger rounded-pill">Deprecated</span>
                    </li>
                <?php endif; endforeach; ?>
            </ul>
        <?php endif; ?>-->

        <div style="margin-top:10px;"></div>

        <?php $multipleExamples = count(explode(",", strip_tags($selected["example"]))) > 1; ?>
        <b>Example<?= $multipleExamples ? "s" : "" ?>:</b><br>
        <?php if (isset($selected["example"]) && trim($selected["example"]) !== ""): ?>
        <?php if ($multipleExamples): ?>
        <ul>
            <?php foreach (explode(",", strip_tags($selected["example"])) as $example): ?>
                <li><?= replaceKeyWords(trim($example)) ?></li>
            <?php endforeach; ?>
        </ul>
        <?php else: ?>
        <?= replaceKeyWords(strip_tags($selected["example"])) ?>
        <?php endif; ?>
        <?php else: ?>
        <p><i>No example provided for this action. Enter edit mode to add an example to this action.</i></p>
        <?php endif; ?>

        <div style="margin-top:10px;"></div>

        <b>Steps to reproduce in real life:</b><br>
        <?php if (isset($selected["irl"]) && trim($selected["irl"]) !== ""): ?>
        <?= replaceKeyWords(strip_tags($selected["irl"])) ?>
        <?php else: ?>
        <p><i>This action is not reproducible in real life.</i></p>
        <?php endif; ?>

        <hr>

        <h4>Similar actions</h4>
        <div class="row">
            <?php

            $names = [];
            $currentName = $selected["name"];
            $namesByDistance = [];

            foreach ($data as $action) {
                if ($action["name"] !== $currentName) $names[$action["name"]] = [
                    "id" => $action["id"],
                    "type" => $action["type"],
                    "ponies" => $action["ponies"]
                ];
            }

            foreach ($names as $name => $data) {
                if ($data["type"] === $selected["type"] || $selected["type"] !== "affectionate") {
                    $namesByDistance[] = [
                        "name" => $name,
                        "distance" => levenshtein($currentName, $name) + ((int)($data["type"] !== $selected["type"]) * 2),
                        "id" => $data["id"],
                        "type" => $data["type"],
                        "ponies" => $data["ponies"]
                    ];
                }
            }

            uasort($namesByDistance, function ($a, $b) use ($selected) {
                return $a["distance"] - $b["distance"];
            });

            foreach ($namesByDistance as $item) {
                echo("<!-- " . $currentName . " <-> " . $item["name"] . " => " . $item["distance"] . " (artif: " . ((int)($item["type"] !== $selected["type"]) * 10) . ") -->");
            }

            $index = 0;
            foreach ($namesByDistance as $item): if ($index < 3):
            ?>
            <div class="col-md-4" style="margin-bottom:20px;">
                <a class="linked-card" href="/-/actions/<?= $item["id"] ?>"><div class="card">
                    <div class="card-body">
                        <h4 class="card-title"><?= $item["name"] ?></h4>
                        <p class="card-text">
                            <!--<?php

                            $uniquePonies = [];

                            foreach ($item["ponies"] as $ponies) {
                                foreach ($ponies["members"] as $member) {
                                    if (isset($uniquePonies[$member]) && !$uniquePonies[$member]) {
                                        $uniquePonies[$member] = false;
                                    } else {
                                        $uniquePonies[$member] = $ponies["deprecated"];
                                    }
                                }
                            }

                            foreach ($uniquePonies as $name => $deprecated): if (!$deprecated): ?>
                            <span data-bs-toggle="tooltip" title="<?= getMemberWithoutSystem($name)["display_name"] ?? getMemberWithoutSystem($name)["display_name"] ?>" style="display: inline-block;">
                                <img src="<?= getAsset(getMemberWithoutSystem($name)["system"], getMemberWithoutSystem($name)["id"], "heads") ?>" style="width:32px;">
                            </span>
                            <?php endif; endforeach; ?>
                            <?php foreach ($uniquePonies as $name => $deprecated): if ($deprecated): ?>
                                <span data-bs-toggle="tooltip" data-bs-html="true" title="<i><?= strip_tags(getMemberWithoutSystem($name)["display_name"] ?? getMemberWithoutSystem($name)["name"]) ?></i>" style="opacity:.5;display: inline-block;">
                                <img src="<?= getAsset(getMemberWithoutSystem($name)["system"], getMemberWithoutSystem($name)["id"], "heads") ?>" style="width:32px;">
                            </span>
                            <?php endif; endforeach; ?>-->
                            -
                        </p>
                        <?php if ($item["type"] === "affectionate"): ?>
                            <span style="" class="badge rounded-pill bg-primary">Affectionate</span>
                        <?php endif; ?>
                        <?php if ($item["type"] === "sexual"): ?>
                            <span style="" class="badge rounded-pill bg-danger">Sexual</span>
                        <?php endif; ?>
                        <?php if ($item["type"] === "mixed"): ?>
                            <span style="" class="badge rounded-pill bg-primary">Affectionate</span> <span style="" class="badge rounded-pill bg-danger">Sexual</span>
                        <?php endif; ?>
                    </div>
                </div></a>
            </div>
            <?php $index++; endif; endforeach; ?>
        </div>

        <div class="modal fade" id="editor">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <h4 class="modal-title">Edit action</h4>
                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                    </div>

                    <div class="modal-body">
                        <form method="post" style="display:inline;">
                            <input type="text" placeholder="Action title" name="name" class="form-control" style="color:white;background:#111;border-color:#222;margin-bottom:10px;" value="<?= str_replace('"', '&quot;', $selected["name"]) ?>">
                            <select name="type" id="editor-type" class="form-select" style='color:white;background-color:#111;border-color:#222;background-image:url("data:image/svg+xml,%3csvg xmlns=&apos;http://www.w3.org/2000/svg&apos; viewBox=&apos;0 0 16 16&apos;%3e%3cpath fill=&apos;none&apos; stroke=&apos;%23ffffff&apos; stroke-linecap=&apos;round&apos; stroke-linejoin=&apos;round&apos; stroke-width=&apos;2&apos; d=&apos;M2 5l6 6 6-6&apos;/%3e%3c/svg%3e");margin-bottom:10px;' onchange="changeMixed();">
                                <option value="0" <?= $selected["type"] === "affectionate" ? "selected" : "" ?>>Affectionate</option>
                                <option value="1" <?= $selected["type"] === "sexual" ? "selected" : "" ?>>Sexual</option>
                                <option value="2" <?= $selected["type"] === "mixed" ? "selected" : "" ?>>Mixed</option>
                            </select>

                            <label style="margin-left:5px;">
                                <input <?= ($selected["consent"] ?? false) ? "checked" : "" ?> type="checkbox" name="consent">
                                Requires consent
                            </label><br>

                            <label style="margin-left:5px;">
                                <input <?= ($selected["verified"] ?? false) ? "checked" : "" ?> <?= $_PROFILE['login'] !== "raindrops" ? "disabled" : "" ?> type="checkbox" name="verified">
                                Mark as verified
                            </label><br>

                            <label style="margin-left:5px;">
                                <input <?= ($selected["untested"] ?? false) ? "checked" : "" ?> type="checkbox" name="untested">
                                Mark as untested
                            </label>

                            <hr>

                            <textarea name="description" class="form-control" style="resize: none;color:white;background:#111;border-color:#222;" placeholder="Description"><?= strip_tags($selected["description"] ?? "") ?></textarea>

                            <hr>

                            <input type="text" placeholder="Keywords (comma-separated)" name="keywords" class="form-control" style="color:white;background:#111;border-color:#222;margin-bottom:10px;" value="<?= str_replace('"', '&quot;', implode(",", $selected["keywords"] ?? [])) ?>">
                            <input type="text" placeholder="Action example" name="example" class="form-control" style="color:white;background:#111;border-color:#222;margin-bottom:10px;" value="<?= str_replace('"', '&quot;', $selected["example"] ?? "") ?>">
                            <input type="text" placeholder="IRL steps" name="irl" class="form-control" style="color:white;background:#111;border-color:#222;" value="<?= str_replace('"', '&quot;', $selected["irl"] ?? "") ?>">

                            <div style="display: none;">
                            <hr>

                            <p>Select the groups of ponies who can do this action:</p>
                            <?php

                            $members = scoreOrderGlobal();
                            $relations = [];

                            foreach ($members as $member) {
                                foreach ([
                                             ...array_map(function ($i) {
                                                 $r = [
                                                     "name" => $i
                                                 ];
                                                 $r["type"] = "marefriends";
                                                 return $r;
                                             }, $member["_metadata"]["marefriends"] ?? []),
                                             ...array_map(function ($i) {
                                                 $r = [
                                                     "name" => $i
                                                 ];
                                                 $r["type"] = "sisters";
                                                 return $r;
                                             }, $member["_metadata"]["sisters"] ?? []),
                                             ...array_map(function ($i) {
                                                 $r = [
                                                     "name" => $i
                                                 ];
                                                 $r["type"] = "caretaking";
                                                 return $r;
                                             }, $member["_metadata"]["caretakers"] ?? [])
                                         ] as $rel) {
                                    $id = $rel["name"];
                                    $otherMember = getSystemMember(explode("/", $id)[0], explode("/", $id)[1]);

                                    $parts = [
                                        $member["id"],
                                        $otherMember["id"]
                                    ];

                                    asort($parts);

                                    $relations[implode("-", $parts)] = [
                                        "name" => getMiniName($member["display_name"] ?? $member["name"]) . " and " . getMiniName($otherMember["display_name"] ?? $otherMember["name"]),
                                        "type" => $rel["type"],
                                        "images" => [
                                            file_exists($_SERVER['DOCUMENT_ROOT'] . "/assets/uploads/pt-$member[name].png") ? "/assets/uploads/pt-$member[name].png" : "/assets/uploads/pt.png",
                                            file_exists($_SERVER['DOCUMENT_ROOT'] . "/assets/uploads/pt-$otherMember[name].png") ? "/assets/uploads/pt-$otherMember[name].png" : "/assets/uploads/pt.png",
                                        ]
                                    ];
                                }
                            }

                            $inFileRelations = [];
                            $inFileDeprecations = [];
                            $inFileSexual = [];

                            foreach ($selected["ponies"] as $ponies) {
                                $inFileRelations[] = $ponies["members"][0] . "-" . $ponies["members"][1];

                                if (isset($ponies["deprecated"]) && $ponies["deprecated"]) $inFileDeprecations[] = $ponies["members"][0] . "-" . $ponies["members"][1];
                                if (isset($ponies["sexual"]) && $ponies["sexual"]) $inFileSexual[] = $ponies["members"][0] . "-" . $ponies["members"][1];
                            }

                            foreach ($relations as $id => $relation):
                                ?>
                                <label style="display:block;" class="creator-relation <?= $selected["type"] === "mixed" ? "mixed" : "" ?> <?= in_array($id, $inFileRelations) ? "checked" : "" ?>">
                                    <input <?= in_array($id, $inFileRelations) ? "checked" : "" ?> name="relations[<?= $id ?>][member]" style="display:none;" type="checkbox" class="checkbox-input">

                                    <img style="vertical-align: middle;width:24px;height:24px;" src="<?= $relation["images"][0] ?>">
                                    <img style="vertical-align: middle;width:24px;height:24px;" src="<?= $relation["images"][1] ?>">
                                    <span style="vertical-align: middle;"><?= $relation["name"] ?></span>

                                    <span style="float:right;margin-top:3px;" class="badge rounded-pill bg-<?= match ($relation["type"]) {
                                        "marefriends" => "danger",
                                        "sisters" => "success",
                                        "caretaking" => "primary"
                                    } ?>"><?= match ($relation["type"]) {
                                            "marefriends" => "Marefriends",
                                            "sisters" => "Sisters",
                                            "caretaking" => "Caretaker"
                                        } ?></span>

                                    <label class="deprecated" style="display:none;margin-left: 20px;margin-top: 5px;">
                                        <input <?= in_array($id, $inFileDeprecations) ? "checked" : "" ?> name="relations[<?= $id ?>][deprecated]" type="checkbox">
                                        Mark as deprecated
                                    </label>
                                    <label class="sexual" style="display:none;margin-left: 20px;margin-top: 5px;">
                                        <input <?= in_array($id, $inFileSexual) ? "checked" : "" ?> name="relations[<?= $id ?>][sexual]" type="checkbox">
                                        Mark as sexual
                                    </label>
                                </label>
                            <?php endforeach; ?>
                            </div>

                            <br>
                            <input type="hidden" name="updateAction">
                            <input type="hidden" name="action" value="<?= $selected["id"] ?>">
                            <input type="submit" class="btn btn-primary" value="Save">
                        </form>
                        <form method="post" style="display:inline;">
                            <input type="hidden" name="deleteAction">
                            <input type="hidden" name="action" value="<?= $selected["id"] ?>">
                            <input type="submit" class="btn btn-danger" value="Delete">
                        </form>
                    </div>
                </div>
            </div>
        </div>

        <?php else: ?>

        <h2>Actions database</h2>
        <p><?= count($data) ?> actions (<?= count(array_filter($data, function ($i) {
                return $i["type"] === "affectionate" || $i["type"] === "mixed";
            })) ?> affectionate, <?= count(array_filter($data, function ($i) {
                return $i["type"] === "sexual" || $i["type"] === "mixed";
            })) ?> sexual, <?= count(array_filter($data, function ($i) {
                return isset($i["untested"]) && $i["untested"];
            })) ?> untested, <?= count(array_filter($data, function ($i) {
                return (isset($i["description"]) && trim($i["description"]) === "") || !isset($i["description"]);
            })) ?> incomplete)</p>

        <p>TODO: fill everything and add keywords</p>

        <input type="text" placeholder="Search for an action..." class="form-control" style="margin-bottom:15px;color:white;background:#111;border-color:#222;" onchange="search();" onkeydown="search();" onkeyup="search();" id="search">

        <div id="list">
            <div class="list-group">
                <?php

                $init = [];
                foreach ($data as $value) {
                    $init[$value["name"]] = $value;
                }

                ksort($init);

                $sorted = array_values($init);

                foreach ($sorted as $item): ?>
                <a href="/-/actions/<?= $item["id"] ?>" id="action-<?= $item["id"] ?>" style="display:grid;grid-template-columns: 1fr 0.2fr;" class="list-group-item list-group-item-action action-listing">
                    <div>
                        <span class="<?= trim($item["description"]) === "" ? "text-danger" : "" ?>"><?= $item["name"] ?></span>
                        <?php if (!isset($item["verified"])): ?><span class="badge bg-warning rounded-pill text-black">Unverified</span><?php endif; ?>
                        <?php if (isset($item["untested"])): ?><span class="badge bg-info rounded-pill">Untested</span><?php endif; ?>
                    </div>
                    <!--
                    <div>
                        <?php

                        $uniquePonies = [];
                        $longPonyList = false;

                        foreach ($item["ponies"] as $ponies) {
                            foreach ($ponies["members"] as $member) {
                                if (isset($uniquePonies[$member]) && !$uniquePonies[$member]) {
                                    $uniquePonies[$member] = false;
                                } else {
                                    $uniquePonies[$member] = $ponies["deprecated"];
                                }
                            }
                        }

                        if (count($uniquePonies) > 6) {
                            $longPonyList = true;
                        }

                        $index = 1;
                        foreach ($uniquePonies as $name => $deprecated): if (!$deprecated): ?>
                        <span title="<?= getMemberWithoutSystem($name)["display_name"] ?? getMemberWithoutSystem($name)["display_name"] ?>" style="display: inline-block;<?= $longPonyList && $index % 2 === 0 ? "position:absolute;margin-left:-12px;z-index:" . (999 - $index) . ";" : "position:relative;z-index:" . (999 - $index) . ";" ?>">
                            <img src="/assets/uploads/pt-<?= getMemberWithoutSystem($name)["name"] ?>.png" style="width:24px;">
                        </span>
                        <?php $index++; endif; endforeach; ?>
                        <?php foreach ($uniquePonies as $name => $deprecated): if ($deprecated): ?>
                        <span title="<?= strip_tags(getMemberWithoutSystem($name)["display_name"] ?? getMemberWithoutSystem($name)["name"]) ?> (deprecated)" style="opacity:.5;display: inline-block;<?= $longPonyList && $index % 2 === 0 ? "position:absolute;margin-left:-12px;z-index:" . (999 - $index) . ";" : "position:relative;z-index:" . (999 - $index) . ";" ?>">
                            <img src="/assets/uploads/pt-<?= getMemberWithoutSystem($name)["name"] ?>.png" style="width:24px;">
                        </span>
                        <?php $index++; endif; endforeach; ?>
                    </div>
                    -->
                    <div style="text-align: right;">
                        <?php if ($item["type"] === "affectionate"): ?>
                            <span style="" class="badge rounded-pill bg-primary">Affectionate</span>
                        <?php endif; ?>
                        <?php if ($item["type"] === "sexual"): ?>
                            <span style="" class="badge rounded-pill bg-danger">Sexual</span>
                        <?php endif; ?>
                        <?php if ($item["type"] === "mixed"): ?>
                            <span style="" class="badge rounded-pill bg-success">Mixed</span>
                        <?php endif; ?>
                    </div>
                </a>
                <?php endforeach; ?>
            </div>
        </div>

        <div id="search-results" class="list-group"></div>

        <div id="page-content">
            <hr>
            <p>Not finding what you are looking for? <a onclick="event.target.blur(); document.getElementById('creator-title').focus();" href="#" data-bs-toggle="modal" data-bs-target="#creator">Create an action.</a></p>
        </div>

        <script>
            window.actions = JSON.parse(atob(`<?= base64_encode(json_encode(array_values(json_decode(file_get_contents($_SERVER['DOCUMENT_ROOT'] . "/includes/data/actions/actions.json"), true)))) ?>`));
        </script>

        <div class="modal fade" id="creator">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <h4 class="modal-title">Create a new action</h4>
                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                    </div>

                    <div class="modal-body">
                        <form method="post">
                            <input id="creator-title" type="text" placeholder="Action title" name="name" class="form-control" style="color:white;background:#111;border-color:#222;margin-bottom:10px;">
                            <select name="type" class="form-select" style='color:white;background-color:#111;border-color:#222;background-image:url("data:image/svg+xml,%3csvg xmlns=&apos;http://www.w3.org/2000/svg&apos; viewBox=&apos;0 0 16 16&apos;%3e%3cpath fill=&apos;none&apos; stroke=&apos;%23ffffff&apos; stroke-linecap=&apos;round&apos; stroke-linejoin=&apos;round&apos; stroke-width=&apos;2&apos; d=&apos;M2 5l6 6 6-6&apos;/%3e%3c/svg%3e");margin-bottom:10px;'>
                                <option value="0" selected>Affectionate</option>
                                <option value="1">Sexual</option>
                                <option value="2">Mixed</option>
                            </select>

                            <div class="alert alert-secondary" style="display:none;">
                                <p>The following actions might be the same as the one you are trying to add:</p>
                                <ul>
                                    <li>Action 1</li>
                                    <li>Action 2</li>
                                    <li>Action 3</li>
                                </ul>
                            </div>

                            <label style="margin-left:5px;">
                                <input type="checkbox" name="consent">
                                Requires consent
                            </label>

                            <div style="display: none;">
                            <hr>

                            <p>Select the groups of ponies who can do this action:</p>
                            <?php

                            $members = scoreOrderGlobal();
                            $relations = [];

                            foreach ($members as $member) {
                                foreach ([
                                             ...array_map(function ($i) {
                                                 $r = [
                                                     "name" => $i
                                                 ];
                                                 $r["type"] = "marefriends";
                                                 return $r;
                                             }, $member["_metadata"]["marefriends"] ?? []),
                                             ...array_map(function ($i) {
                                                 $r = [
                                                     "name" => $i
                                                 ];
                                                 $r["type"] = "sisters";
                                                 return $r;
                                             }, $member["_metadata"]["sisters"] ?? []),
                                             ...array_map(function ($i) {
                                                 $r = [
                                                     "name" => $i
                                                 ];
                                                 $r["type"] = "caretaking";
                                                 return $r;
                                             }, $member["_metadata"]["caretakers"] ?? [])
                                         ] as $rel) {
                                    $id = $rel["name"];
                                    $otherMember = getSystemMember(explode("/", $id)[0], explode("/", $id)[1]);

                                    $parts = [
                                        $member["id"],
                                        $otherMember["id"]
                                    ];

                                    asort($parts);

                                    $relations[implode("-", $parts)] = [
                                        "name" => getMiniName($member["display_name"] ?? $member["name"]) . " and " . getMiniName($otherMember["display_name"] ?? $otherMember["name"]),
                                        "type" => $rel["type"],
                                        "images" => [
                                            file_exists($_SERVER['DOCUMENT_ROOT'] . "/assets/uploads/pt-$member[name].png") ? "/assets/uploads/pt-$member[name].png" : "/assets/uploads/pt.png",
                                            file_exists($_SERVER['DOCUMENT_ROOT'] . "/assets/uploads/pt-$otherMember[name].png") ? "/assets/uploads/pt-$otherMember[name].png" : "/assets/uploads/pt.png",
                                        ]
                                    ];
                                }
                            }

                            foreach ($relations as $id => $relation):
                                ?>
                                <label style="display:block;" class="creator-relation">
                                    <input name="relations[<?= $id ?>]" style="display:none;" type="checkbox" class="checkbox-input">

                                    <img style="vertical-align: middle;width:24px;height:24px;" src="<?= $relation["images"][0] ?>">
                                    <img style="vertical-align: middle;width:24px;height:24px;" src="<?= $relation["images"][1] ?>">
                                    <span style="vertical-align: middle;"><?= $relation["name"] ?></span>

                                    <span style="float:right;margin-top:3px;" class="badge rounded-pill bg-<?= match ($relation["type"]) {
                                        "marefriends" => "danger",
                                        "sisters" => "success",
                                        "caretaking" => "primary"
                                    } ?>"><?= match ($relation["type"]) {
                                            "marefriends" => "Marefriends",
                                            "sisters" => "Sisters",
                                            "caretaking" => "Caretaker"
                                        } ?></span>
                                </label>
                            <?php endforeach; ?></div>

                            <p style="margin-top:10px;">You can add additional data (description, example, how to do the action IRL) after creating the action.</p>
                            <input type="hidden" name="createAction">
                            <input type="submit" class="btn btn-primary" value="Create">
                        </form>
                    </div>
                </div>
            </div>
        </div>

        <?php endif; ?>
    </div>
</div>

<!--suppress JSUnresolvedFunction -->
<script>
    Array.from(document.getElementsByClassName("checkbox-input")).forEach((el) => {
        el.onchange = () => {
            let parent = el.parentElement;

            if (el.checked) {
                parent.classList.add("checked");
            } else {
                parent.classList.remove("checked");
            }
        }
    });

    const fuse = new Fuse(window.actions, {
        includeScore: true,
        keys: [
            {
                name: 'name',
                weight: 1
            },
            {
                name: 'description',
                weight: 1
            },
            {
                name: 'example',
                weight: 0.7
            },
            {
                name: 'irl',
                weight: 0.5
            }
        ]
    })

    function search() {
        let query = document.getElementById("search").value;
        let results = fuse.search(query).map((i) => {
            return {
                id: i.item.id,
                score: i.score
            };
        });

        let unfiltered = results;

        results = results.filter((i) => {
            return i.score < 0.7;
        });

        console.log("Before:", unfiltered, "After:", results);

        document.getElementById("list").style.display = "none";
        document.getElementById("search-results").style.display = "block";
        document.getElementById("search-results").innerHTML = "";

        for (let result of results) {
            document.getElementById("search-results").innerHTML += document.getElementById("action-" + result.id).outerHTML;
        }

        console.log(results);

        if (query.trim() === "") {
            document.getElementById("list").style.display = "block";
            document.getElementById("search-results").style.display = "none";
        }
    }

    function changeMixed() {
        let value = document.getElementById("editor-type").value;
        console.log(value);

        if (value === "2") {
            Array.from(document.getElementsByClassName("creator-relation")).forEach((el) => {
                el.classList.add("mixed");
            });
        } else {
            Array.from(document.getElementsByClassName("creator-relation")).forEach((el) => {
                el.classList.remove("mixed");
            });
        }
    }
</script>

<style>
    .modal-header {
        border-bottom: 1px solid #353738;
    }

    .modal-content {
        border: 1px solid rgba(255, 255, 255, .2);
        background-color: #111;
    }

    .btn-close {
        filter: invert(1);
    }

    .creator-relation {
        border-radius: 10px;
        padding: 5px 10px;
        opacity: .5;
    }

    .creator-relation.checked {
        background-color: rgba(255, 255, 255, .1);
        opacity: 1;
    }

    .creator-relation:hover {
        background-color: rgba(255, 255, 255, .1);
    }

    .creator-relation.checked:hover {
        background-color: rgba(255, 255, 255, .25) !important;
    }

    .creator-relation.checked .deprecated {
        display: block !important;
    }

    .creator-relation.mixed.checked .sexual {
        display: block !important;
    }

    .list-group-item {
        color: #fff;
        background-color: #222;
        border: 1px solid rgba(255, 255, 255, .125);
    }

    .list-group-item.disabled {
        color: #fff;
        background-color: #222;
        border-color: rgba(255, 255, 255, .125);
        opacity: .75;
    }

    .list-group-item:hover {
        background-color: #252525;
        color: #ddd;
    }

    .list-group-item:active, .list-group-item:focus {
        background-color: #272727;
        color: #bbb;
    }

    @media (max-width: 991px) {
        .action-listing {
            grid-template-columns: 1fr !important;
            text-align: center !important;
        }

        .action-listing > * {
            margin-bottom: 10px;
            text-align: center !important;
        }

        .action-listing > *:nth-last-child(1) {
            margin-bottom: 0 !important;
        }

        .action-listing img {
            width: 32px !important;
        }
    }

    .toys-list-inner {
        display: grid;
        grid-template-columns: repeat(4, 1fr);
        background-color: #111111;
        box-sizing: border-box;
        grid-gap: 1px;
    }

    .toys-list-inner > * {
        text-decoration: none !important;
        box-shadow: 0 0 0 1px #2f2f2f;
        padding: 5px 10px;
    }

    .toys-list-inner > *:nth-child(1) {
        border-top-left-radius: 5px;
    }

    .toys-list-inner > *:nth-child(4) {
        border-top-right-radius: 5px;
    }

    .toys-list-inner > *:nth-last-child(4) {
        border-bottom-left-radius: 5px;
    }

    .toys-list-inner > *:nth-last-child(1) {
        border-bottom-right-radius: 5px;
    }
</style>

<?php require_once $_SERVER['DOCUMENT_ROOT'] . '/includes/footer.inc'; ?>