<?PHP
/**
 * Start page of the backend.
 * Offers a dashboard.
 *
 * @author Joshua Ramon Enslin <joshua@jrenslin.de>
 */

/*
 * Require files and ensure environment.
 */

require_once __DIR__ . "/inc/functions.php";

ensureEnvironment();            // Ensure existence of system files.
$translations = loadLanguage(); // Load translations.
ensureBackendEnv();             // Ensure session is started etc.
$pages = loadPages();           // Load overview of pages.

/*
 * Load data.
 */

// Check for vars.
loadHttpToGlobals(["task", "username", "realName", "email", "password", "passwordVerify", "admin"]);

if (!isset($users)) {
    $users = json_decode(file_get_contents(__DIR__ . "/../data/users.json"), true);
}

if (isset($task) and $task == "insert") { // Adding new users.

    $redirectURL = "./users.php?" . write_common_vars(["username", "realName", "email", "admin"]) . "#addUser";

    if (!isset($admin)) $admin = false;

    // Ensure all required values are set.
    foreach (["username", "realName", "email", "password", "passwordVerify"] as $var) {
        if (isset($$var)) continue;

        $_SESSION["editHistory"] = ["changesAborted", $translations['requiredValueMissing']];
        header('Location: ' . $redirectURL);
        return;
    }

    // Check if the passwords match.
    if ($password != $passwordVerify) {
        $_SESSION["editHistory"] = ["changesAborted", $translations['passwordsDoNotMatch']];
        header('Location: ' . $redirectURL);
        return;
    }

    // Check if passwords is too short.
    if (strlen($password) < 8) {
        $_SESSION["editHistory"] = ["changesAborted", $translations['passwordTooShort']];
        header('Location: ' . $redirectURL);
        return;
    }

    // Options for hashing.
    $newUser = array(

        "username" => $username,
        "realName" => $realName,
        "email"    => $email,
        "password" => password_hash("$password", PASSWORD_BCRYPT, ['cost' => 12]),
        "admin"    => $admin,
        "created"  => date("Y-m-d H:i:s"),

    );

    $users[$username] = $newUser;

    // Store the users array.
    file_put_contents(__DIR__ . "/../data/users.json", json_encode($users), LOCK_EX);

    $_SESSION["editHistory"] = ["changesStored", $translations['userAdded'] . " $username"];
    header('Location: ./users.php#addUser');
    return;

}

/*
 * Output
 */

echo printBackendHead($settings, $translations['start'], $translations['start'], $settings['logo']);
echo printBackendHeader($translations['usersOverview'], $translations['helpUsers']);

echo '
<div id="mainWrapper">
';

echo printBackendNav($translations);

echo '
    <main>

    <p>
        <a href="#listUsers" class="buttonLike">' . $translations['listUsers'] . '</a>
        <a href="#addUser" class="buttonLike">' . $translations['addUser'] . '</a>
    </p>

    <section id="listUsers">

        <form action="" method="POST">
        <table class="obj_cha_maintable">

            <tr>
                <th><label for="username">' . $translations['username'] . '</label></th>
                <td><input type="text" id="username" name="username" placeholder="' . $translations['username']. '"';
if (isset($username)) echo " value='$username'";
echo ' required /></td>
                <td>' . generateHelpToolTip("helpUsername", $translations['username'], $translations['helpUsername']) . '</td>
            </tr>

            <tr>
                <th><label for="realName">' . $translations['realName'] . '</label></th>
                <td><input type="text" id="realName" name="realName" placeholder="' . $translations['realName']. '"';
if (isset($realName)) echo " value='$realName'";
echo ' required /></td>
                <td>' . generateHelpToolTip("helpRealName", $translations['realName'], $translations['helpRealName']) . '</td>
            </tr>

            <tr>
                <th><label for="userEmail">' . $translations['email'] . '</label></th>
                <td><input type="email" id="userEmail" name="email" placeholder="' . $translations['email']. '"';
if (isset($email)) echo " value='$email'";
echo ' required /></td>
                <td>' . generateHelpToolTip("helpEmail", $translations['email'], $translations['helpEmail']) . '</td>
            </tr>

            <tr>
                <th><label for="password">' . $translations['password'] . '</label></th>
                <td><input type="password" id="password" name="password" placeholder="' . $translations['password']. '" required /></td>
                <td>' . generateHelpToolTip("helpPassword", $translations['password'], $translations['helpPassword']) . '</td>
            </tr>

            <tr>
                <th><label for="passwordVerify">' . $translations['passwordVerify'] . '</label></th>
                <td><input type="password" id="passwordVerify" name="passwordVerify" placeholder="' . $translations['passwordVerify']. '" required /></td>
                <td></td>
            </tr>

            <tr>
                <th><label for="admin">' . $translations['admin'] . '</label></th>
                <td>
                    <label class="switch">
                        <input name="admin" id="admin" type="checkbox"'; if (isset($admin) and $admin) echo ' checked'; echo '>
                        <span class="slider round"></span>
                    </label>
                </td>
                <td>' . generateHelpToolTip("helpAdmin", $translations['admin'], $translations['helpAdmin']) . '</td>
            </tr>

            <tr>
                <th></th>
                <td><button type="submit">' . $translations['submit'] . '</button></td>
                <td>
                    ' . printHiddenInputs(['task' => 'insert'], 16) . '
                </td>
            </tr>

        </table>
        </form>

    </section>

    <section>

    <table class="overviewtable">
        <thead>
            <tr>
                <th>' . $translations['username'] . '</th>
                <th>' . $translations['realName'] . '</th>
                <th>' . $translations['email'] . '</th>
                <th>' . $translations['admin'] . '</th>
                <th>' . $translations['options'] . '</th>
            </tr>
        </thead>
        <tbody>
';

foreach ($users as $user) {

    echo '
            <tr>
                <td><a href="user.php?t=' . urlencode($user['username']) . '">' . $user['username'] . '</a></td>
                <td>' . $user['realName'] . '</td>
                <td>' . $user['email'] . '</td>
                <td>' . $user['admin'] . '</td>
                <td></td>
            </tr>
    ';

}

echo '
        </tbody>
    </table>

    </section>

    </main>
</div>';

echo printBackendEnd();

?>
