<?php
/**
 * Ce script contient la définition de la classe 'layout_antares'.
 *
 * @package framework_openmairie
 * @version SVN : $Id: om_layout_antares.class.php 5178 2025-10-30 18:11:12Z ebrodin $
 */

/**
 * Définition de la classe 'layout_antares'.
 */
class layout_antares extends layout_base {

    /**
     *
     */
    var $layout = "antares";
    /**
     *
     */
    var $stylesheet = "";

    var $app_logo = "../app/img/logo.png";
    var $html_head_css = array(
        10 => array(
            "../lib/remixicon/fonts/remixicon.css",  
            "../lib/inter-ui/inter.css",
        ), 
        20 => array(
            "../lib/antares/assets/css/style.css",
        ),
        30 => array(
            "../app/css/style.css",
        ),
    );

    /**
     *
     */
    var $html_head_js = array();

    public function __construct($layout_type = null) {
        // Charger uniquement les vendors en mode popup
        if (isset($_GET['popup']) && $_GET['popup'] === '1') {
            $this->html_head_css = array(
                20 => array(
                    "../lib/antares/assets/css/style-embedded.css",
                ),
            );
        }

        $this->html_head_js = array(
            10 => array(
                "../lib/jquery/jquery.min.js",
                "../lib/jquery-thirdparty/jquery.form.js",
                "../lib/jquery-thirdparty/jquery.collapsible.js",
                "../lib/jquery-thirdparty/jquery-minicolors/jquery.minicolors.min.js",
                "../lib/jquery-thirdparty/jquery.autosize-min.js",
            ),
            20 => array(
                "../lib/om-assets/js/layout_jqueryui_before.js",
                "../lib/jquery-ui/jquery.ui.datepicker-fr.min.js",
                "../lib/tinymce/tinymce.min.js",
                "../lib/jquery-ui/jquery-ui.min.js",
                "../lib/om-assets/js/".LOCALE.".js",
                "../lib/om-assets/js/layout_jqueryui_after.js",
                "../lib/antares/assets/js/index.js",
            ),
            30 => array(
                "../app/js/script.js",
            )
        );
    }

    /**
     * Affiche le logo de l'application avec un lien vers le tableau de bord.
     *
     * @return void
     */
    public function display_logo(): void {
        if ($this->get_parameter("application") === "Framework openMairie") {
            $this->app_logo = "../lib/antares/assets/img/logo.png";
        }

        $appName = htmlspecialchars($this->get_parameter("application"), ENT_QUOTES, 'UTF-8');
        $dashboardUrl = htmlspecialchars($this->get_parameter("url_dashboard"), ENT_QUOTES, 'UTF-8');
        $dashboardTitle = htmlspecialchars(__("Tableau de bord"), ENT_QUOTES, 'UTF-8');

        echo sprintf(
            '<div id="logo">
                <h1>
                    <a class="logo" href="%s" title="%s - %s">
                        <img src="%s" alt="%s" class="logo" />
                        <span class="sr-only">%s</span>
                    </a>
                </h1>
            </div>',
            $dashboardUrl,
            $appName,
            $dashboardTitle,
            htmlspecialchars($this->app_logo, ENT_QUOTES, 'UTF-8'),
            $appName,
            $appName
        );
    }

    // {{{ STRUCTURE GENERALE DE LA PAGE

