<?php

/**
 *  @module         TinyMCE
 *  @version        see info.php of this module
 *  @authors        erpe, Dietrich Roland Pehlke (Aldus)
 *  @copyright      2010-2026 erpe, Dietrich Roland Pehlke (Aldus)
 *  @license        GPLv2+ License
 *  @license terms  see info.php of this module
 *  @platform       see info.php of this module
 *
 *  Please note: TINYMCE is distributed under the <a href="https://github.com/tinymce/tinymce/blob/develop/LICENSE.TXT">MIT License</a> 
 *
 *
 */

class tinymce extends LEPTON_abstract 
{
    /**
     *  Needed for reponsitive filemanager
     *  @access protected
     *  @type string
     */
    protected static string $akey = "";
    
    /**
     * Own instance of the class
     * @var object|instance
     */
    public static $instance;

    public string $selector = "";

    /**
     * Required by LEPTON_abstract - called after "getInstance()"
     */
    public function initialize() 
    {
        // Own initializations here:
    }
    
    /**
     *    returns the template name of the current displayed page
     * 
     *    @param string    $css_path A path to the editor.css - if there is one. Default is an empty string. Call by reference!
     *    @return string $tiny_template_dir
     */
    static public function get_template_name( &$css_path = ""): string
    {
        $database = LEPTON_database::getInstance();
        $lookup_paths = array(
            '/css/editor.css',
            '/editor.css'
        );
        
        $tiny_template_dir = "none";

        /**
         *    Looking up for an editor.css file for editor
         *
         */
        foreach($lookup_paths as $temp_path) 
        {
            if (file_exists(LEPTON_PATH .'/templates/' .DEFAULT_TEMPLATE .$temp_path ) ) 
            {
                $css_path = $temp_path; // keep in mind, that this one is pass_by_reference
                $tiny_template_dir = DEFAULT_TEMPLATE;
                break;
            }
        }
            
        // check if a editor.css file exists in the specified template directory of current page
        if (isset($_GET["page_id"]) && ((int) $_GET["page_id"] > 0)) 
        {
            $pageid = (int) $_GET["page_id"];
            // obtain template folder of current page from the database
            $query_page = "SELECT `template` FROM `" .TABLE_PREFIX ."pages` WHERE `page_id` = ".$pageid;
            $pagetpl = $database->get_one($query_page);
            
            //    check if a specific template is defined for current page
            if (isset($pagetpl) && ($pagetpl != '')) 
            {    
                //    check if a specify editor.css file is contained in that folder
                foreach($lookup_paths as $temp_path) 
                {
                    if (file_exists(LEPTON_PATH.'/templates/'.$pagetpl.$temp_path)) 
                    {
                        $css_path = $temp_path; // keep in mind, that this one is pass_by_reference
                        $tiny_template_dir = $pagetpl;
                        break;
                    }
                }
            }
        }
        return $tiny_template_dir;
    }


