<?php global $system; global $app; global $systemCommonName; global $systemID; global $member; global $memberData; global $memberCommonName; global $memberID; $title = "Editing metadata for " . $memberCommonName . " ยท " . $systemCommonName; require_once $_SERVER['DOCUMENT_ROOT'] . '/includes/components/header.inc';

if (file_exists($_SERVER['DOCUMENT_ROOT'] . "/includes/data/metadata/" . $memberID . ".json")) {
    $metadata = parseMetadata(json_decode(file_get_contents($_SERVER['DOCUMENT_ROOT'] . "/includes/data/metadata/" . $memberID . ".json"), true));
}

?>

<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);
    }

    .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;
    }

    .member-link, .list-group-item-action {
        cursor: pointer !important;
    }
</style>

<br>
<div class="container">
    <h2 id="page-content"><a href="/<?= $memberData["name"] ?>"><?= $memberData["display_name"] ?? $memberData["name"] ?></a></h2>
    <?php if (file_exists($_SERVER['DOCUMENT_ROOT'] . "/includes/data/metadata/" . $memberID . ".json")): ?>
    <form>
        <input name="submit" type="hidden">
        <p>
            <b>File</b><br>
            <?= $_SERVER['DOCUMENT_ROOT'] . "/includes/data/metadata/" . $memberID . ".json" ?>
        </p>

        <hr>

        <h3>General information</h3>

        <div style="margin-bottom: 1rem;">
            <b>General:</b><br>
            <div style="display: grid; grid-template-columns: repeat(2, 1fr); grid-gap: 10px;">
                <select class="tooltip-nohelp form-select" style='display:inline-block;filter:invert(1) hue-rotate(180deg);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;%23000000&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");' name="food">
                    <option <?= $metadata["food"] === 0 ? "selected" : "" ?> value="0">Doesn't need to eat</option>
                    <option <?= $metadata["food"] === 1 ? "selected" : "" ?> value="1">Can't eat fish or meat</option>
                    <option <?= $metadata["food"] === 2 ? "selected" : "" ?> value="2">Can't eat meat</option>
                    <option <?= $metadata["food"] === 3 ? "selected" : "" ?> value="3">Can eat everything</option>
                </select>
                <select class="tooltip-nohelp form-select" style='display:inline-block;filter:invert(1) hue-rotate(180deg);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;%23000000&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");' name="shared_memory">
                    <option <?= $metadata["shared_memory"] === 2 ? "selected" : "" ?> value="2">Doing subconsciously</option>
                    <option <?= $metadata["shared_memory"] === 1 ? "selected" : "" ?> value="1">Consciously willing</option>
                    <option <?= $metadata["shared_memory"] === 0 ? "selected" : "" ?> value="0">Incapable/not willing</option>
                </select>
            </div>
        </div>
        <div style="margin-bottom: 1rem;">
            <b>Species</b><br>
            <div style="display: grid; grid-template-columns: repeat(2, 1fr); grid-gap: 10px;">
                <select class="tooltip-nohelp form-select" style='display:inline-block;filter:invert(1) hue-rotate(180deg);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;%23000000&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");' name="species[0]">
                    <option <?= !isset($metadata["species"][0]) || $metadata["species"][0] === "" ? "selected" : "" ?> value="">None</option>
                    <option <?= $metadata["species"][0] === "earth" ? "selected" : "" ?> value="earth">Earth pony</option>
                    <option <?= $metadata["species"][0] === "unicorn" ? "selected" : "" ?> value="unicorn">Unicorn</option>
                    <option <?= $metadata["species"][0] === "pegasus" ? "selected" : "" ?> value="pegasus">Pegasus</option>
                    <option <?= $metadata["species"][0] === "alicorn" ? "selected" : "" ?> value="alicorn">Alicorn</option>
                    <option <?= $metadata["species"][0] === "batpony" ? "selected" : "" ?> value="batpony">Bat pony</option>
                    <option <?= $metadata["species"][0] === "crystal" ? "selected" : "" ?> value="crystal">Crystal pony</option>
                    <option <?= $metadata["species"][0] === "changeling" ? "selected" : "" ?> value="changeling">Changeling</option>
                    <option <?= $metadata["species"][0] === "human" ? "selected" : "" ?> value="human">Human</option>
                    <option <?= $metadata["species"][0] === "merpony" ? "selected" : "" ?> value="merpony">Merpony</option>
                </select>
                <select class="tooltip-nohelp form-select" style='display:inline-block;filter:invert(1) hue-rotate(180deg);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;%23000000&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");' name="species[1]">
                    <option <?= !isset($metadata["species"][1]) || $metadata["species"][1] === "" ? "selected" : "" ?> value="">None</option>
                    <option <?= ($metadata["species"][1] ?? "") === "earth" ? "selected" : "" ?> value="earth">Earth pony</option>
                    <option <?= ($metadata["species"][1] ?? "") === "unicorn" ? "selected" : "" ?> value="unicorn">Unicorn</option>
                    <option <?= ($metadata["species"][1] ?? "") === "pegasus" ? "selected" : "" ?> value="pegasus">Pegasus</option>
                    <option <?= ($metadata["species"][1] ?? "") === "alicorn" ? "selected" : "" ?> value="alicorn">Alicorn</option>
                    <option <?= ($metadata["species"][1] ?? "") === "batpony" ? "selected" : "" ?> value="batpony">Bat pony</option>
                    <option <?= ($metadata["species"][1] ?? "") === "crystal" ? "selected" : "" ?> value="crystal">Crystal pony</option>
                    <option <?= ($metadata["species"][1] ?? "") === "changeling" ? "selected" : "" ?> value="changeling">Changeling</option>
                    <option <?= ($metadata["species"][1] ?? "") === "human" ? "selected" : "" ?> value="human">Human</option>
                    <option <?= ($metadata["species"][1] ?? "") === "merpony" ? "selected" : "" ?> value="merpony">Merpony</option>
                </select>
            </div>
        </div>
        <div style="margin-bottom: 1rem;">
            <b>Alignment</b><br>
            <div style="display: grid; grid-template-columns: repeat(2, 1fr); grid-gap: 10px;">
                <select class="tooltip-nohelp form-select" style='display:inline-block;filter:invert(1) hue-rotate(180deg);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;%23000000&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");' name="alignment[sexual]">
                    <option <?= $metadata["alignment"]["sexual"] === "unsure" ? "selected" : "" ?> value="unsure">Unsure</option>
                    <option <?= $metadata["alignment"]["sexual"] === "aroace" ? "selected" : "" ?> value="aroace">Asexual</option>
                    <option <?= $metadata["alignment"]["sexual"] === "hetero" ? "selected" : "" ?> value="hetero">Heterosexual</option>
                    <option <?= $metadata["alignment"]["sexual"] === "homo" ? "selected" : "" ?> value="homo">Homosexual</option>
                    <option <?= $metadata["alignment"]["sexual"] === "bi" ? "selected" : "" ?> value="bi">Bisexual</option>
                    <option <?= $metadata["alignment"]["sexual"] === "pan" ? "selected" : "" ?> value="pan">Pansexual</option>
                    <option <?= $metadata["alignment"]["sexual"] === "poly" ? "selected" : "" ?> value="poly">Polysexual</option>
                </select>
                <select class="tooltip-nohelp form-select" style='display:inline-block;filter:invert(1) hue-rotate(180deg);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;%23000000&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");' name="alignment[romantic]">
                    <option <?= $metadata["alignment"]["romantic"] === "unsure" ? "selected" : "" ?> value="unsure">Unsure</option>
                    <option <?= $metadata["alignment"]["romantic"] === "aroace" ? "selected" : "" ?> value="aroace">Aromantic</option>
                    <option <?= $metadata["alignment"]["romantic"] === "hetero" ? "selected" : "" ?> value="hetero">Heteroromantic</option>
                    <option <?= $metadata["alignment"]["romantic"] === "homo" ? "selected" : "" ?> value="homo">Homoromantic</option>
                    <option <?= $metadata["alignment"]["romantic"] === "bi" ? "selected" : "" ?> value="bi">Biromantic</option>
                    <option <?= $metadata["alignment"]["romantic"] === "pan" ? "selected" : "" ?> value="pan">Panromantic</option>
                    <option <?= $metadata["alignment"]["romantic"] === "poly" ? "selected" : "" ?> value="poly">Polyromantic</option>
                </select>
            </div>
        </div>
        <p>
            <b>Gender</b><br>
            <input name="gender" class="form-control" style="filter: invert(1) hue-rotate(180deg);" type="text" value="<?= $metadata["gender"] ?? "" ?>">
        </p>

        <hr>

        <h3>Relationships</h3>

        <div class="modal" id="new-relation" data-bs-backdrop="static" data-bs-keyboard="false">
            <div class="modal-dialog">
                <div class="modal-content">

                    <div class="modal-header">
                        <h4 class="modal-title">Add a new <span id="new-relation-type">-</span> for <?= $memberData["display_name"] ?? $memberData["name"] ?></h4>
                        <button id="new-fronter-close" type="button" class="btn-close" data-bs-dismiss="modal"></button>
                    </div>

                    <div class="modal-body">
                        <input type="text" placeholder="Search for a pony..." class="form-control" style="margin-bottom:15px;color:white;background:#111;border-color:#222;" id="search">

                        <div id="list">
                            <div class="list-group">
                                <?php foreach (scoreOrderGlobal() as $member): ?>
                                    <a id="list-pony-<?= $member['id'] ?>" onclick="confirmAdd('<?= $member['system'] ?>/<?= $member['id'] ?>');" class="new-fronter-link list-group-item list-group-item-action"><img src="<?= getAsset($member["system"], $member["id"], "heads") ?>" style="width:24px;"> <?= $member["display_name"] ?? $member["name"] ?></a>
                                <?php endforeach; ?>
                            </div>
                        </div>

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

                </div>
            </div>
        </div>

        <script src="/assets/editor/fuse.js"></script>
        <script>
            window.modal = new bootstrap.Modal(document.getElementById("new-relation"));
            window.currentSelectedValue = null;

            function openAddDialog(value, text) {
                modal.show();
                window.currentSelectedValue = value;
                document.getElementById("new-relation-type").innerText = text;
                document.getElementById("search").value = ""; search({});
                document.getElementById("search").focus();
            }

            window.poniesList = JSON.parse(atob(`<?= base64_encode(json_encode(array_values(scoreOrderGlobal()))) ?>`));
            window.avatars = JSON.parse(atob(`<?php

            $avatars = [];

            foreach (scoreOrderGlobal() as $pony) {
                $avatars[$pony["system"] . "/" . $pony["id"]] = getAsset($pony["system"], $pony["id"]);
            }

            echo(base64_encode(json_encode($avatars))); ?>`))

            const fuse = new Fuse(window.poniesList, {
                includeScore: true,
                keys: [
                    {
                        name: 'name',
                        weight: 1
                    },
                    {
                        name: 'display_name',
                        weight: 1
                    },
                    {
                        name: 'id',
                        weight: 0.7
                    },
                    {
                        name: 'species',
                        weight: 0.5
                    }
                ]
            })

            function search(event) {
                if (event.key === "Enter") {
                    return;
                }

                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) {
                    if (document.getElementById("list-pony-" + result.id)) document.getElementById("search-results").innerHTML += document.getElementById("list-pony-" + result.id).outerHTML;
                }

                console.log(results);

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

            document.getElementById("search").onchange = document.getElementById("search").onkeyup = document.getElementById("search").onkeydown = search;

            document.getElementById("search").addEventListener("keydown", (event) => {
                if (event.key === "Enter") {
                    document.querySelector("#search-results .new-fronter-link").click();
                    event.preventDefault();
                }
            });

            function update(type) {
                document.getElementById(type + "-list").innerHTML = document.getElementsByName(type)[0].value.split(",").map(i => i.trim()).filter(i => i && i.trim() !== "").map(i => `
                <a style="margin-top: 4px;" class="btn btn-dark" onclick="deleteRelation('${type}', '${i}');">
                    <img src="${window.avatars[i]}" style="width: 24px; vertical-align: middle; border-radius: 999px;">
                    <span style="vertical-align: middle; margin-left: 5px;">${window.poniesList.filter(j => j.id === i.split("/")[1])[0]['display_name'] ?? window.poniesList.filter(j => j.id === i.split("/")[1])[0]['name']}</span>
                </a>
                `).join("");
            }

            function confirmAdd(item) {
                document.getElementsByName(window.currentSelectedValue)[0].value += ", " + item;
                update(window.currentSelectedValue);
                window.currentSelectedValue = null;
                modal.hide();
            }

            function deleteRelation(type, relation) {
                let relations = document.getElementsByName(type)[0].value.split(",").map(i => i.trim()).filter(i => i && i !== "");
                relations = relations.filter(i => i !== relation);
                document.getElementsByName(type)[0].value = relations.join(", ");
                update(type);
            }
        </script>

        <?php foreach ([
            $systemID !== $app["other"]["id"] ? [ "sexfriends", "Sexfriends" ] : null,
            [ "marefriends", "Marefriends", "marefriend" ],
            [ "sisters", "Sisters", "sister" ],
            [ "caretakers", "Caretakers", "caretaker" ],
            [ "friends", "Friends", "friend" ],
        ] as $relations): if (isset($relations)): ?>
            <p>
                <b><?= $relations[1] ?></b><br>
                <input name="<?= $relations[0] ?>" type="hidden" value="<?= implode(", ", $metadata[$relations[0]] ?? []) ?>">
                <span id="<?= $relations[0] ?>-list"></span>
                <a style="margin-top: 4px;" class="btn btn-secondary" onclick="openAddDialog('<?= $relations[0] ?>', '<?= $relations[2] ?? '' ?>')">+</a>
                <script>
                    update('<?= $relations[0] ?>');
                </script>
            </p>
        <?php endif; endforeach; ?>

        <hr>

        <h3>Age and interests</h3>

        <p>
            <b>Birth date (use January 1<sup>st</sup> for none, fixed age takes priority over birth year if applicable)</b><br>
            <input name="birth" class="form-control" style="filter: invert(1) hue-rotate(180deg);" type="date" value="<?= $metadata["birth"]["year"] ?? "" ?>-<?= $metadata["birth"]["date"] ?? "" ?>">
        </p>
        <p>
            <b>Age (for ponies with fixed age, takes priority over birth year)</b><br>
            <input name="age" class="form-control" style="filter: invert(1) hue-rotate(180deg);" type="text" pattern="^(-\d{1,2}|\d{1,2}(-\d{1,2}|))$" value="<?= $metadata["birth"]["age"] ?? "" ?>">
        </p>
        <?php if ($systemID !== $app["other"]["id"]): ?>
            <p>
                <b>Primary interest (keep it short)</b><br>
                <input name="interest" class="form-control" style="filter: invert(1) hue-rotate(180deg);" type="text" value="<?= $metadata["interest"] ?? "" ?>">
            </p>
        <?php endif; ?>

        <hr>

        <h3>Toggleable flags</h3>

        <?php

        $flags = json_decode(file_get_contents($_SERVER['DOCUMENT_ROOT'] . "/includes/flags.json"), true);

        foreach ($flags as $id => $name): if (!is_array($name) && !is_null($name)): if (($systemID === $app["other"]["id"] && str_starts_with($name, "!!")) || ($systemID === $app["other"]["id"] && str_starts_with($name, "#")) || ($systemID !== $app["other"]["id"] && !str_starts_with($name, "#"))): ?>
            <label style="margin-bottom:5px;">
                <input <?= (isset($metadata[$id]) && $metadata[$id]) ? "checked" : "" ?> class="form-check-input" type="checkbox" name="flags[<?= $id ?>]">
                <?= str_replace("%other%", $app["other"]["name"], str_starts_with($name, "!!") ? substr($name, 2) : (str_starts_with($name, "#") ? substr($name, 1) : $name)) ?>
            </label><br>
        <?php endif; else: foreach ($name ?? [] as $id2 => $name2): if (!is_array($name2) && !is_null($name2)): if (($systemID === $app["other"]["id"] && str_starts_with($name2, "!!")) || ($systemID !== $app["other"]["id"] && !str_starts_with($name2, "#"))): ?>
            <label style="margin-bottom:5px;">
                <input <?= $metadata[$id][$id2] ? "checked" : "" ?> class="form-check-input" type="checkbox" name="flags[<?= $id ?>][<?= $id2 ?>]">
                <?= str_replace("%other%", $app["other"]["name"], str_starts_with($name2, "!!") ? substr($name2, 2) : $name2) ?>
            </label><br>
        <?php endif; endif; endforeach; endif; endforeach; ?>

        <hr>

        <input name="submit" class="btn btn-outline-primary" value="Save and refresh" type="submit">
    </form>
    <?php else: ?>
    <div class="alert alert-warning">
        This member does not have a metadata file. This file needs to be initially created by an administrator before it can be edited using this page.
    </div>
    <?php endif; ?>
</div>

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