<?php

require_once $_SERVER['DOCUMENT_ROOT'] . "/includes/init.inc"; global $title; global $isLowerLoggedIn; global $isLoggedIn; global $lang; global $pages; global $app;
require_once $_SERVER['DOCUMENT_ROOT'] . "/includes/util/functions.inc";
require_once $_SERVER['DOCUMENT_ROOT'] . "/includes/util/bitset.inc";

if (!isset($_GET['_']) || trim($_GET['_']) === "") peh_error("Invalid request", 400);

$parts = explode("/", $_GET['_']);
array_shift($parts);
array_shift($parts);
$system = $parts[0];
$member = !isset($parts[1]) || $parts[1] === "" ? null : $parts[1];

if ($system !== "cloudburst" && $system !== "raindrops" && $system !== $app["other"]["slug"]) peh_error("Invalid system name: " . $system, 400);
$systemCommonName = $system === "cloudburst" ? "Cloudburst System" : ($system === $app["other"]["slug"] ? $app["other"]["name"] : "Raindrops System");
$systemID = $system === "cloudburst" ? "ynmuc" : ($system === $app["other"]["slug"] ? $app["other"]["id"] : "gdapd");

if ($isLowerLoggedIn && $systemID !== $app["other"]["id"]) {
    header("Location: /");
    die();
}

if ($member === null) {
    header("Location: /");
    die();
} else {
    $members = json_decode(file_get_contents($_SERVER['DOCUMENT_ROOT'] . "/includes/data/" . $systemID . "/members.json"), true);
    $memberData = null;
    $memberCommonName = null;
    $memberID = null;

    foreach ($members as $m) {
        if ($m['name'] === $member) {
            $memberData = $m;
            $memberCommonName = $m['display_name'] ?? $m['name'];
            $memberID = $m['id'];
        }
    }

    if ($memberData === null) {
        peh_error("Not found", 404);
    }

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

        $toUpdate = [];

        header("Content-Type: text/plain");

        if (isset($_GET["bitset"]) && is_numeric($_GET["bitset"])) {
            $toUpdate["bitset"] = (int)$_GET["bitset"];
        }

        if (isset($_GET["food"]) && is_numeric($_GET["food"])) {
            $toUpdate["food"] = (int)$_GET["food"];
        }

        if (isset($_GET["shared_memory"]) && is_numeric($_GET["shared_memory"])) {
            $toUpdate["shared_memory"] = (int)$_GET["shared_memory"];
        }

        if (isset($_GET["species"][0])) {
            if (trim($_GET["species"][0]) === "") {
                $toUpdate["species"][0] = null;
            } else {
                $toUpdate["species"][0] = $_GET["species"][0];
            }
        }

        if (isset($_GET["species"][1])) {
            if (trim($_GET["species"][1]) === "") {
                $toUpdate["species"][1] = null;
            } else {
                $toUpdate["species"][1] = $_GET["species"][1];
            }
        }

        $toUpdate["alignment"] = [];

        if (isset($_GET["alignment"]["sexual"])) {
            $toUpdate["alignment"]["sexual"] = $_GET["alignment"]["sexual"];
        }

        if (isset($_GET["alignment"]["romantic"])) {
            $toUpdate["alignment"]["romantic"] = $_GET["alignment"]["romantic"];
        }

        if (isset($_GET["interest"])) {
            $toUpdate["interest"] = strip_tags($_GET["interest"]);
        }

        if (isset($_GET["gender"])) {
            $toUpdate["gender"] = strip_tags($_GET["gender"]);
        }

        $regex = "/^(ynmuc|gdapd|" . $app["other"]["id"] . ")\/[a-z]{5}$/m";

        if (isset($_GET["marefriends"])) {
            $toUpdate["marefriends"] = array_values(array_filter(array_map(function ($i) { return trim($i); }, explode(",", $_GET["marefriends"])), function ($i) use ($regex) {
                return !!preg_match($regex, $i);
            }));
        }

        if (isset($_GET["sexfriends"])) {
            $toUpdate["sexfriends"] = array_values(array_filter(array_map(function ($i) { return trim($i); }, explode(",", $_GET["sexfriends"])), function ($i) use ($regex) {
                return !!preg_match($regex, $i);
            }));
        }

        if (isset($_GET["sisters"])) {
            $toUpdate["sisters"] = array_values(array_filter(array_map(function ($i) { return trim($i); }, explode(",", $_GET["sisters"])), function ($i) use ($regex) {
                return !!preg_match($regex, $i);
            }));
        }

        if (isset($_GET["caretakers"])) {
            $toUpdate["caretakers"] = array_values(array_filter(array_map(function ($i) { return trim($i); }, explode(",", $_GET["caretakers"])), function ($i) use ($regex) {
                return !!preg_match($regex, $i);
            }));
        }

        if (isset($_GET['regressed'])) {
            if (!!preg_match("/^[a-z]{5}$/m", $_GET['regressed'])) {
                $toUpdate["regression"] = $_GET['regressed'];
            } else {
                $toUpdate["regression"] = null;
            }
        }

        $toUpdate["birth"] = [
            "date" => "01-01",
            "year" => null,
            "age" => 0
        ];

        if (isset($_GET["age"]) && is_numeric($_GET["age"])) {
            $toUpdate["birth"]["age"] = (int)$_GET["age"];
        } else if (isset($_GET["age"]) && preg_match("/^\d{1,2}-\d{1,2}$/", $_GET["age"]) === 1) {
            $toUpdate["birth"]["age"] = $_GET["age"];
        }

        if (isset($_GET["birth"]) && trim($_GET['birth']) !== "" && !!preg_match("/^\d{4}-\d{2}-\d{2}$/m", $_GET['birth'])) {
            $toUpdate["birth"]["year"] = (int)substr($_GET["birth"],0, 4);
            $toUpdate["birth"]["date"] = substr($_GET["birth"],5);
        }

        if (isset($_GET["membc"])) {
            $toUpdate["code"] = $_GET['membc'];
        }

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

        foreach ($flags as $id => $name) if (!is_array($name)) {
            if (isset($_GET['flags'][$id])) {
                $toUpdate[$id] = true;
            } else {
                $toUpdate[$id] = false;
            }
        } else foreach ($name as $id2 => $_) {
            if (isset($_GET['flags'][$id][$id2])) {
                $toUpdate[$id][$id2] = true;
            } else {
                $toUpdate[$id][$id2] = false;
            }
        }

        foreach ($toUpdate as $item => $value) {
            $metadata[$item] = $value;
        }

        if (isset($metadata["bitset"])) unset($metadata["bitset"]);
        if (trim($metadata["species"][1]) === "") unset($metadata["species"][1]);

        file_put_contents($_SERVER['DOCUMENT_ROOT'] . "/includes/data/metadata/" . $memberID . ".json", json_encode($metadata));

        header("Location: /" . $_GET['_']);
    } else {
        require_once $_SERVER['DOCUMENT_ROOT'] . '/includes/fragments/metadata.inc';
    }
}

exit;