    /**
     * Initialize editor and create an textarea
     *
     * @param string $name              Name of the textarea.
     * @param string $id                Id of the textarea.
     * @param string $content           The content to edit.
     * @param int|string|null $width    The width of the editor, overwrites the wysiwyg-settings!.
     * @param int|string|null $height   The height of the editor, overwrites the wysiwyg-settings!
     * @param bool $prompt              Direct output to the client via echo (true) or returnd as HTML-textarea (false)?
     * @return bool|string              Could be a BOOL or STR (textarea-tags).
     *
     */
    static public function show_wysiwyg_editor(
        string $name,
        string $id,
        string $content,
        int|string|null $width = null,
        int|string|null $height = null,
        bool $prompt=true
    ): bool|string
    {
        global $id_list;
        $database = LEPTON_database::getInstance();
        
        // Get Twig
        $oTWIG = lib_twig_box::getInstance();
        $oTWIG->registerModule('tinymce');
        

        //  [1.0] get values either from wysiwyg_settings class or from internal settings class
        $bWysiwygClassOk = false;
        if(class_exists('wysiwyg_settings',true))
        {
            // [1.1.0] Geht the instance
            $oSettings = wysiwyg_settings::getInstance();
            
            // [1.1.1] Check for entries for this editor
            if( !empty($oSettings->editor_settings) )
            {
                // [1.1.2] Class exists and there are entries for this editor
                $bWysiwygClassOk = true;
            }
        }
                
        //  [1.2] Class "wysiwyg_settings" doesn't exists or there are no entries for this editor:
        if (false === $bWysiwygClassOk)
        {
            //  [1.2.1] Custom class?
            $oSettings = self::getInstance()->getEditorSettings();
        }
            
        /** ***************************
         *  1. tinyMCE main script part
         */

        $tinymce_url = LEPTON_URL."/modules/tinymce/tinymce";
        
		$temp_css_file = "editor.css";
        $template_name = self::get_template_name( $temp_css_file );
        

 	    // If editor.css file exists in default template folder or template folder of current page  -> https://www.tiny.cloud/docs/tinymce/latest/add-css-options/  
        if ( !file_exists (LEPTON_PATH .'/templates/'.$template_name.$temp_css_file) ) 
        {
            $css_status = 0;
			$css_file = ""; // will prevent content_css from loading
        }
		else
		{
			// line 97 tinymce.lte is overwriting internal conten_css from line 16 tinymce.lte
			$css_status = 1;
			$css_file = '"'.LEPTON_URL .'/templates/'.$template_name.$temp_css_file.'"';		
		}

        
        // If backend.css file exists in default theme folder overwrite module backend.css
        $backend_css = LEPTON_URL.'/templates/'.DEFAULT_THEME.'/backend/tinymce/backend.css';
        if(!file_exists(LEPTON_PATH.'/templates/'.DEFAULT_THEME.'/backend/tinymce/backend.css')) 
        {
            $backend_css = LEPTON_URL.'/modules/tinymce/css/backend.css';
        }
         

        //    Include language file, if the file is not found (local) we use an empty string (then default = uk.js
        $lang = strtolower( LANGUAGE );
        $language = (file_exists( LEPTON_PATH."/modules/tinymce/tinymce/langs/". $lang .".js" )) ? $lang    : "en";

        $filemanager_url = LEPTON_URL."/modules/lib_r_filemanager";

        if (!defined("tinymce_loaded"))
        {
            define("tinymce_loaded", true);
            echo $oTWIG->render(
                "@tinymce/tinymce_load.lte",
                [
                    'backend_css'   => $backend_css,
                    'tinymce_url'   => $tinymce_url,
                ]
            );

            // define access key
            $temp_akey = password_hash( LEPTON_GUID, PASSWORD_DEFAULT);
            $temp_akey = str_replace(array('$','/'),'',$temp_akey);
            self::$akey = substr($temp_akey, -30);
            $_SESSION['rfkey'] = self::$akey;
        }
        
        $data = [
            'filemanager_url'=> $filemanager_url,
            'LEPTON_URL'    => LEPTON_URL,
            'ACCESS_KEY'    => self::$akey,
            'tinymce_url'   => $tinymce_url,
            'backend_css'   => $backend_css,
            'selector'      => '#'.$id, //.", textarea:not(#no_wysiwyg)",
            'language'  => $language,
            'width'     => str_replace(["%","px"], "", ($width ?? $oSettings->getWidth())),
            'height'    => str_replace(["%","px"], "", ($height ?? $oSettings->getHeight())),
            'css_file'  => $css_file,
            'toolbar'   => $oSettings->getToolbar(),
            'skin'      => $oSettings->getSkin(),
			'css_status'=> $css_status,
            'content_css'   => $oSettings->getContentCss(), // see line 16 tinymce.lte
        ];
        
        echo $oTWIG->render( 
            "@tinymce/tinymce.lte",    //  template-filename
            $data            //  template-data
        );

        
        /** ****************
         *  2. textarea part
         *
         */

        //    values for the textarea
        $data = [
            'id'        => $id,
            'name'        => $name,
            'content'    => htmlspecialchars_decode( $content ),
            'width'        => $oSettings->getWidth(),
            'height'    => $oSettings->getHeight()
        ];

        $result = $oTWIG->render(
            '@tinymce/textarea.lte',    // template-filename
            $data            // template-data
        );
        
        if ($prompt == true) {
            echo $result;
            return true;
        }
        return $result;
    }
}
