<?php

/**
 * @class SiteMenuRender
 * @description This class is responsible for rendering the site menu using Twig templates. when the load_site_menu
 *              hook is called in the loader.
 * @author Nithika Senaweera <nithika.senaweera@mtc.co.uk>
 * @copyright MTC Media
 * @date 2025-05-27
 * @version 2.0
 * */
namespace Mtc\Plugins\SiteMenu\Classes;
use GuzzleHttp\Client;
use Twig\Environment;


class SiteMenuRender {

    protected $template_location;
    protected $is_https;
    protected $host;
    protected $api_path;
    protected $client;

    /**
     * Constructs the URL for the API endpoint.
     *
     * @return string The constructed URL.
     */
    private static function constructUrl(string $api_path, string $function) : string {
        $is_https = $_SERVER['HTTPS'] ?? null;
        $host = $_SERVER['HTTP_HOST'];
        $http_type = ($is_https === 'on') ? "https://" : "http://";
        return $http_type . $host . $api_path . $function;
    }

    /**
     * @description Renders the menu layout using Twig templates.
     * @param array $menu_data The menu data to render.
     * @param Environment $twig The Twig environment instance.
     * @return void
     * @throws \Exception If the template rendering fails.
     * */
    private static function renderTemplate($menu_data, $template_location, Environment $twig) : void
    {
        echo $twig->render($template_location, [
            'items' => $menu_data,
        ]);
    }

    /**
     * Renders the menu using Twig templates.
     *
     * @param string $name The name of the menu to render.
     * @param Environment $twig The Twig environment instance.
     */
    public static function renderMenu($name, Environment $twig) : void
    {
        $template_location = 'view/menu.twig';

        $api_path = "/site-menu/";
        $function = 'children-by-name/';

        $url = self::constructUrl($api_path, $function);
        $client = new \GuzzleHttp\Client();

        try {
           $response = $client->request('POST', $url,
           [
               'json' => [
                   'name' => $name,
               ]
           ]
           );

           $data = json_decode($response->getBody(), true);
           self::renderTemplate($data, $template_location, $twig);
        } catch (\Exception $e) {
            echo "Failed to load menu: " . $e->getMessage();
        }
    }
};


?>
