<?php

/**
 * Generate the global context for Mustache.
 */
function getstachecontext(): array {
    global $_SETTINGS;
    $context = [];
    foreach ($_SETTINGS["context"] as $key => $val) {
        $context[$key] = $val;
    }
    return $context;
}

function stacheify(string $content, $template = "", $context = null): string {
    global $_SETTINGS, $STACHECONTEXT;
    if (!is_array($context)) {
        $context = $STACHECONTEXT;
    }

    $options =  ['extension' => '.html'];
    $m = new Mustache_Engine([
        'partials_loader' => new Mustache_Loader_FilesystemLoader(__DIR__ . "/../../" . $_SETTINGS["source_folder"] . "/includes", $options)
    ]);

    if (!empty($template)) {
        $template = file_get_contents(__DIR__ . "/../../" . $_SETTINGS["source_folder"] . "/template/" . $template . ".html");
        $context["page_content"] = $content;
        return $m->render($template, $context);
    }

    return $m->render($content, $context);
}
