<?php

/**
 * Includes a PHP file that returns metadata associated with a dynamic page.
 * It simply scopes an external file into a function to prevent variable conflicts.
 *
 * @param string $file The file path to the PHP file that contains metadata.
 * @return array Returns an associative array of metadata from the included PHP file.
 */
function getDynamicMetadata(string $file): array{
    return include($file);
}
/**
 * Extracts and validates the minimal permission level required to access certain content,
 * defaulting to system configuration if not properly set or in case of an error.
 *
 * @param array $metadata Metadata array that should include a 'parameters' key with 'minimal_permission_level'.
 * @return int Returns the minimal permission level required to access a page.
 *@global array $routerConfig Global router configuration settings.
 */
function getDynamicPermission(array $metadata): int {
    global $routerConfig;
    $params = $metadata["parameters"];
    try {
        $permission_level = $params["minimal_permission_level"];

        if (!is_numeric($permission_level) || $permission_level <= 0) {
            $permission_level = $routerConfig["page"]["default_permissions"];
        }
    }
    catch (Exception){
        $permission_level = $routerConfig["page"]["default_permissions"];
    } finally {
        return $permission_level;
    }
}
/**
 * Generates HTML navigation links for all sites and pages configured in the router,
 * adjusting active states based on current request and filtering links by user permissions.
 *
 * @global array $routerConfig Global configuration that includes directory paths and default settings.
 * @global array $routerRequest Current request details including site and page name.
 * @return string Returns the HTML string of the navigation menu.
 */
function generateNavigation(): string
{
    global $routerConfig;
    global $routerRequest;

    $nav = file_get_contents($routerConfig["template_dir"] . "nav.html");
    $site_dirs = array_diff(scandir($routerConfig["page_dir"]), array('.', '..'));

    $nav_out = "";

    foreach ($site_dirs as $site_dir) {
        $pages_dir = array_diff(scandir($routerConfig["page_dir"] . $site_dir), array('.', '..'));

        $site_name = str_replace("_", " ", $site_dir);

        $site_name = ucfirst($site_name);

        $site_location = "/" . $site_dir . "/" . $routerConfig["default_page"];

        if ($routerRequest["site_name"] == $site_dir) {
            //this is the current page
            $site_class = "class=\"navsite_link active\"";
        }
        else{
            $site_class = "class=\"navsite_link\"";
        }

        $navigation_pages = "";

        foreach ($pages_dir as $page_file) {
            $page_file_tmp = explode(".", $page_file);
            $page_basename = $page_file_tmp[0];
            $page_class = "class=\"navpage_link\"";
            if ($routerRequest["site_name"] == $site_dir && $routerRequest["page_name"] == $page_basename) {
                $page_class = "class=\"navpage_link active\"";
            }

            $page_location = "/" . $site_dir . "/" . $page_basename;

            $page_name = str_replace("_", " ", $page_basename);
            $page_name = explode(".", $page_name)[0];
            $page_name = ucfirst($page_name);

            $page_file_path = $routerConfig["page_dir"] . $site_dir . "/" . $page_file ;
            if($page_file_tmp[1] == "html"){
                $page_tmp = file_get_contents($page_file_path);

                $pageMetadata = parsePageTag($page_tmp);
                if(!empty($pageMetadata["parameters"]["minimal_permission_level"])){
                    $page_required_permission = intval($pageMetadata["parameters"]["minimal_permission_level"]);
                }
                else{
                    $page_required_permission = $routerConfig["page"]["default_permissions"];
                }
                if(!empty($pageMetadata["parameters"]["page_title"])){
                    $page_name = $pageMetadata["parameters"]["page_title"];
                }
            }
            elseif($page_file_tmp[1] == "php"){
                $pageMetadata = getDynamicMetadata($page_file_path);
                $page_required_permission = getDynamicPermission($pageMetadata);

                if(!empty($pageMetadata["parameters"]["page_title"])){
                    $page_name = $pageMetadata["parameters"]["page_title"];
                }
            }
            else{
                $page_required_permission = $routerConfig["page"]["default_permissions"];
            }


            if($page_required_permission <= $_SESSION["privilege_level"]) {
                $navpage_attributes = "data-site='$site_dir' data-page='$page_basename'";
                $navigation_pages .= "<li class='navpage_item' $navpage_attributes ><a $navpage_attributes href='$page_location' $page_class>$page_name</a></li>";
            }
        }
        if(!empty($navigation_pages)){
            $default_page = $routerConfig["default_page"];
            $navsite_attributes = "data-page='$default_page' data-site='$site_dir'";
            $nav_out .= "<li class='navsite_item' ><a $navsite_attributes href='$site_location' $site_class>$site_name</a><ul class='navpage_list'>$navigation_pages</ul></li>";
        }
    }

    return str_replace("__NAV_PAGES__", $nav_out, $nav);
}
/**
 * Provides a simple API endpoint-like response for fetching generated navigation HTML.
 * Wraps generateNavigation for an API.
 *
 * @return array Returns an associative array with the navigation HTML and a status indicating success.
 */
function getNavigationEndpoint() :array{
    return [
        "Status" => "Success",
        "Navigation" => generateNavigation(),
    ];
}