<?php

// SCSS Compilieren:
//http://leafo.github.io/scssphp/docs/example.html
use Leafo\ScssPhp\Compiler;

/**
 * FR_Presenter_smarty
 *
 * @author Dirk Herbes <d.herbes@fair-computer.de>
 * @copyright Dirk Herbes <d.herbes@fair-computer.de>
 * @package Framework
 * @filesource
 */
require_once(SMARTY_DIR . 'Smarty.class.php');
  require_once _HM_BASE . '/includes/scssphp2/scss.inc.php';
                            use ScssPhp\ScssPhp\Compiler as BS5Compiler;

/**
 * FR_Presenter_smarty
 *
 * By default we use Smarty as our websites presentation layer (view). Smarty
 * is a robust compiling template engine with an active community.
 *
 * @author Dirk Herbes <d.herbes@fair-computer.de>
 * @package Framework
 * @link http://smarty.php.net
 */
class FR_Presenter_smarty extends FR_Presenter_localization {

    private $template = null;
    private $path = null;

    public function __construct(FR_Module $module) {

        parent::__construct($module);

        $this->path = _HM_BASE . '/tpl/' . FR_TEMPLATE;
        $this->template = new Smarty();
        $this->template->left_delimiter = '[%';
        $this->template->right_delimiter = '%]';
        $this->template->template_dir = $this->path . '/' . 'templates';
        $this->template->compile_dir = $this->path . '/' . 'templates_c';
        $this->template->cache_dir = $this->path . '/' . 'cache';
        $this->template->config_dir = $this->path . '/' . 'config';
        $this->template->auto_literal = false;
        //$this->template->compile_locking = false;

        $this->template->assign('CSSTEMPLATE', CSSTEMPLATE);

        if (@$_SESSION['GlobalConnect'] == 1) {
            $baseurl = @$_SESSION['BaseURL'];
            $this->template->assign('junction', trim(@$_SESSION['Junction']));
        } else {
            if (defined("GLOBALCONNECT_IP") && $_SERVER['REMOTE_ADDR'] == GLOBALCONNECT_IP) {
                $baseurl = GLOBALCONNECT_URL;
            } else {
                $baseurl = (isset($_SERVER['HTTPS'])) ? 'https://' : 'http://';
                $baseurl .= $_SERVER['HTTP_HOST'] . '/';
            }
        }
        $baseurl = urldecode($baseurl);
        $this->template->assign('portalurl', $baseurl);
    }

    public function display() {
        if (defined("BOOTSTRAP") && BOOTSTRAP == 1) {
            $this->displayBootstrap();
        } else {
            $this->displayFCS();
        }
    }

