<?php

declare(strict_types=1);

/**
 * This file is part of an ADDON for use with LEPTON Core.
 * This ADDON is released under the GNU GPL.
 * Additional license terms can be seen in the info.php of this module.
 *
 * @module          Droplets
 * @author          LEPTON Project
 * @copyright       2010-2026 LEPTON Project
 * @link            https://lepton-cms.org
 * @license         https://gnu.org/licenses/gpl.html
 * @license_terms   please see info.php of this module
 *
 */

class droplets extends LEPTON_abstract
{
    /**
     *  Holds a list of current backup-filenames.
     *  @type   array
     *  @access public
     */
    public array $backups = [];
    
    /**
     *  Holds the current values from the db.
     *  @type   array
     *  @access public
     */
    public array $settings = [];
    
    /**
     *  Is CodeMirror installed?
     *  @type   boolean
     */
    public bool $codemirrorSupported = false;
    
    /**
     *  Own instance of this module
     *  @type   object
     */
    public static $instance;
    
    /**
     *  Initialize own module settings, values, methods.
     *
     */
    public function initialize()
    {
        self::$instance->codemirrorSupported = class_exists("lib_codemirror", true);
        
        require_once dirname(__DIR__)."/functions.php";
		require_once dirname(__DIR__)."/droplets.php";
        self::$instance->getSettings();
        self::$instance->getBackups();
    }
    
    /**
     *  Read the /export/ dir for existing *.zip backup files
     *
     */
    public function getBackups(): void
    {
        $sLookUpPath = dirname(__DIR__)."/export/";
        LEPTON_handle::register( "file_list" );
        self::$instance->backups = file_list( $sLookUpPath, array(), false, "zip", $sLookUpPath."/");
    }

    /**
     *  Get the current values from the db
     *
     */
    public function getSettings(): void
    {
        $aTempSettings = [];
        LEPTON_database::getInstance()->execute_query(
            "SELECT * FROM `". TABLE_PREFIX . "mod_droplets_settings`",
            true,
            $aTempSettings,
            true
        );
        
        foreach($aTempSettings as &$ref)
        {
            self::$instance->settings[$ref['attribute']] = explode("|", $ref['value']);
        }
    } 
    
    /**
     *  Test if a given droplet is installed.
     *    
     *  @param  int|string $sNameOrID  String (DropletName) or integer (droplet_id).
     *  @return boolean True if exists - false if not.
     *
     *  @code{.php}
     *
     *      // by name
     *      $bIsItInstalled = droplets::dropletExists( 'hello_world' );
     *
     *      // by id
     *      $bIsItInstalled = droplets::dropletExists( 231 );
     *
     *  @endcode
     */
    public static function dropletExists(int|string $sNameOrID = ""): bool
    {
        if (empty($sNameOrID))
        {
            return false;
        }
        
        $database = LEPTON_database::getInstance();

        $id = $database->get_one("SELECT `id` FROM `" . TABLE_PREFIX . "mod_droplets` WHERE (`id`='" . $sNameOrID . "' OR `name` = '" . $sNameOrID . "')");
        return (!is_null($id));
    }
       
    /**
     *  Try to test the dropletCode for a given droplet id or name
     *
     *  @param  int|string $sNameOrID String (DropletName) or integer (droplet_id).
     *  
     *  @return bool    True if success, otherwise false;
     *
     *  @code{.php}
     *
     *      // by name
     *      $bIsCodeOk = droplets::testDroplet( 'hello_world' );
     *
     *      // by id
     *      $bIsCodeOk = droplets::testDroplet( 231 );
     *
     *  @endcode
     *
     *
     */
    static public function testDroplet(int|string $sNameOrID = ""): bool
    {
        if (empty($sNameOrID))
        {
            return false;
        }

        if (false === self::dropletExists($sNameOrID))
        {
            return false;
        } 
		else 
		{
            $database = LEPTON_database::getInstance();
            
            $aDroplet = [];
            $database->execute_query(
                "SELECT `code`,`name` FROM `" . TABLE_PREFIX . "mod_droplets` WHERE (`id`='" . $sNameOrID . "' OR `name` = '" . $sNameOrID . "')",
                true,
                $aDroplet,
                false
            );

            if (empty($aDroplet))
            { 
                return false;
            } 
			else 
			{
                try
				{
                    // add a return forwards to prevent executing the droplet-code here
                    $sTempCode = "return true;" . $aDroplet['code'] . ";";
                    eval($sTempCode);

                } catch (ParseError $oError)
				{

                    echo LEPTON_tools::display($oError->getMessage(), "div", "ui message red");
                    return false;
                }
                return true;
            }
        }
    }
}
