<?php

declare(strict_types=1);

/**
 * @module          Wysiwyg Settings
 * @author          LEPTON team
 * @copyright       2010-2026 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 string   $table = TABLE_PREFIX.'mod_wysiwyg_settings';
	public array    $editor_settings = [];
	public string   $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 string   $addon_color = 'blue';
	public int      $wysiwyg = 0;
	public string   $action_url = ADMIN_URL . '/admintools/tool.php?tool=wysiwyg_settings';
	public string   $action = LEPTON_URL . '/modules/wysiwyg_settings/';

	public object|null $oES = null;
	public object|null $oTwig = null;		
	public LEPTON_database $database;
	public LEPTON_admin $admin;
	public static $instance = null;

    /**
     * @return void
     */
    public function initialize(): void
    {
            $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->oTwig = lib_twig_box::getInstance();
			$this->oTwig->registerModule('wysiwyg_settings');			
            $this->init_tool();		
	}

    /**
     * @return void
     */
    public function init_tool(): void
    {
        $this->database->execute_query(
            "SELECT * FROM `".$this->table."` WHERE `editor`='". strtolower(WYSIWYG_EDITOR)."'",
            true,
            $this->editor_settings,
            false
        );
        /**
         * [a.1] No entry found but a 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 ?? ""), // ! not CKEditor
                    '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
            );
        }
    }

    /**
     * @return void
     */
    public function display_settings(): void
    {
		$display_editor = '';
		if (isset($this->editor_settings['id']))
		{
			if (!is_null($this->oES))
			{
				LEPTON_handle::register('display_wysiwyg_editor');
				$display_editor = display_wysiwyg_editor( 
					$this->editor_settings['editor'],
					"wysiwyg_settings_".$this->editor_settings['id'],
					($this->oES->content ?? $this->content),
					(int) $this->editor_settings['width'],
					(int) $this->editor_settings['height'],
					false
				);
			} else {
				$display_editor = $this->language['class_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.
		echo $this->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 = [
			'oWS'			=> $this,
			'image_url'		=> "https://cms-lab.com/_documentation/media/wysiwyg_settings/wysiwyg_settings.jpg",
			'readme_link'	=> "<a class='ui basic blue button' href='https://cms-lab.com/_documentation/wysiwyg_settings/readme.php' target='_blank'><i class='book icon'></i>Readme</a>",
			'live_support'	=> "<a  class='ui basic red button' href='#'><i class='bookmark icon'></i>NO Live-Support</a>",			
			'forum_support'	=> "<a class='ui basic blue button' href='https://forum.lepton-cms.org/viewforum.php?f=14' target='_blank'><i class='bookmark icon'></i>Forum-Support</a>"
		];

		//	get the template-engine.
		echo $this->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'] ?? ""; 
	}
	//  [5]
	public function getContentCss()
	{
		return $this->editor_settings['content_css'] ?? ""; 
	}	

    public function removeEntry(string $sEditor)
    {
        $this->database->simple_query(
            "DELETE from `".$this->table."` WHERE `editor` = '".$sEditor."';"
        );
    }
}