<?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", "startPage", "pageTitle", "logo", "url", "css", "hideInstitution", "mdVersion", "mdImgFolder", "cacheRefreshInterval", "limitToInstitutions", "maxFileSize", "sendHTTPHeaders", "CSPimageSources", "CSPobjectSources", "defaultLang"]);

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

    if (isset($defaultLang) and !in_array("$defaultLang.php", scanDirConts(__DIR__ . "/translations"))) {
        $_SESSION["editHistory"] = ["changesAborted", $translations['languageUnavailable']];
        header('Location: settings.php');
    }

    // Ensure that URLs end with a trailing slash.
    if (isset($mdVersion)) $mdVersion = rtrim($mdVersion, "/") . "/";
    if (isset($mdImgFolder)) $mdImgFolder = rtrim($mdImgFolder, "/") . "/";

    if (isset($limitToInstitutions)) $settings['limitToInstitutions'] = array_diff(explode(',', $limitToInstitutions), ['']);
    foreach (["startPage", "pageTitle", "logo", "url", "css", "hideInstitution", "mdVersion", "mdImgFolder", "cacheRefreshInterval", "maxFileSize", "sendHTTPHeaders", "CSPimageSources", "CSPobjectSources", "defaultLang"] as $var) {
        if (isset($$var)) $settings[$var] = $$var;
    }

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

    $_SESSION["editHistory"] = ["changesStored", $translations['settingsUpdated'] . " $username"];
    header('Location: settings.php');
    return;

}

/*
 * Output
 */

echo printBackendHead($settings, $translations['settings'], $translations['settings'], $settings['logo']);
echo printBackendHeader($translations['settings'], $translations['helpSettings']);

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

echo printBackendNav($translations);

echo '
    <main>

    <section id="listUsers">

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

            <tr>
                <th colspan="3" class="sectionTH">' . $translations['general'] . '</th>
            </tr>

            <!-- Start page -->
            <tr>
                <th><label for="startPage">' . $translations['startPage'] . '</label></th>
                <td>
                    <select id="startPage" name="startPage" placeholder="' . $translations['startPage']. '">';
$publicPages = loadPublicPages();
foreach ($publicPages as $page) {
    echo '<option value="' . $page['id'] . '"';
    if (isset($settings['startPage']) and $page['id'] == $settings['startPage']) echo ' selected';
    echo '>' . $page['title'] . '</option>';
}
unset($publicPages);
echo '
 value="'.$settings['url'].'" required />
                    </select>
                </td>
                <td>' . generateHelpToolTip("helpStartPage", $translations['startPage'], $translations['helpStartPage']) . '</td>
            </tr>

            <!-- Page Title -->
            <tr>
                <th><label for="pageTitle">' . $translations['settingsPageTitle'] . '</label></th>
                <td><input type="text" id="pageTitle" name="pageTitle" placeholder="' . $translations['settingsPageTitle']. '" value="'.$settings['pageTitle'].'" required /></td>
                <td>' . generateHelpToolTip("helpSettingsPageTitle", $translations['settingsPageTitle'], $translations['helpSettingsPageTitle']) . '</td>
            </tr>

            <!-- Logo -->
            <tr>
                <th><label for="logo">' . $translations['logo'] . '</label></th>
                <td><input type="text" id="logo" name="logo" placeholder="' . $translations['logo']. '" value="'.$settings['logo'].'" required /></td>
                <td>' . generateHelpToolTip("helpLogo", $translations['logo'], $translations['helpLogo']) . '</td>
            </tr>

            <!-- URL -->
            <tr>
                <th><label for="url">' . $translations['urlAbbr'] . '</label></th>
                <td><input type="url" id="url" name="url" placeholder="' . $translations['url']. '" value="'.$settings['url'].'" required /></td>
                <td>' . generateHelpToolTip("helpURL", $translations['url'], $translations['helpURL']) . '</td>
            </tr>

            <!-- CSS -->
            <tr>
                <th><label for="settingsUsedCSS">' . $translations['settingsUsedCSS'] . '</label></th>
                <td>
                    <select name="css" id="settingsUsedCSS">
                    ';
foreach (scanDirConts(__DIR__ . "/../themes") as $cssOption) {
    if (!is_dir(__DIR__ . "/../themes/$cssOption")) continue;
    echo '<option value="' . $cssOption . '"';
    if ($settings['css'] == $cssOption) echo ' selected';
    echo '>' . $cssOption . '</option>';
}
echo '
                    </select>
                </td>
                <td>' . generateHelpToolTip("helpSettingsUsedCSS", $translations['settingsUsedCSS'], $translations['helpSettingsUsedCSS']) . '</td>
            </tr>

            <tr>
                <th><label for="language">' . $translations['language'] . '</label></th>
                <td>
                    <select name="defaultLang" id="language">
                    ';
