<?php

/**
 * Initializes the routing system for a web application. This function processes the incoming
 * URL and determines the site name and page name based on the configuration and the URL structure.
 * It handles default configurations and supports different types of requests like API or page requests.
 *
 * @global array $routerConfig The global configuration array that includes default site and page settings.
 * @return array Returns an associative array containing the routing information, including the site name,
 *               page name, request type, and parsed request address from the HTTP host.
 */
function initRouter(): array
{
    global $routerConfig;
    $routerRequest = array();

    $routerRequest["requestAddress"] = array_slice(explode('.', $_SERVER['HTTP_HOST']), -3, 3); //get the last 3 elements

    $request_uri = explode("/", $_SERVER["QUERY_STRING"]);

    $request_uri = array_slice($request_uri, -3, 3);


    $routerRequest["site_name"] = $routerConfig["default_site"];
    $routerRequest["page_name"] = $routerConfig["default_page"];

    if(count($request_uri) > 2){
        $routerRequest["page_name"] = basename($request_uri[2]);
    }
    if(count($request_uri) > 1){
        $routerRequest["site_name"] = basename($request_uri[1]);

    }

    if($_SERVER["REQUEST_METHOD"] == "POST"){
        $routerRequest["type"] = "api";
    }

    if(empty($routerRequest["type"])) {
        $routerRequest["type"] = "page";
    }

    return $routerRequest;
}


