<?php

use idoit\Component\Helper\Purify;

/**
 * i-doit
 *
 * Breadcrumb Navigation: Hierarchical View of Links in the Banner
 *
 * @internal
 * @package     i-doit
 * @subpackage  Components_Template
 * @copyright   synetics GmbH
 * @license     http://www.i-doit.com/license
 */
class isys_component_template_breadcrumb
{
    private $includeHome = false;

    /**
     * Sets the option to include the "home" segment to the breadcrumb.
     *
     * @param bool $include
     *
     * @return $this
     */
    public function includeHome(bool $include): self
    {
        $this->includeHome = $include;

        return $this;
    }

    /**
     * @param bool        $plain
     * @param string|null $append
     * @param int|null    $moduleId
     * @param string|null $prepend
     *
     * @return string
     * @throws isys_exception_general
     */
    public function process(bool $plain, string|null $append, int|null $moduleId, string|null $prepend)
    {
        global $g_dirs;

        $l_out = '';

        if ($this->includeHome) {
            $l_out = '<li><a href="' . isys_application::instance()->www_path . '" class="home btn btn-secondary" data-tooltip="1" title="Home">' .
                '<img src="' . $g_dirs['images'] . 'axialis/construction/house-4.svg" alt="i-doit" />' .
                '</a></li>';
        }

        // Determine module manager as "first level".
        $l_modman = isys_module_manager::instance();

        // Retrieve the current module.
        if (!empty($moduleId)) {
            $l_actmod = $moduleId;
        } else {
            if (!$l_modman) {
                $l_actmod = defined_or_default('C__MODULE__CMDB');
            } else {
                $l_actmod = $l_modman->get_active_module();
            }
        }

        if ($l_actmod) {
            // Return active module register entry.
            $l_modreg = $l_modman->get_by_id($l_actmod);

            if (is_object($l_modreg) && $l_modreg->is_initialized()) {
                // Asking module for its breadcrumb navigation.
                $l_modobj = $l_modreg->get_object();

                // The module data includes the module title
                $l_moddata = $l_modreg->get_data();
                $l_strTitle = $l_moddata["isys_module__title"];

                // Build first entry of breadcrumb.
                $l_req_gets = isys_module_request::get_instance()
                    ->get_gets();
                $l_req_gets = Purify::castIntValues($l_req_gets);

                $l_gets = [];
                $l_gets[C__GET__MODULE_ID] = $l_actmod;

                // This is for 'Templates' and 'Mass changes', because both functions are using the same module class.
                if (isset($l_req_gets[C__GET__MODULE]) && $l_modobj instanceof isys_module_templates) {
                    if ($l_req_gets[C__GET__MODULE] == defined_or_default('C__MODULE__CMDB')) {
                        $l_strTitle = 'LC__MASS_CHANGE';
                    } else {
                        $l_strTitle = 'LC__MODULE__TEMPLATES';
                    }
                }

                // Append URL
                if ($plain) {
                    $l_out .= isys_application::instance()->container->get('language')->get($l_strTitle) . ' > ';
                } else {
                    if ($prepend) {
                        $l_out .= $prepend;
                    }

                    // Build URL for GET-Parameters of module.
                    $url = isys_glob_build_url(isys_glob_http_build_query($l_gets));

                    // @see ID-8897 Fix for add-ons with 'rewritten' URLs.
                    if (defined(get_class($l_modobj) . '::MAIN_MENU_REWRITE_LINK') && constant(get_class($l_modobj) . '::MAIN_MENU_REWRITE_LINK')) {
                        $url = isys_application::instance()->www_path . $l_modobj->getIdentifier();
                    }

                    $l_out .= $this->buildLink($url, $l_strTitle);
                }

                if ($l_modobj instanceof isys_module) {
                    /**
                     * breadcrumb_get has to return following data structure:
                     *
                     * [
                     *    [
                     *       "MeinObjekt" => [
                     *          "moduleID" => 2,
                     *          "objID"    => 3,
                     *          "viewMode" => C__CMDB__VIEW__CATEGORY_GLOBAL,
                     *          "treeMode" => C__CMDB__VIEW__TREE_OBJECT
                     *       ]
                     *    ],
                     *    ...
                     * ];
                     */

                    $l_bc_data = $l_modobj->breadcrumb_get($_GET);

                    if ($l_bc_data && is_array($l_bc_data)) {
                        // Iterating through breadcrumb entries.
                        foreach ($l_bc_data as $l_bc_no => $l_bc_info) {
                            $l_bc_title = key($l_bc_info);
                            $l_bc_gets = current($l_bc_info);

                            // Build URL.
                            $l_bc_url = isys_glob_build_url(isys_glob_http_build_query($l_bc_gets));

                            if ($plain) {
                                $l_out .= $prepend . $l_bc_title . $append;
                                continue;
                            }

                            if ($prepend) {
                                $l_out .= $prepend;
                            }

                            if (($l_bc_no < count($l_bc_data) - 1)) {
                                $l_out .= $this->buildLink($l_bc_url, $l_bc_title);

                                /* .. and append URL for this entry */
                                if ($append == null) {
                                    $l_out .= " > ";
                                } else {
                                    $l_out .= $append;
                                }
                            } else {
                                if ($prepend) {
                                    $l_out .= '<strong>' . $l_bc_title . '</strong>';
                                } else {
                                    $l_current_url = str_replace("&ajax=1", "", $_SERVER["QUERY_STRING"]);
                                    $l_current_url = str_replace("&request=breadcrumb", "", $l_current_url);

                                    $l_out .= $this->buildLink(isys_glob_build_url($l_current_url), $l_bc_title);
                                }
                            }
                        }
                    }
                }
            }
        }

        return $l_out . ((isset($append) && !$plain) ? $append : '');
    }

    /**
     * @param string $url
     * @param string $title
     *
     * @return string
     * @throws Exception
     */
    private function buildLink(string $url, string $title): string
    {
        $languageManager = isys_application::instance()->container->get('language');

        if (!empty($title)) {
            $title = $languageManager->get(html_entity_decode(stripslashes($title), ENT_COMPAT, BASE_ENCODING));
        }

        if (empty($title)) {
            $title = $languageManager->get('LC__NAVIGATION__BREADCRUMB__NO_TITLE');
        }

        if (strpos($title, '<') !== false || strpos($title, '>') !== false) {
            $title = htmlentities($title, ENT_QUOTES, BASE_ENCODING);
        }

        if (empty($url)) {
            return $title;
        }

        if (strpos($url, '/') !== 0) {
            $url = isys_application::instance()->www_path . $url;
        }

        return "<a href=\"{$url}\">{$title}</a>";
    }
}