    /**
     * Affiche le header : logo, actions, raccourcis, menu, contenu et titre.
     * Ne s'affiche que si le header HTML a été affiché et que le header ne l'a pas encore été.
     *
     * @return void
     */
    public function display_header(): void {
        if ($this->header_displayed !== false || $this->html_header_displayed !== true) {
            return;
        }

        // Start header
        echo <<<'HTML'
<!-- ########## START HEADER ########## -->
<header id="header" role="banner">
	<div class="header-left-container">

HTML;

        // Menu toggle (only if user is logged in)
        if (!empty($_SESSION['login'])) {
            $menuToggleLabel = htmlspecialchars(__("Menu"), ENT_QUOTES, 'UTF-8');
            echo <<<HTML
		<input type="checkbox" id="menu-toggle" aria-hidden="true" />
		<label id="menu-toggle-label" for="menu-toggle" aria-label="{$menuToggleLabel}">
			<i id="menu-toggle-icon" class="ri-menu-fold-line" aria-hidden="true"></i>
		</label>

HTML;
        }

        // Logo
        $this->display_logo();

        // Close left container, open right container
        echo <<<'HTML'
	</div>
	<div class="header-right-container">

HTML;

        // Actions and shortlinks
        $this->display_actions();
        $this->display_shortlinks();

        // Close right container
        echo <<<'HTML'
	</div>

HTML;

        // User menu
        $this->display_responsive_user_menu();

        // Close header
        echo <<<'HTML'
</header>
<!-- ########## END HEADER ########## -->

HTML;

        // Display remaining sections
        $this->display_menu();
        $this->display_content_start();
        $this->display_page_title();
        $this->header_displayed = true;
    }

    /**
     * Cette méthode permet d'afficher le début de la section contenu
     */
    public function display_content_start() {
        //
        echo "<!-- ########## START CONTENT ########## -->\n";
        echo "<div id=\"content\"";
        echo " class=\"ui-widget ui-widget-content ui-corner-all";
        // XXX
        if ($this->get_parameter("flag") == "htmlonly"
            || $this->get_parameter("flag") == "htmlonly_nodoctype"
            || $this->get_parameter("flag") == "nohtml"
            || $this->get_parameter("flag") == "login_and_nohtml"
            || count($this->get_parameter("menu")) == 0) {
             echo " nomenu";
        }
        echo "\"";
        echo ">\n\n";
    }

    // }}} STRUCTURE GENERALE DE LA PAGE - END

    public function display_start_fieldset($params = array()) {
        // XXX Rétro-compatibilité
        if (count($params) == 0) {
            //
            echo "<fieldset class=\"collapsible\">\n";
            //
            echo "\t<legend class=\"ui-corner-all ui-widget-content ui-state-active\">";
            //
            return;
        }
        //
        if (!isset($params["fieldset_class"])) {
            $params["fieldset_class"] = "";
        }
        $params["fieldset_class"] .= " cadre ui-corner-all ui-widget-content";
        //
        if (!isset($params["legend_class"])) {
            $params["legend_class"] = "";
        }
        $params["legend_class"] .= " ui-corner-all ui-widget-content ui-state-active";
        //
        parent::display_start_fieldset($params);
    }

    // {{{ NEW

    /**
     * Affiche une liste d'éléments sous forme de carte cliquable.
     *
     * @param array $params Tableau contenant 'title' et 'list'
     * @return void
     */
    public function display_list($params) {
        $title = htmlspecialchars($params["title"] ?? '', ENT_QUOTES, 'UTF-8');
        $class = htmlspecialchars($params["class"] ?? '', ENT_QUOTES, 'UTF-8');

        echo sprintf(
            '<section class="list-container %s" aria-labelledby="list-title">
                <h2 id="list-title" class="list-title">%s</h2>
                <ul class="list-choices" role="list">',
            $class,
            $title
        );    
        foreach ($params["list"] as $value) {
            $linkHref = htmlspecialchars($value["href"] ?? '#', ENT_QUOTES, 'UTF-8');
            $linkTitle = htmlspecialchars($value["title"] ?? '', ENT_QUOTES, 'UTF-8');
            $linkClass = htmlspecialchars($value["class"] ?? '', ENT_QUOTES, 'UTF-8');
            $linkId = htmlspecialchars($value["id"] ?? '', ENT_QUOTES, 'UTF-8');

            // Only add target="_blank" if explicitly set in the value array (Edition only)
            $targetAttr = '';
            if (isset($value["target"]) && $value["target"] === "blank") {
                $targetAttr = ' target="_blank" rel="noopener noreferrer"';
            }

            echo sprintf(
                '<li class="list-choice">
                    <a href="%s" class="choice-link %s" id="%s"%s>
                        <span class="choice-title">%s</span>
                    </a>',
                $linkHref,
                $linkClass,
                $linkId,
                $targetAttr,
                $linkTitle
            );

            if (isset($value["links"]) && is_array($value["links"]) && count($value["links"]) > 0) {
                echo '<div class="choice-actions">';
                foreach ($value["links"] as $link) {
                    $this->display_link($link);
                }
                echo '</div>';
            }

            echo '</li>';
        }

        echo '</ul></section>';
    }

