<?php

/**
 * @module          Wysiwyg Settings
 * @author          LEPTON team
 * @copyright       2022-2022 LEPTON team
 * @link            https://lepton-cms.org
 * @license         GNU General Public License 3 (see info.php)
 * @license_terms   see license
 *
 */
 
class wysiwyg_settings extends LEPTON_abstract implements LEPTON_wysiwyg_interface
{
	public $oES = NULL;
	public $database = 0;
	public $admin = 0;
	public $table = TABLE_PREFIX.'mod_wysiwyg_settings';
	public $editor_settings = [];
	public $content = "<strong>Berthold’s</strong> quick brown fox jumps over the lazy dog and feels as if he were in the seventh heaven of typography.";	
	public $addon_color = 'blue';
	public $wysiwyg = 0;
	public $action_url = ADMIN_URL . '/admintools/tool.php?tool=wysiwyg_settings';
	public $action = LEPTON_URL . '/modules/wysiwyg_settings/';

	public static $instance;	

	public function initialize() 
	{
            $this->wysiwyg = 0;
            if(WYSIWYG_EDITOR !== 'none')
            {
                $this->oES = $this->getAdditionalClass("settings", strtolower( WYSIWYG_EDITOR ));
                if( NULL !== $this->oES )
                {
                   $this->wysiwyg = 1; 
                }
            }
	
            $this->database = LEPTON_database::getInstance();		
            $this->admin = LEPTON_admin::getInstance();
            $this->init_tool();		
	}
	
	public function init_tool()
	{
            $this->database->execute_query(
                "SELECT * FROM `".$this->table."` WHERE `editor`='". strtolower(WYSIWYG_EDITOR)."'",
                true,
                $this->editor_settings,
                false
            );
            /**
             * [a.1 No entry found but an setting-class exists.
             */
            if((empty($this->editor_settings)) && (NULL !== $this->oES))
            {
                // [a.1.1] New entry in DB
                $this->database->build_and_execute(
                    "INSERT",
                    $this->table,
                    [
                        'editor'    => strtolower(WYSIWYG_EDITOR),
                        'width'     => $this->oES->getWidth(),
                        'height'    => $this->oES->getHeight(),
                        'content_css' => ($this->oES->default_content_css ?? ""), // !only TinyMCE
                        'skin'      => $this->oES->getSkin(),
                        'toolbar'   => $this->oES->default_toolbar
                    ]
                );
                // [a.1.2] Get current again
                $this->database->execute_query(
                    "SELECT * FROM `".$this->table."` WHERE `editor`='". strtolower(WYSIWYG_EDITOR)."'",
                    true,
                    $this->editor_settings,
                    false
                );
            }
        }

	public function display_settings() 
	{	
		$display_editor = '';
		if(isset($this->editor_settings['id']))
		{
			if($this->oES !== NULL)
			{
				LEPTON_handle::register('display_wysiwyg_editor');
				$display_editor = display_wysiwyg_editor( 
					$this->editor_settings['editor'],
					$this->editor_settings['id'],
					($this->oES->content ?? $this->content),
					$this->editor_settings['width'],
					$this->editor_settings['height'],
					false
				);
			} else {
				$display_editor = "Can't display preview: editor class is missing!";
			}
		}

		// data for twig template engine	
		$data = array(
			'oWS'           => $this,
			'wysiwyg'       => $this->wysiwyg,
			'wysiwyg_editor'=> WYSIWYG_EDITOR,
			'editor_name'   => $this->database->get_one("SELECT name FROM ".TABLE_PREFIX."addons WHERE directory = '".WYSIWYG_EDITOR."' "),
			'display_editor'=> $display_editor,
			'leptoken'      => get_leptoken(),
			'help_link'     => "https://forum.lepton-cms.org/viewforum.php?f=14"			
		);

		/**	
		 *	get the template-engine.
		 */
		$oTwig = lib_twig_box::getInstance();
		$oTwig->registerModule('wysiwyg_settings');

		echo $oTwig->render( 
			"@wysiwyg_settings/display_settings.lte",
			$data
		);
	}

	public function save_settings() 
	{
		$save_id = intval(filter_input(INPUT_POST, "save_settings", FILTER_SANITIZE_NUMBER_INT));
		
		if( NULL === $this->oES )
		{
			$this->oES = wysiwyg_settings_defaults::getInstance();
		}
		
		$request = LEPTON_request::getInstance();
		
		$all_names = [
			'skin'          => ['type' => 'string_chars',   'default' => "none"],   // toDo: get default by WYSIWYG editor class!
			'toolbar'       => ['type' => 'string_chars',   'default' => ($this->oES->toolbar ?? "none")],    // get default by WYSIWYG editor class!
			'content_css'   => ['type' => 'string_chars',   'default' => "none"],			
			'width'         => ['type' => 'integer+',       'default' => intval($this->oES->getWidth() ?? "100") ],   // get default by WYSIWYG editor class!
			'height'        => ['type' => 'integer+',       'default' => intval($this->oES->getHeight() ?? "400")],   // get default by WYSIWYG editor class!
			'editor'        => ['type' => 'string_chars',   'default' => "none"]
		];

		$all_values = $request->testPostValues($all_names);			

		if ($save_id != 0)
		{
			$this->database->build_and_execute( 'UPDATE', $this->table, $all_values,'id = '.$save_id);
		}

		if ($save_id == 0)
		{
			$this->database->build_and_execute ("INSERT", $this->table, $all_values);			
		}

		$this->admin->print_success($this->language['save_ok'], $this->action_url);
	}	

	public function show_info() 
	{

		// data for twig template engine	
		$data = array(
			'oWS'           => $this,
			'readme_link'   => "<a href='https://cms-lab.com/_documentation/wysiwyg_settings/readme.php' class='info' target='_blank'>Readme</a>",
			'SUPPORT'       => "<a href='#'>NO Live-Support / FAQ</a>",		
			'image_url'     => 'https://cms-lab.com/_documentation/media/wysiwyg_settings/wysiwyg_settings.jpg'
		);

		/**
		 *  get the template-engine.
		 */
		$oTwig = lib_twig_box::getInstance();
		$oTwig->registerModule('wysiwyg_settings');

		echo $oTwig->render( 
			"@wysiwyg_settings/info.lte",   //  template-filename
			$data                           //	template-data
		);	
	}

	// interfaces
	//  [1]
	public function getHeight()
	{
	   return $this->editor_settings['height']; 
	}
	//  [2]
	public function getWidth()
	{
		return $this->editor_settings['width']; 
	}
	//  [3]
	public function getToolbar()
	{
		// [3.1] any custom class where?
		$sCustom = (class_exists( WYSIWYG_EDITOR."_settings_custom", true)) ? "_custom" : "";
		
		// [3.2] get available toolbars
		$oTempArray = eval("return ".WYSIWYG_EDITOR."_settings".$sCustom."::getInstance()->toolbars;");
		
		// [3.3] return the "toolbar definition string"
		return $oTempArray[$this->editor_settings['toolbar'] ] ?? ""; 
	}
	//  [4]
	public function getSkin()
	{
		return $this->editor_settings['skin'] ?? ""; 
	}
        
        public function removeEntry( string $sEditor )
        {
            $this->database->simple_query(
                    "DELETE from `".$this->table."` WHERE `editor` = '".$sEditor."';"
            );
        }
}