<?php

include_once(dirname(__FILE__).'/../nmGen.class.php');

class nmGenNavMenu extends nmGen
{

    var $arr_menu_data;
    var $menu_itens;
    var $user_items;
    var $tb_itens;
    var $layout;
    var $theme;
    var $moustache_replacements = [];
    var $moustache_inactive = [];

    public function writeMain()
    {
//        $htmlData = $this->readHTML();
//        $jsMainData = $this->readJSMain();
//        $jsAppData = $this->readJS();
//        $cssData = $this->readCSS();
//        $cssMainData = $this->readCSSMain();
//        $this->writeItemsData($attr_menu_itens);
//        //$this->writeApplicationInit($this->main_file);
//        $this->appendToMainFile($htmlData);
//        $this->appendJSToMainFile('var items_data = '.json_encode($attr_menu_itens));
//        $this->appendJSToMainFile('var user_menu_data = '.json_encode($user_items));
//        $this->appendJSToMainFile($jsAppData);
//        $this->appendJSToMainFile($jsMainData);
//        $this->appendCSSToMainFile($cssData);

    }
    function loadData($arq, $data)
    {
        parent::loadData($arq, $data);
        $this->loadItens();
        $this->verifyMoustacheVars();
    }

    public function checkHeaderString() {
        $string_place = $this->arr_menu_data['header_string_pos'];

        $is_horizontal = $this->arr_menu_data['layout'] == 'H';
        $has_split = $this->arr_menu_data['check_split'] == 'S';
        $has_tb = $this->arr_menu_data['check_toolbar'] == 'S';

        if ($is_horizontal) {
            if ($has_split) {
                $string_place = 'H';
            }
        } else {
            if (!$has_tb) {
                $string_place = 'M';
            }
        }

        if ($string_place == 'M') {
            $this->moustache_inactive[] = 'header_string_h_placement';
        } else {
            $this->moustache_inactive[] = 'header_string_m_placement';
        }
    }

    public function checkUseTabs() {
        if ($this->app_data['menu_parms1']['open_itens_tab'] != 'S') {
            $this->moustache_inactive[] = 'tabs_placement';
        }
        if ($this->app_data['menu_parms1']['show_breadcrumbs'] != 'S') {
            $this->moustache_inactive[] = 'breadcrumbs_placement';
        }
    }
    public function verifyMoustacheVars() {
        $this->checkUseTabs();
        $this->checkHeaderString();
        $this->moustache_replacements = [
            'tabs_placement' => $this->buildTabsHTML(),
            'breadcrumbs_placement' => $this->buildBreadcrumbsHTML(),
            'header_string_h_placement' => $this->buildHeaderString('h'),
            'header_string_m_placement' => $this->buildHeaderString('m'),
            'themes-panel' => $this->buildPanelHTML('themes'),
            'languages-panel' => $this->buildPanelHTML('languages'),
            'fav-panel' => $this->buildPanelHTML('fav'),
            'search-panel' => $this->buildPanelHTML('search'),
            'menu_theme' => $this->theme,
            'username' =>  $this->buildVarReading('username'),
            'userimage' => $this->buildVarReading('userimage'),
            'userdesc' => $this->buildVarReading('userdesc'),
            'header_string' =>  $this->buildVarReading('header_string'),
            'logo' => "<?php echo \"" . $this->arr_menu_data['logo'] . "\"; ?>",
            'logo_compact' => "<?php echo \"" . $this->arr_menu_data['logo_compact'] . "\"; ?>",
        ];
    }
    public function renderMoustacheVars(&$htmlData) {

        foreach ($this->moustache_replacements as $k => $v) {
            $replacement = $v;
            if (in_array($k, $this->moustache_inactive)) {
                $replacement = '';
            }
            $htmlData = str_replace('{{'.$k.'}}', $replacement, $htmlData);
        }
    }
    public function loadItens() {
        $this->arr_menu_data = json_decode(json_encode($this->app_data['arr_apldata']['MenuItens']), true);
        $this->menu_itens = $this->arr_menu_data['items'];
        $this->user_items = $this->arr_menu_data['user_items'];
        $this->tb_itens = $this->arr_menu_data['user_items'];
        $this->theme = $this->arr_menu_data['theme'];

        $this->layout = 'desktop_h_resp';

        if ($this->arr_menu_data['layout'] == 'H') {
            if ($this->arr_menu_data['check_split'] == 'S') {
                $this->layout = 'desktop_h_split';
            }
        } else {
            if ($this->arr_menu_data['check_toolbar'] == 'S') {
                if ($this->arr_menu_data['layout_usr_pos'] == 'in') {
                    $this->layout = 'desktop_v_user_toolbar';
                } else {
                    $this->layout = 'desktop_v_toolbar';
                }
            } else {
                $this->layout = 'desktop_v_user';
            }
        }

    }