    public function displayFCS() {
        $path = _HM_BASE . '/modules/' . $this->module->moduleName . '/tpl';
        $BootstrapPath = _HM_BASE . '/modules/' . $this->module->moduleName . '/bs_tpl';
        if (defined("BOOTSTRAP") && BOOTSTRAP == 1 && file_exists($BootstrapPath)) {
            $path = $BootstrapPath;
        }
        $tplFile = $this->module->tplFile;

        $uri = @$_SERVER['REQUEST_URI'];
        $uri = preg_replace('/language=.*&|language=.*$/Uis', '', $uri);
        if (substr($uri, -1) == '?') {
            $uri = substr($uri, 0, -1);
        }

        $uri_clue = (strpos($uri, '?') !== false) ? '&' : '?';


        $module_name = $this->module->moduleName;
        $class_name = $this->module->className;
        $event_name = $this->module->eventName;


        $url = $module_name;
        if ($class_name != $module_name)
            $url .= '/' . $class_name;
        if ($event_name != '__default')
            $url .= '/' . $event_name;
        $url .= '.html';
        $this->template->assign('baseurl', $this->module->baseurl);
        $this->template->assign('gb', $url);
//            $this->template->assign('gbclue', $uri_clue);
        $this->template->assign('modulePath', $path);
        $this->template->assign('tplFile', $tplFile);

        $this->template->assign('user', $this->user);

        $this->template->assign('session', $this->session);
        $this->template->assign('AssetDesk', (defined('ASSETDESK') && ASSETDESK == 1) ? 1 : 0 );

        // Base Template Settings
        $this->template->assign('show_language', $this->module->show_language);
        $this->template->assign('show_font', $this->module->show_font);
        $this->template->assign('show_help', $this->module->show_help);
        $this->template->assign('show_print', $this->module->show_print);
        $this->template->assign('page_title', $this->module->page_title);
        $this->template->assign('portal_name', (defined("FR_PORTAL_NAME")) ? FR_PORTAL_NAME : '');


        foreach ($this->module->getData() as $var => $val) {
            if (!in_array($var, array('path', 'tplFile'))) {
                $this->template->assign($var, $val);
            }
        }

        $content = $this->template->fetch($path . '/' . $tplFile);
        $this->template->assign('content', $content);


        //Benutzerdefinierte-Styleanpassungen:
        try {
//$debugOutput[] = "<h2>angepasste Styles</h2>";
            if (is_writable(_HM_BASE . '/' . _HM_STYLEPATH)) {
//$debugOutput[] = "<br/>".__LINE__.": Stylepfad ist beschreibbar";
                if (!isset($_SESSION['LoadedStyle']) || !file_exists(_HM_BASE . "/" . $_SESSION['LoadedStyle'])) {
//$debugOutput[] = "<br/>".__LINE__.": Datei f�r Style [".$_SESSION['LoadedStyle']."] existiert nicht... ";
                    $LoadedStyle = $this->tools->getStyle();
//$debugOutput[] = "<br/>".__LINE__.": Style [".$LoadedStyle['StyleName']."] soll verwendet werden und wurde aus DB geladen... ";
//$debugOutput[] = "<pre>";
                    $this->log->log("STYLEs: " . json_encode($LoadedStyle));
//$debugOutput[] = "</pre>";
                    if (isset($LoadedStyle['Definitions']) && $this->tools->FCS_Count($LoadedStyle['Definitions']) && isset($LoadedStyle['Definitions']['StyleName']) && isset($LoadedStyle['Definitions']['CreateDate'])) {
//$debugOutput[] = "<br/>".__LINE__.":Style [".$LoadedStyle['Definitions']['StyleName']."] wird verarbeitet... ";
                        $PathToStyle = _HM_STYLEPATH . $LoadedStyle['Definitions']['StyleName'] . ".css";
                        $filename = _HM_BASE . "/" . $PathToStyle;
//$debugOutput[] = " ".$this->tools->ToUnixTimestamp($LoadedStyle['CreateDate'])."==".$LoadedStyle['Definitions']['CreateDate']." ?";
                        if (!file_exists($filename) || filemtime($filename) < $LoadedStyle['Definitions']['CreateDate']) {
//$debugOutput[] = "<br/>".__LINE__.": Datei existiert nicht oder ist �lter als Definition [".$LoadedStyle['CreateDate']."] aus DB ... ";
                            //jk 12.06.2014: LESS f�r CSS-Templates einbinden:
                            // http://leafo.net/lessphp/docs/
                            require_once _HM_BASE . '/includes/lessc.inc.php';
                            $less = new lessc;

                            $less->setVariables($LoadedStyle['Definitions']);
                            @unlink($filename);
                            $less->setFormatter("compressed");
                            $less->checkedCompile(_HM_BASE . "/styles/less/screen.less", $filename);
//$debugOutput[] = "<br/>".__LINE__.": Style compiliert und Datei [$filename] neu angelegt ...";
                        }
                    }
                } else {
                    $PathToStyle = $_SESSION['LoadedStyle'];
                    $filename = _HM_BASE . "/" . $PathToStyle;
//$debugOutput[] = "<br/>".__LINE__.": Style compiliert und Datei [$filename] wird verwendet.";
                }

                if (isset($filename) && file_exists($filename)) {
//$debugOutput[] = "<br/>".__LINE__.": Pfad [$PathToStyle] wurde als LESSStylePath ans Template �bergeben.";
                    $this->template->assign("LESSStylePath", $PathToStyle);
                    $_SESSION['LoadedStyle'] = $PathToStyle;
                }
            }
        } catch (Exception $exc) {
//$debugOutput[] = "<br/>".__LINE__.": Exception beim laden des Styles aufgetreten: ";
            echo $exc->getTraceAsString();
        }
        //Nachrichtenwesen:
        $ShowMessages = (defined("SHOWMESSAGES") && SHOWMESSAGES == 0) ? false : true;
        $this->template->assign("ShowMessages", $ShowMessages);

        if ($this->module->pageTemplateFile == null) {
            $pageTemplateFile = 'page.tpl';
        } else {
            $pageTemplateFile = $this->module->pageTemplateFile;
        }

        // header('Content-type: text/html; charset=utf-8');
        $this->template->display($pageTemplateFile);
    }

