<?PHP
/**
 * This file contains all the main functions for the backend.
 *
 * @file
 *
 * @author Joshua Ramon Enslin <joshua@jrenslin.de>
 */

// Include functions from frontend.

require_once __DIR__ . '/../../inc/functions.php';
require_once __DIR__ . '/standardHTML.php';

/**
 * Function for ensuring everything is in order in the backend.
 *
 * @return void
 */
function ensureBackendEnv() {

    // Ensure secure session cookies are used.

    ini_set('session.cookie_secure', '1');
    ini_set('session.cookie_httponly', '1');
    ini_set('session.use_only_cookies', '1');

    // Ensure session is started

    if (session_status() != PHP_SESSION_ACTIVE) {
        session_start();
    }

    include_once __DIR__ . "/../password_protect.php";

}

/**
 * Function that checks all the indexes in the input array for their availability in $_GET or $_POST.
 * If they exist in either, they are written to global variables.
 *
 * @param string[] $vars Input array containing indices, that may be contained in $_GET or $_POST.
 *
 * @return void
 */
function loadHttpToGlobals(array $vars) {

    foreach ($vars as $var) {
        if (isset($_GET[$var])) $GLOBALS[$var] = $_GET[$var];
        else if (isset($_POST[$var])) $GLOBALS[$var] = $_POST[$var];
    }

}

/**
 * Function for loading the language.
 *
 * @return string[]
 */
function loadLanguage():array {

    if (isset($_GET['lan'])) $_SESSION['lan'] = $lan = $_GET['lan'];
    else if (isset($_SESSION['lan'])) $lan = $_SESSION['lan'];

    // Default to English
    if (!isset($lan) or !file_exists(__DIR__ . "/translations/$lan.php")) {
        $lan = "en";
    }

    include __DIR__ . "/../translations/$lan.php";

    return $translations;

}

/**
 * Function for generating caches.
 *
 * @return void
 */
function generateStaticPgCaches() {

    // Create empty arrays
    // Remove existing caches for static pages.

    $targetFiles = [
        "allPages"    => __DIR__ . "/../../data/caches/pages.json",
        "publicPages" => __DIR__ . "/../../data/caches/publicPages.json",
    ];
    foreach ($targetFiles as $key => $file) {
        $$key = [];
        if (file_exists($file)) unlink($file);
    }

    // Read contents.

    $pagesFiles = scanDirConts(__DIR__ . "/../../data/static");

    foreach ($pagesFiles as $file) {
        $jsonData = json_decode(file_get_contents(__DIR__ . "/../../data/static/$file"), true);
        $tData = [
            "id" => str_replace(".json", "", $file), //The ID equals the file name, minus the extension.
            "title" => $jsonData['title'],
            "higher" => $jsonData["higher"],
            "public" => $jsonData["public"],
        ];

        $allPages[$tData["id"]] = $tData;
        if ($tData['public']) $publicPages[$tData["id"]] = $tData;
    }

    // Save to file(s)

    foreach ($targetFiles as $key => $file) {
        file_put_contents($file, json_encode($$key), LOCK_EX);
    }

}

/**
 * Function for storing a post.
 *
 * @param array   $pages  Array of pages.
 * @param array   $inputs Input array.
 * @param integer $id     ID of the currently edited entry. If it is 0, a new one will be set.
 *
 * @return integer
 */
function storePage(array $pages, array $inputs, int $id = 0):int {

    if (!$id) {
        if (count($pages) === 0) {
            $id = 1;
        }
        else $id = max(array_keys($pages)) + 1;
    }

    $filename = __DIR__ . "/../../data/static/$id.json";

    file_put_contents($filename, json_encode(array_merge($inputs)), LOCK_EX);

    generateStaticPgCaches();
    return $id;

}

?>