foreach (scanDirConts(__DIR__ . "/translations") as $lang) {
    $lang = pathinfo($lang)['filename'];
    echo '<option value="' . $lang . '"';
    if ($settings['defaultLang'] == $lang) echo ' selected';
    echo '>' . $lang . '</option>';
}
echo '
                    </select>
                </td>
                <td>' . generateHelpToolTip("helpLanguage", $translations['language'], $translations['helpLanguage']) . '</td>
            </tr>

            <tr>
                <th colspan="3" class="sectionTH">' . $translations['integrationWithMD'] . '</th>
            </tr>

            <!-- MD Version -->
            <tr>
                <th><label for="mdVersion">' . $translations['mdVersion'] . '</label></th>
                <td><input type="url" id="mdVersion" name="mdVersion" placeholder="' . $translations['mdVersion']. '" value="'.$settings['mdVersion'].'" required /></td>
                <td>' . generateHelpToolTip("helpMDVersion", $translations['mdVersion'], $translations['helpMDVersion']) . '</td>
            </tr>

            <!-- MD Image Folder -->
            <tr>
                <th><label for="mdImgFolder">' . $translations['mdImgFolder'] . '</label></th>
                <td><input type="url" id="mdImgFolder" name="mdImgFolder" placeholder="' . $translations['mdImgFolder']. '" value="'.$settings['mdImgFolder'].'" required /></td>
                <td>' . generateHelpToolTip("helpMDimgFolder", $translations['mdImgFolder'], $translations['helpMDimgFolder']) . '</td>
            </tr>

            <!-- Refresh Interval -->
            <tr>
                <th><label for="cacheRefreshInterval">' . $translations['cacheRefreshInterval'] . '</label></th>
                <td><input type="number" id="cacheRefreshInterval" name="cacheRefreshInterval" placeholder="' . $translations['cacheRefreshInterval']. '" value="'.$settings['cacheRefreshInterval'].'" required /></td>
                <td>' . generateHelpToolTip("helpCacheRefreshInterval", $translations['cacheRefreshInterval'], $translations['helpCacheRefreshInterval']) . '</td>
            </tr>

            <!-- Restricting inputs to given institutions -->
            <tr>
                <th><label for="limitToInstitutions">' . $translations['limitToInstitutions'] . '</label></th>
                <td><input type="text" id="limitToInstitutions" name="limitToInstitutions" placeholder="' . $translations['limitToInstitutions']. '" value="'.implode(',', $settings['limitToInstitutions']).'" /></td>
                <td>' . generateHelpToolTip("helpLimitToInstitutions", $translations['limitToInstitutions'], $translations['helpLimitToInstitutions']) . '</td>
            </tr>

            <!-- Hiding attribution (if the page is for only one museum) or not -->
            <tr>
                <th><label for="hideInstitution">' . $translations['hideInstitution'] . '</label></th>
                <td>
                    <input name="hideInstitution" id="hideInstitution" type="range" min="0" max="1" value="' . (string)$settings['hideInstitution'] . '" />
                </td>
                <td>' . generateHelpToolTip("helpHideInstitution", $translations['hideInstitution'], $translations['helpHideInstitution']) . '</td>
            </tr>

            <tr>
                <th colspan="3" class="sectionTH">' . $translations['security'] . '</th>
            </tr>

            <!-- Max Upload Size -->
            <tr>
                <th><label for="maxFileSize">' . $translations['maxFileSize'] . '</label></th>
                <td><input type="number" id="maxFileSize" name="maxFileSize" placeholder="' . $translations['maxFileSize']. '" value="'.$settings['maxFileSize'].'" required /></td>
                <td>' . generateHelpToolTip("helpMaxFileSize", $translations['maxFileSize'], $translations['helpMaxFileSize']) . '</td>
            </tr>

            <!-- Whether or not to send security-related headers -->
            <tr>
                <th><label for="sendHTTPHeaders">' . $translations['sendHTTPHeaders'] . '</label></th>
                <td>
                    <input name="sendHTTPHeaders" id="sendHTTPHeaders" type="range" min="0" max="1" value="' . (string)$settings['sendHTTPHeaders'] . '" />
                </td>
                <td>' . generateHelpToolTip("helpSendHTTPHeaders", $translations['sendHTTPHeaders'], $translations['helpSendHTTPHeaders']) . '</td>
            </tr>

            <!-- Image sources whitelisted for CSPs -->
            <tr>
                <th><label for="CSPimageSources">' . $translations['CSPimageSources'] . '</label></th>
                <td><input type="text" id="CSPimageSources" name="CSPimageSources" placeholder="' . $translations['CSPimageSources']. '" value="'.$settings['CSPimageSources'].'" /></td>
                <td>' . generateHelpToolTip("helpCSPimageSources", $translations['CSPimageSources'], $translations['helpCSPimageSources']) . '</td>
            </tr>

            <!-- Object and frame sources whitelisted for CSPs -->
            <tr>
                <th><label for="CSPobjectSources">' . $translations['CSPobjectSources'] . '</label></th>
                <td><input type="text" id="CSPobjectSources" name="CSPobjectSources" placeholder="' . $translations['CSPobjectSources']. '" value="'.$settings['CSPobjectSources'].'" /></td>
                <td>' . generateHelpToolTip("helpCSPobjectSources", $translations['CSPobjectSources'], $translations['helpCSPobjectSources']) . '</td>
            </tr>

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

        </table>
        </form>

    </section>

    </main>
</div>';

echo printBackendEnd();

?>