    // }}}

    /**
     * @ignore
     */
    function display__form_input_submit($params) {
        if (isset($params["id"])
            && ($params["id"] == "adv-search-submit"
                || $params["id"] == "search-submit")) {
            echo "\t\t<button type=\"submit\" id=\"".$params["id"]."\" name=\"".$params["name"]."\">";
            echo __("Recherche");
            echo "</button>\n";
            return;
        }
        parent::display__form_input_submit($params);
    }

    /**
     * @ignore
     */
    function display__form_controls_container__begin($params = null) {
        printf(
            '<div class="formControls%s">',
            (isset($params["controls"]) ? " formControls-".$params["controls"] : "")
        );
    }

            /**
     * Affiche le nom de l'utilisateur connecté dans le menu utilisateur responsive.
     * Retourne un élément <li> contenant le login de la session courante.
     *
     * @return string HTML de l'élément <li> avec le login utilisateur
     */
    public function display_action_login_responsive() {
        return sprintf(
            '<li class="action-login">%s</li>',
            $_SESSION['login']
        );
    }

    /**
     * Affiche le nom de la collectivité dans le menu utilisateur responsive.
     * Si la clé "ville" existe dans le paramètre "collectivite",
     * la fonction retourne un élément <li> contenant le nom de la ville.
     *
     * @return string HTML de l'élément <li> ou rien si non défini
     */
    public function display_action_collectivite_responsive() {
        $collectivite = $this->get_parameter("collectivite");
        if (isset($collectivite["ville"])) {
            return sprintf(
                '<li class="action-collectivite">%s</li>',
                $collectivite["ville"]
            );
        }
        return "";
    }

    /**
     * Génère un lien HTML pour le menu utilisateur responsive.
     * Les paramètres permettent de personnaliser l'adresse, l'id, la classe CSS, la cible, le titre et la description du lien.
     *
     * @param array $params Tableau associatif contenant les propriétés du lien :
     *   - href : adresse du lien (obligatoire)
     *   - id : identifiant HTML (optionnel)
     *   - class : classe(s) CSS (optionnel)
     *   - target : cible du lien (optionnel)
     *   - title : texte affiché dans le lien (obligatoire)
     *   - description : info-bulle (optionnel)
     * @return string HTML du lien ou chaîne vide si href absent
     */
    public function display_link_responsive($params) {
        $title  = isset($params['description']) ? $params['description'] : "";
        $class  = isset($params['class']) ? $params['class'] : "";
        $target = isset($params['target']) ? $params['target'] : "";
        $id     = isset($params['id']) ? $params['id'] : "";

        if (isset($params['href'])) {
            return sprintf(
                '<a href="%s" id="%s" class="%s" target="%s" title="%s">%s</a>',
                $params['href'],
                $id,
                $class,
                $target,
                $title,
                $params['title']
            );
        }
        return "";
    }


    /**
     * Génère la liste des liens utilisateur (raccourcis ou actions personnelles) pour le menu responsive.
     *
     * @param string $type        Type de liens à afficher (ex : 'raccourcis', 'actions_personnelles').
     * @param string $type_class  Classe CSS à utiliser pour le type de liens (optionnel).
     * @return string             HTML des éléments <li> contenant les liens.
     */
    public function display_header_user_links($type, $type_class = "") {
        $links = "";
        if ($type_class === "") {
            $type_class = $type;
        }

        foreach ($this->get_parameter($type) as $key => $value) {
            $class = isset($value['class']) ? $value['class'] : "";
            $links .= sprintf(
                '<li class="%s-list-elem user-%s">%s</li>',
                $type_class,
                $class,
                $this->display_link_responsive($value)
            );
        }
        return $links;
    }