    public function displayBootstrap() {
       // if (!file_exists( _HM_STYLEPATH)) {
         //   mkdir(_HM_STYLEPATH, 0777, true);
       // }
       // echo _HM_STYLEPATH;
        $path = _HM_BASE . '/modules/' . $this->module->moduleName . '/tpl';
        $BootstrapPath = _HM_BASE . '/modules/' . $this->module->moduleName . '/bs_tpl';
        if (defined("BOOTSTRAP") && BOOTSTRAP == 1 && file_exists($BootstrapPath)) {
            $path = $BootstrapPath;
        }
        $tplFile = $this->module->tplFile;

        $uri = @$_SERVER['REQUEST_URI'];
        $uri = preg_replace('/language=.*&|language=.*$/Uis', '', $uri);
        if (substr($uri, -1) == '?') {
            $uri = substr($uri, 0, -1);
        }

        $uri_clue = (strpos($uri, '?') !== false) ? '&' : '?';


        $module_name = $this->module->moduleName;
        $class_name = $this->module->className;
        $event_name = $this->module->eventName;


        $url = $module_name;
        if ($class_name != $module_name)
            $url .= '/' . $class_name;
        if ($event_name != '__default')
            $url .= '/' . $event_name;
        $url .= '.html';
        $this->template->assign('baseurl', $this->module->baseurl);
        $this->template->assign('gb', $url);
//            $this->template->assign('gbclue', $uri_clue);
        $this->template->assign('modulePath', $path);
        $this->template->assign('tplFile', $tplFile);

        $this->template->assign('user', $this->user);
        $this->template->assign('Tools', $this->tools);
        if (defined('EDITORFONT') && EDITORFONT != '') {
            $editorFonts = array();
            $editorFont = explode(';', EDITORFONT);

            foreach ($editorFont as $fontAndDescr) {

                $arr = explode(',', trim($fontAndDescr));

                $font = array();
                if (count($arr) == 2) {
                    $font['code'] = trim($arr[0]);
                    $font['name'] = trim($arr[1]);

                    $editorFonts[] = $font;
                }
            }

            $this->template->assign('EditorFonts', $editorFonts);
            if (count($editorFonts) > 0) {
                $this->template->assign('EditorStandardFont', $editorFonts[0]);
            }
        }

        $this->template->assign('session', $this->session);
        $this->template->assign('AssetDesk', (defined('ASSETDESK') && ASSETDESK == 1) ? 1 : 0 );

        // Base Template Settings
        $this->template->assign('show_language', $this->module->show_language);
        $this->template->assign('show_font', $this->module->show_font);
        $this->template->assign('show_help', $this->module->show_help);
        $this->template->assign('show_print', $this->module->show_print);
        $this->template->assign('page_title', $this->module->page_title);
        $this->template->assign('portal_name', (defined("FR_PORTAL_NAME")) ? FR_PORTAL_NAME : '');


        foreach ($this->module->getData() as $var => $val) {
            if (!in_array($var, array('path', 'tplFile'))) {
                $this->template->assign($var, $val);
            }
        }

        $content = $this->template->fetch($path . '/' . $tplFile);
        $this->template->assign('content', $content);


        //Benutzerdefinierte-Styleanpassungen:
        try {
//AlteS StyleDatei löschen, wenn nicht bootstrap:
            if (strpos(file_get_contents(_HM_STYLEPATH . "Default.css"), "Bootstrap  v5.3.0") === false) {
                unlink(_HM_STYLEPATH . "Default.css");
            }

            $debugOutput[] = "<h2>angepasste Styles</h2>";
            if ($_GET['module'] != 'installation' && is_writable(_HM_PUBLIC . '/' . _HM_STYLEPATH)) { // Beim Aufruf des installation-Moduls soll er nicht prüfen, ob es angepasste Styles gibt
                $debugOutput[] = "<br/>" . __LINE__ . ": Stylepfad ist beschreibbar";
                if (!isset($_SESSION['LoadedStyle']) || !file_exists(_HM_BASE . "/" . $_SESSION['LoadedStyle']) || (is_writable(_HM_PUBLIC . DS . _HM_STYLEPATH) && !file_exists(_HM_PUBLIC . "/" . $_SESSION['LoadedStyle']))) {
                    $debugOutput[] = "<br/>" . __LINE__ . ": Datei für Style [" . $_SESSION['LoadedStyle'] . "] existiert nicht... ";
                    $LoadedStyle = $this->tools->getStyle();
                    $debugOutput[] = "<br/>" . __LINE__ . ": Style [" . $LoadedStyle['StyleName'] . "] soll verwendet werden und wurde aus DB geladen... ";
                    $debugOutput[] = "<pre>";
                    $debugOutput[] = print_r($LoadedStyle, true);
                    $tmp = $LoadedStyle['Definitions'];
                    foreach ($tmp as $key => $value) {
                        $tmp2[str_replace('_', '-', $key)] = $value;
                    }
                    $LoadedStyle['Definitions'] = $tmp2;
                    $debugOutput[] = "</pre>";
                    if (isset($LoadedStyle['Definitions']) && $this->tools->FCS_Count($LoadedStyle['Definitions']) && isset($LoadedStyle['Definitions']['StyleName']) && isset($LoadedStyle['Definitions']['CreateDate'])) {
                        $debugOutput[] = "<br/>" . __LINE__ . ":Style [" . $LoadedStyle['Definitions']['StyleName'] . "] wird verarbeitet... ";
                        $PathToStyle = _HM_STYLEPATH . $LoadedStyle['Definitions']['StyleName'] . ".css";
                        $filename = _HM_BASE . "/" . $PathToStyle;
                        $filenameLaravel = _HM_PUBLIC . "/" . $PathToStyle;

                        $debugOutput[] = " " . $this->tools->ToUnixTimestamp($LoadedStyle['CreateDate']) . "==" . $LoadedStyle['Definitions']['CreateDate'] . " ?";
                        if (
                                (!file_exists($filename) || filemtime($filename) < $LoadedStyle['Definitions']['CreateDate']) || (is_writable(_HM_PUBLIC . DS . _HM_STYLEPATH) && !file_exists($filenameLaravel))
                        ) {
                            $debugOutput[] = "<br/>" . __LINE__ . ": Datei existiert nicht oder ist �lter als Definition [" . $LoadedStyle['CreateDate'] . "] aus DB ... ";
                            //jk 12.06.2014: LESS f�r CSS-Templates einbinden:
                            // http://leafo.net/lessphp/docs/
                            $debugOutput[] = "<br/>" . __LINE__ . ": Dateieinbinden: " . _HM_BASE . '/includes/scssphp/scss.inc.php';


                            $debugOutput[] = "<br/>" . __LINE__ . ": scssphp eingebunden ... ";
                            $scss = new BS5Compiler();
                            $debugOutput[] = "<br/>" . __LINE__ . ": scssphp erstellt ... ";
//$scss->setImportPaths('scss/');
//echo  "<br/>".__LINE__." Compiliert ".$scss->compile('@import "bootstrap.scss";');
// ALTE BS3 SCSS
                           // $sass_directory = 'styles' . DS . 'bootstrap-sass' . DS . 'assets' . DS . 'stylesheets';
                            // NEUE BS5 SCSS
                            $sass_directory = 'bootstrap_sass';
                            $scss->setImportPaths($sass_directory);
                            $debugOutput[] = "<br/>" . __LINE__ . ": pfad gesetzt ... ";
// will search for 'assets/stylesheets/mixins.scss'
//echo  "<br/>".__LINE__." Compiliert ".$scss->compile('@import "_bootstrap.scss";');
//$server = new scss_server("stylesheets", null, $scss);
//echo $server->serve();
//
//exit;
//                            $less->setVariables($LoadedStyle['Definitions']);
//Das f�r SCSS:
                            @unlink($filename);

//                            $less->setFormatter("compressed");
//                            $less->checkedCompile(_HM_BASE . "/styles/less/screen.less", $filename);
                            //$css = $scss->compile('@import "_bootstrap.scss";');

                            $scss->setVariables($LoadedStyle['Definitions']);


 //                           $css = $scss->compile('@import "_custom.scss";');
                            $css = $scss->compile('@import "custom.scss";');
//echo $css;
                            file_put_contents($filename, $css);

                            //Die Datei auch im Laravel-Public-Verzeichnis anlegen:
                            if (is_writable(_HM_PUBLIC . DS . _HM_STYLEPATH)) {
                                @unlink($filenameLaravel);
                                file_put_contents($filenameLaravel, $css);
                            }
                            $debugOutput[] = "<br/>" . __LINE__ . ": Style compiliert und Datei [$filename] sowie [$filenameLaravel] neu angelegt ...";


//                            $scss->setVariables($LoadedStyle['Definitions']);
//                            $wysiwyg_css = $scss->compile('@import "wysiwyg.scss";');
//                            file_put_contents(_HM_BASE . "/" ._HM_STYLEPATH."wysiwyg.css", $wysiwyg_css);
                        }
                    }
                } else {
                    $PathToStyle = $_SESSION['LoadedStyle'];
                    $filename = _HM_BASE . "/" . $PathToStyle;
                    $filenameLaravel = _HM_PUBLIC . DS . $PathToStyle;

            if (strpos(file_get_contents($filenameLaravel), "Bootstrap  v5.3.0") === false) {
                        unlink($filenameLaravel);
                        echo "Die CSS-Dateien werden neu kompiliert, einen Moment bitte... Sollte die Ansicht im Anschluss noch immer nicht passen, laden Sie die Seite mit Strg + F5 neu. <script>location.reload();</script>";
                        exit;

            }
                    $debugOutput[] = "<br/>" . __LINE__ . ": Style compiliert und Datei [$filename] wird verwendet.";
                }
               // echo $filename;

                if (isset($filenameLaravel) && file_exists($filenameLaravel)) {
                    $debugOutput[] = "<br/>" . __LINE__ . ": Pfad [$PathToStyle] wurde als LESSStylePath ans Template übergeben.";
                    $this->template->assign("LESSStylePath", $PathToStyle);
                    $_SESSION['LoadedStyle'] = $PathToStyle;
                }
            }
        } catch (Exception $exc) {
//$debugOutput[] = "<br/>".__LINE__.": Exception beim laden des Styles aufgetreten: ";
            echo "<br/>".__LINE__.": Exception beim laden des Styles aufgetreten: ";
            print_r($exc);
            echo $exc->getTraceAsString();
        }
        //Nachrichtenwesen:
        $ShowMessages = (defined("SHOWMESSAGES") && SHOWMESSAGES == 0) ? false : true;
        $this->template->assign("ShowMessages", $ShowMessages);

        if ($this->module->pageTemplateFile == null) {
            $pageTemplateFile = 'page.tpl';
        } else {
            $pageTemplateFile = $this->module->pageTemplateFile;
        }

        //Pürfen, ob styles/default/css/CustomStyles.css exisitirt
        //StylePath: realpath(_HM_PUBLIC . DS . _HM_STYLEPATH.DS.'..');
        $CustomStylesExist = file_exists(realpath(_HM_PUBLIC . DS . _HM_STYLEPATH.DS.'..'.DS.'CustomStyles.css'));
        $this->template->assign("CustomStylesExist", $CustomStylesExist);


        // header('Content-type: text/html; charset=utf-8');
        $this->template->display($pageTemplateFile);
    }

    public function __destruct() {
        parent::__destruct();
    }

}

?>
