<?php

declare(strict_types=1);

/**
 * @module   	    edit_area
 * @version        	see info.php of this module
 * @author			Christophe Dolivet (EditArea), Christian Sommer (wrapper), LEPTON Project
 * @copyright		2009-2010 Christian Sommer
 * @copyright       2010-2026 LEPTON Project
 * @license        	GNU General Public License
 * @license terms  	see info.php of this module
 * @platform       	see info.php of this module
 *
 */ 

class edit_area extends LEPTON_abstract
{
    public $oES = NULL;

    
    /**
     * Own instance of the class
     * @var object|instance
     */
    public static $instance;
    
    /**
     * Required by LEPTON_abstact - called after "getInstance()"
     */
    public function initialize() 
    {
        
    }
    
	/**
	 * Initialize editor and create an textarea
	 * 
	 * @param STR $name		Name of the textarea.
	 * @param STR $id		Id of the textarea.
	 * @param STR $content	The content to edit.
	 * @param INT $width	The width of the editor, overwritten by wysiwyg-admin.
	 * @param INT $height	The height of the editor, overwritten by wysiwyg-admin.
	 * @param BOOL $prompt	Direct output to the client via echo (true) or returnd as HTML-textarea (false)?
	 * @return MIXED		Could be a BOOL or STR (textarea-tags).
	 *
	 */
	public static function show_wysiwyg_editor( $name, $id, $content, $width=NULL, $height=NULL, $prompt=true) 
	{
		global $id_list, $section_id, $page_id, $preview;
		$database = LEPTON_database::getInstance();
		
		// Get Twig
		$oTWIG = lib_twig_box::getInstance();
		$oTWIG->registerModule('edit_area');

        //  [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();
		}
	

		// check if used backend language is supported by EditArea
		$language = 'en';
		if (defined('LANGUAGE') && file_exists(dirname(__FILE__) . '/langs/' . strtolower(LANGUAGE) . '.js')) 
		{
			$language = strtolower(LANGUAGE);
		}

		
		// Try to load the basic js only one time.
		$register = "";
		if (!defined('EDIT_AREA_LOADED'))
        {
			define('EDIT_AREA_LOADED', true);
			$script_url = LEPTON_URL.'/modules/edit_area/edit_area/edit_area_full.js';
			$register .= "\n<script src='".$script_url."' type='text/javascript'></script>\n";
			
		}

		if (!isset($_SESSION['edit_area']))
		{
			$script = LEPTON_URL.'/modules/edit_area/edit_area/edit_area_full.js';
			$register = "\n<script src=\"".$script."\" type=\"text/javascript\"></script>\n";

			if (!isset($preview))
			{
				$last = $database->get_one("SELECT section_id from ".TABLE_PREFIX."sections where page_id = ".$page_id." order by position desc limit 1"); 
				$_SESSION['edit_area'] = $last;
			}

		} 
		else 
		{
			if ($section_id == $_SESSION['edit_area'])
			{
				unset($_SESSION['edit_area']);
			}
		}
		echo $register;
		
		$oES = edit_area_settings::getInstance();

		$data = [
			'id'        => $id,
			'content'   => $content,
			'skin'      => $oES->skins[$oES->default_skin],
			'width'     => ($width ?? $oES->getWidth()),
			'height'    => ($height ?? $oES->getHeight()),
			'min_width' => ($width ?? $oES->getWidth()),
			'min_height' => ($height ?? $oES->getHeight()),
			'allow_resize'  => $oES->allow_resize,
			'allow_toggle'  => $oES->allow_toggle,
			'toolbar'       => $oES->toolbars[$oES->default_toolbar],
			'start_highlight' => $oES->start_highlight,
			'syntax'        => $oES->default_syntax,
			'language'      => $language
		];
		
		$oTwig = lib_twig_box::getInstance();
		$oTwig->registerModule("edit_area");
		
		$HTML_source = $oTwig->render(
			'@edit_area/show.lte',
			$data
		);
		
		if(true === $prompt)
		{
		    echo $HTML_source;
		    return true;
		} 
		else 
		{
		    return $HTML_source;
		}
	}
    
    /**
     *  Returns the generated JS code (script-tag) for EditArea incl. the link-tag to edit-area source.
     *  Is used e.g by Droplets!
     * 
     *  @param string   $id                 The ID if the refrended textarea.
     *  @param string   $syntax             The syntax to displax: defailt is 'php'.
     *  @param bool     $syntax_selection   Default is 'true'.
     *  @param string   $allow_resize       Default is 'both'.
     *  @param bool     $allow_toggle       Default is 'true'.
     *  @param bool     $start_highlight    Default is 'true'.
     *  @param integer  $min_width          The min width (in px), default is 600.
     *  @param integer  $min_height         The min height (in px), default si 300.
     *  @param string   $toolbar            The toolbar(name or definition). The default is 'default'.
     *
     *  @return string  The generated js-script tag.
     */
    static function registerEditArea(
            $id = 'code_area',
            $syntax = 'php',
            $syntax_selection = true,
            $allow_resize = 'both',
            $allow_toggle = true,
            $start_highlight = true,
            $min_width = 600,
            $min_height = 300,
            $toolbar = 'default'
    ) {

        // set default toolbar if no user defined was specified
        if ($toolbar == 'default') {
            $toolbar = 'search, fullscreen, |, undo, redo, |, select_font, syntax_selection, |, highlight, reset_highlight, |, help';
            $toolbar = (!$syntax_selection) ? str_replace('syntax_selection,', '', $toolbar) : $toolbar;
        }

        // check if used backend language is supported by EditArea
        $language = 'en';
        if (defined('LANGUAGE') && file_exists(dirname(__FILE__) . '/langs/' . strtolower(LANGUAGE) . '.js')) {
            $language = strtolower(LANGUAGE);
        }

        // check if highlight syntax is supported by edit_area
        $syntax = in_array($syntax, array('css', 'html', 'js', 'php', 'xml', 'csv', 'sql')) ? $syntax : 'php';

        // check if resize option is supported by edit_area
        $allow_resize = in_array($allow_resize, array('no', 'both', 'x', 'y')) ? $allow_resize : 'no';

        /**
         * 	Try to load the basic js only one time.
         */
        $return_value = "";
        if (!defined('EDIT_AREA_LOADED')) {
            define('EDIT_AREA_LOADED', true);
            $script_url = LEPTON_URL . '/modules/edit_area/edit_area/edit_area_full.js';
            $return_value .= "\n<script src='" . $script_url . "' type='text/javascript'></script>\n";
        }

        $data = array(
            'id' => $id,
            'min_width' => $min_width,
            'min_height' => $min_height,
            'allow_resize' => $allow_resize,
            'allow_toggle' => $allow_toggle,
            'toolbar' => $toolbar,
            'language' => $language,
            'syntax' => $syntax,
            'start_highlight' => $start_highlight
        );

        $oTwig = lib_twig_box::getInstance();
        $oTwig->registerModule("edit_area");

        $return_value .= $oTwig->render(
                "@edit_area/register.lte",
                $data
        );

        return $return_value;
    }

}