    public function buildHeaderString($pos) {
        $panelHTML = '';
        $panelHTML .= file_get_contents(dirname(__FILE__).'/common/header_string_'.$pos.'.php');
        return $panelHTML;
    }
    public function buildPanelHTML($panelName) {
        $panelHTML = '';
        $panelHTML .= file_get_contents(dirname(__FILE__).'/common/panels/'.$panelName.'.php');
        return $panelHTML;
    }
    public function buildTabsHTML() {
        $tabsHTML = ' ';
        $tabsHTML .= file_get_contents(dirname(__FILE__).'/common/tabs.php');
        $tabsHTML .= " <script> ";
        $tabsHTML .= file_get_contents(dirname(__FILE__).'/common/tabs.js');
        $tabsHTML .= " </script> ";

        return $tabsHTML;
    }
    public function buildBreadcrumbsHTML() {
        $bcHTML = ' ';
        $bcHTML .= file_get_contents(dirname(__FILE__).'/common/breadcrumbs.php');
        $bcHTML .= " <script> ";
        $bcHTML .= file_get_contents(dirname(__FILE__).'/common/breadcrumbs.js');
        $bcHTML .= " </script> ";

        return $bcHTML;
    }
    public function getData() {
        return $this->arr_menu_data;
    }
    public function buildVarReading($varname) {
        global $apl_charset;
        $ret = $varname;
        if (is_string( $this->arr_menu_data[$varname])) {
            $ret = preg_replace_callback('/\[([A-Za-z_]{1}\w*)\]/', function ($match) {
/*                return '<?php echo $this->sc_temp_' . $match[1] . '; ?>';*/
                return $match[1];
            }, $this->arr_menu_data[$varname]);
        }
        $conv_ini = '';
        $conv_end = '';
        if (strpos($ret, '$_SESSION') === false && $apl_charset != 'UTF-8') {
            $conv_ini = "mb_convert_encoding(";
            $conv_end = ", '$apl_charset', 'UTF-8')";

            $ret = json_encode($ret, 2097152);
            $ret = substr($ret, 1, -1);
            $ret = str_replace('\\/','/',  $ret);
            $ret = preg_replace_callback('/\\\\u([0-9a-fA-F]{4})/', function ($match) {
                return '&#x'.$match[1].';';
            }, $ret);
        }

/*        return  "<?php echo ".$conv_ini."\"" . $ret . "\"".$conv_end."; ?>";*/
        return  "<?php echo \"" . $ret ."\"; ?>";
    }
    public function readHTML() {
        $htmlData = file_get_contents(dirname(__FILE__).'/templates/'.$this->layout.'/index.php');
        $this->renderMoustacheVars($htmlData);
        return $htmlData;
    }
    public function readJSMain() {
        $jsAppData = file_get_contents(dirname(__FILE__).'/common/sc-menu.class.js');
        $jsAppData .= file_get_contents(dirname(__FILE__).'/common/main.js');
        return $jsAppData;
    }
    public function readCSSMain() {
        $jsAppData = file_get_contents(dirname(__FILE__).'/common/sc-menu.class.css');
        $jsAppData .= file_get_contents(dirname(__FILE__).'/common/themes.css');
        $jsAppData .= file_get_contents(dirname(__FILE__).'/common/common.css');
        return $jsAppData;
    }
    public function readJS() {
        $jsAppData = file_get_contents(dirname(__FILE__).'/templates/'. $this->layout.'/assets/sc-menu.class.js');
        return $jsAppData;
    }

    public function readCSS() {
//        $cssData = file_get_contents(dirname(__FILE__).'/templates/'. $this->layout.'/assets/sc-menu.class.css');
        $cssData = '';
        return $cssData;
    }

    public function buildItemsData() {
        return $this->arrayToNotation($this->menu_itens);
    }

    public function writeItemsData() {
        $this->appendPHPToMainFile("\$menu_items = ".$this->buildItemsData());
    }

    public function writeApplicationInit($arq) {
        $nm_php_codigo = $this->app_data['nm_php_codigo'];
        $nome_classe = $this->app_data['nome_classe'];

        $nmgp_tem_redirect = false;
        if (isset($nm_php_codigo['onApplicationInit']) && !empty($nm_php_codigo['onApplicationInit']))
        {
            $_SESSION['scriptcase']['evt_process'] = "Evt.onApplicationInit:";
            $nmgp_formula = $nm_php_codigo['onApplicationInit'];
            $nmgp_formula = str_replace("sc_redirect", "sc_redir", $nmgp_formula);
            $nmgp_formula = str_replace("sc_redir", "sc_redirect", $nmgp_formula);
            nm_formula_php($nmgp_formula, "menu", "0");
            if ($nmgp_tem_redirect)
            {
                $nmgp_formula = str_replace("\$_SESSION['scriptcase']['sc_apl_menu_link']", "\$" . $nome_classe . "_menuData['url']['link']", $nmgp_formula);
                $nmgp_formula = str_replace('_form_php.php', '.php', $nmgp_formula);
            }
            $nmgp_formula = str_replace("\$this->Ini->path_link", "\$path_link", $nmgp_formula);
            $nmgp_formula = str_replace("\$this->Campos_Mens_erro", "\$Campos_Mens_erro", $nmgp_formula);
            $nmgp_formula = str_replace("\$this->Ini->sc_page", "'1'", $nmgp_formula);
            $nmgp_formula = str_replace("\$this->Ini->", "\$this->", $nmgp_formula);
            $this->appendToFile($arq, "<?php ");
            $this->appendToFile($arq, "      " . $nmgp_formula . "\r\n");
            $this->appendToFile($arq, " ?> ");
        }
    }

}

?>