    /**
     * Affiche le menu utilisateur responsive dans l'en-tête.
     * Ce menu inclut les informations de connexion, la collectivité,
     * les raccourcis et les actions personnelles de l'utilisateur.
     * Le menu n'est affiché que si des actions personnelles sont définies.
     */
    public function display_responsive_user_menu() {
        if (count($this->get_parameter("actions_personnelles")) == 0) {
            return;
        }

        echo sprintf(
            '<button id="user-menu-button" popovertarget="user-menu" class="">
                <i class="ri-user-3-fill"></i>
            </button>
            <div popover id="user-menu">
                <ul class="user-menu-info">
                    %s
                    %s
                </ul>
                <ul class="user-menu-actions">
                    %s
                    %s
                </ul>
            </div>',
            $this->display_action_login_responsive(),
            $this->display_action_collectivite_responsive(),
            $this->display_header_user_links("raccourcis", "shortlinks"),
            $this->display_header_user_links("actions_personnelles")
        );
    }

        /**
     * Affichage du menu
     */
    public function display_menu(): void {
        //
        if ($this->get_parameter("menu") == NULL) {
            return;
        }

        // Initialisation des variables de menu
        $menuOpen = null;

        echo "<!-- ########## START MENU ########## -->\n";
        echo "<nav id=\"menu\" aria-label=\"" . htmlspecialchars(__("Menu principal"), ENT_QUOTES, 'UTF-8') . "\">\n";

        echo "<ul id=\"menu-list\">\n";

        // Boucle sur les rubriques
        foreach ($this->get_parameter("menu") as $m => $rubrik) {
            // Check if any link inside this rubrik is actually selected
            $hasSelectedLink = false;
            if (isset($rubrik['links']) && is_array($rubrik['links'])) {
                foreach ($rubrik['links'] as $link) {
                    if (isset($link["selected"])) {
                        $hasSelectedLink = true;
                        break;
                    }
                }
            }

            if ($hasSelectedLink || isset($rubrik["selected"])) {
                $menuOpen = $m;
            }

            $link_class = isset($rubrik['class']) && $rubrik['class'] != "" ? " {$rubrik['class']}-20" : "";

            echo "\t<li class=\"rubrik" . htmlspecialchars($link_class, ENT_NOQUOTES, 'UTF-8') . "\">\n";

            // Titre de la rubrique - Using button for accordion functionality
            $headerTitle = isset($rubrik['description']) && $rubrik['description'] != ""
                ? htmlspecialchars($rubrik['description'], ENT_QUOTES, 'UTF-8')
                : '';

            echo "\t\t<button type=\"button\"";
            echo " class=\"rubrik-header" . htmlspecialchars($link_class, ENT_NOQUOTES, 'UTF-8') . "\"";
            if ($headerTitle != '') {
                echo " title=\"" . $headerTitle . "\"";
            }
            echo ">\n";

            // Affichage du titre avec lien
            if (isset($rubrik['href']) && $rubrik['href'] != "" && $rubrik['href'] != "#") {
                echo "\t\t\t<a href=\"" . htmlspecialchars($rubrik['href'], ENT_QUOTES, 'UTF-8') . "\"";
                echo " class=\"rubrik" . htmlspecialchars($link_class, ENT_NOQUOTES, 'UTF-8') . "\"";
                echo ">";
                echo htmlspecialchars($rubrik['title'], ENT_NOQUOTES, 'UTF-8');
                echo "</a>\n";
            } else {
                echo "\t\t\t<a href=\"#\" class=\"rubrik" . htmlspecialchars($link_class, ENT_NOQUOTES, 'UTF-8') . "\"";
                echo ">";
                echo htmlspecialchars($rubrik['title'], ENT_NOQUOTES, 'UTF-8');
                echo "</a>\n";
            }

            echo "\t\t</button>\n";

            //
            if (count($rubrik['links']) != 0) {
                // Contenu de la rubrique
                echo "\t\t<div class=\"rubrik-content\">\n";
                echo "\t\t\t<ul class=\"rubrik\">\n";

                // Boucle sur les entrees de menu
                foreach ($rubrik['links'] as $link) {
                    // Vérifier si c'est un séparateur
                    $isSeparator = (trim($link['title']) == "<hr />"
                        || trim($link['title']) == "<hr/>"
                        || trim($link['title']) == "<hr>");

                    if ($isSeparator) {
                        echo "\t\t\t\t<li class=\"elem hr\" role=\"separator\" aria-hidden=\"true\"><hr /></li>\n";
                    } else {
                        // Entree de menu normale
                        $elemClass = "elem";
                        if (isset($link["selected"])) {
                            $elemClass .= " ui-state-focus";
                        }
                        if (isset($link['class'])) {
                            $elemClass .= " " . $link['class'];
                        }

                        echo "\t\t\t\t<li class=\"" . htmlspecialchars($elemClass, ENT_NOQUOTES, 'UTF-8') . "\">";

                        if (isset($link["href"])) {
                            echo "<a";
                            if (isset($link['class']) && $link['class'] != "") {
                                echo " class=\"" . htmlspecialchars($link['class'], ENT_QUOTES, 'UTF-8') . "-16\"";
                            }
                            echo " href=\"" . htmlspecialchars(html_entity_decode($link['href'], ENT_QUOTES | ENT_HTML5, 'UTF-8'), ENT_QUOTES, 'UTF-8') . "\"";
                            if (isset($link['target']) && $link['target'] != "") {
                                echo " target=\"" . htmlspecialchars($link['target'], ENT_QUOTES, 'UTF-8') . "\"";
                            }
                            if (isset($link['description']) && $link['description'] != "") {
                                echo " title=\"" . htmlspecialchars($link['description'], ENT_QUOTES, 'UTF-8') . "\"";
                            }
                            if (isset($link["selected"])) {
                                echo " aria-current=\"page\"";
                            }
                            echo ">";
                            echo htmlspecialchars($link['title'], ENT_NOQUOTES, 'UTF-8');
                            echo "</a>";
                        } else {
                            echo "<span>" . htmlspecialchars($link['title'], ENT_NOQUOTES, 'UTF-8') . "</span>";
                        }

                        echo "</li>\n";
                    }
                }

                // Fin de la rubrique
                echo "\t\t\t</ul>\n";
                echo "\t\t</div>\n";
            }

            // Fermeture de la rubrique
            echo "\t</li>\n";
        }

        // Fin du menu
        echo "</ul>\n";

        // Données pour JavaScript (accessible mais masqué visuellement)
        if ($menuOpen !== null) {
            echo "<span id=\"menuopen_val\" class=\"sr-only\" hidden aria-hidden=\"true\">"
                . htmlspecialchars($menuOpen, ENT_QUOTES, 'UTF-8')
                . "</span>\n";
        }

        echo "</nav>\n";
        echo "<!-- ########## END MENU ########## -->\n";
    }

    public function display_formulaire_portlet_start($params = array()) {
        // affichage du portlet d'actions contextuelles
        echo sprintf(
            '<div id="%1$s_portlet-actions" class="ui-widget-content ui-corner-all ui-state-default">
                <input type="checkbox" name="portlet-dropdown" class="portlet-dropdown" id="%1$s_portlet_dropdown_button"> 
                <label for="%1$s_portlet_dropdown_button" class="display_portlet__label button-primary">
                    <i class="ri-more-2-line" style="font-size:16px"></i>
                     Actions
                </label>
                <ul class="%1$s_portlet-list">',
            $_GET["obj"]
        );
    }

        protected function display_html_header_htmltag() {
        //
        echo "<html lang=\"fr\">\n";
    }
}
