<?php

/**
 * This file is part of LEPTON Core, released under the GNU GPL
 * Please see LICENSE and COPYING files in your package for details, specially for terms and warranties.
 * 
 * NOTICE:LEPTON CMS Package has several different licenses.
 * Please see the individual license in the header of each single file or info.php of modules and templates.
 *
 * @author          LEPTON Project
 * @copyright       2010-2026 LEPTON Project
 * @link            https://lepton-cms.org
 * @license         https://gnu.org/licenses/gpl.html
 * @license_terms   please see LICENSE and COPYING files in your package
 *
 */

// include secure.php to protect this file and the whole CMS!
if(!defined("SEC_FILE")){define("SEC_FILE",'/framework/secure.php' );}
if (defined('LEPTON_PATH')) {	
	include LEPTON_PATH.SEC_FILE;
} else {
	$oneback = "../";
	$root = $oneback;
	$level = 1;
	while (($level < 10) && (!file_exists($root.SEC_FILE))) {
		$root .= $oneback;
		$level += 1;
	}
	if (file_exists($root.SEC_FILE)) { 
		include $root.SEC_FILE;  
	} else {
		trigger_error(sprintf("[ <b>%s</b> ] Can't include secure.php!", $_SERVER['SCRIPT_NAME']), E_USER_ERROR);
	}
}
// end include secure file


/**
 * get additions for page footer (js, script)
 *
 * + gets all active sections for a page;
 * + scans module directories for file footers.inc.php;
 * + includes that file if it is available
 * @access public
 * @param  string  $for - 'frontend' (default) / 'backend'
 * @return string (echo's result)
 *
 **/
 
function get_page_footers(string $for = 'frontend' ): string
{

	LEPTON_handle::register("get_active_sections");

    $FOOTERS = &LEPTON_core::$FOOTERS;

	// don't do this twice
	if ( defined( 'LEP_FOOTERS_SENT' ) )
	{
		return "";
	}
	
	//  Temp. additional infostring
	$sAdditionalInfo = "";
	
	//  Initialize var with an empty string.
	$module = '';

    if (($for != 'frontend') && ($for != 'backend'))
    {
		$for = 'frontend';
		$oLEPTON = LEPTON_frontend::getInstance();
	}
    // Aldus: 2021-07-16 L* 5.3
	$page_id = LEPTON_request::getPageID();
	
	if (is_null($page_id))
	{
	    $page_id = -1; //
	}
	
	$js_subdirs = [];
	// it's an admin tool...
	$sMyTool = filter_input(INPUT_GET,'tool',FILTER_SANITIZE_SPECIAL_CHARS) ?? '';
    if ($for == 'backend' && isset($sMyTool) && file_exists(LEPTON_PATH.'/modules/'.$sMyTool.'/tool.php'))
	{
		$js_subdirs[] = [
            'modules/'.$sMyTool.'/js',
            'modules/'.$sMyTool
        ];
        if (file_exists(LEPTON_PATH.'/modules/'.$sMyTool.'/footers.inc.php'))
		{
            LEPTON_core::addItems($for, LEPTON_PATH.'/modules/'.$sMyTool, true);
		}
	}
    elseif ($page_id && is_numeric($page_id))
	{
        $sections = get_active_sections($page_id, NULL, ($for === "backend"));
		if (is_array($sections) && count($sections))
		{
			global $current_section;
			
			// avoid loading modules twice!
			$loaded_modules = [];

            foreach ($sections as $section)
			{

                $module = $section['module'];

                if (in_array($module, $loaded_modules))
				{
					continue;
				}
				$loaded_modules[] = $module;
				
				// find header definition file
                if (file_exists(LEPTON_PATH.'/modules/'.$module.'/footers.inc.php'))
				{
                    $current_section = $section['section_id'];
                    LEPTON_core::addItems($for, LEPTON_PATH.'/modules/'.$module, true);
					
				} else {
				
					$current_template = (isset($oLEPTON->page['template']) && ($oLEPTON->page['template'] != '')) ? $oLEPTON->page['template'] : DEFAULT_TEMPLATE;

                    if (file_exists(LEPTON_PATH.'/templates/'.$current_template.'/footers.inc.php'))
                    {
						$current_section = $section['section_id'];
                        LEPTON_core::addItems($for, LEPTON_PATH.'/templates/'.$current_template, true);
						
					}
				}
				
				$temp_js = [
                    'modules/'.$module,
                    'modules/'.$module.'/js'
				];

                if ($for == 'frontend')
				{
					$current_template = (isset($oLEPTON->page['template']) && ($oLEPTON->page['template'] != '')) ? $oLEPTON->page['template'] : DEFAULT_TEMPLATE;
					$lookup_file = "templates/".$current_template."/frontend/".$module;

                } // end $for == 'frontend'
				else {
					// start $for == 'backend' 
					$current_theme = DEFAULT_THEME;
					$lookup_file = "templates/".$current_theme."/backend/".$module;

                    // end $for == 'backend'
				}
                $temp_js[] = $lookup_file;
                $temp_js[] = $lookup_file."/js";

                $js_subdirs[]= array_reverse($temp_js);
			}
		}
		// add css/js search subdirs for frontend only; page based CSS/JS
		// does not make sense in BE
        if ($for == 'frontend')
		{
			$js_subdirs[] = [
				PAGES_DIRECTORY,
				PAGES_DIRECTORY . '/js'
			];
		}
	}
	else
	{
		// load footers if no page_id exists (/account)
		$sAdditionalInfo .= "\n<!-- no page_id, no modules -->\n";
		// [3.1] Make sure that the correct template footers.inc.php is loaded
		// [3.1.0] is it the search result page?
		$sTempPagePath = filter_input(INPUT_SERVER, "REQUEST_URI", FILTER_SANITIZE_FULL_SPECIAL_CHARS);

        if (str_contains($sTempPagePath, "frontend_result"))
		{
		    $sAdditionalInfo .= "\n<!-- search results -->\n";
		    
		    // [3.1.1] Get the template-name from the db-table "search"
		    $sTempTemplateName = LEPTON_database::getInstance()->get_one("SELECT `value` FROM `".TABLE_PREFIX."search` where `name`='template'");
		    
		    // [3.1.2] Temp path
		    $sTempLookUp = LEPTON_PATH."/templates/".$sTempTemplateName."/footers.inc.php";
            if (file_exists($sTempLookUp))
		    {
		        // 3.1.3 require the file
                LEPTON_core::addItems($for, LEPTON_PATH.'/templates/'.$sTempTemplateName, true);
		    }
		}
		else 
		{
		    // [3.2.0] WHAT ist it? Frontend account?
		    
		    // [3.3.0] We try to get the default template footers.imc.php
		    $sAdditionalInfo .= "\n<!-- default frontend template -->\n";
		    
		    // [3.3.1] Temp path
		    $sTempLookUp = LEPTON_PATH."/templates/".DEFAULT_TEMPLATE."/footers.inc.php";
            if (file_exists($sTempLookUp))
		    {
		        // [3.3.2] require the file
                LEPTON_core::addItems($for, LEPTON_PATH . '/templates/' . DEFAULT_TEMPLATE, true);
		    }
		} 
	}	
	
	// add template JS
	// note: defined() is just to avoid warnings, the NULL does not really make sense!
    if ($for == 'backend')
	{
        $subdir = (defined('DEFAULT_THEME') ? DEFAULT_THEME : NULL);
	} else {
        $subdir = (defined('TEMPLATE') ? TEMPLATE : NULL);
	}

    if (($module != '') && (!isset($loaded_modules)))
	{ 
        $js_subdirs[0][] = 'templates/'.$subdir.'/backend/'.$module;
        $js_subdirs[0][] = 'templates/'.$subdir.'/backend/'.$module.'/js';
        $js_subdirs[0]= array_reverse($js_subdirs[0]);   
	}
	
	$js_subdirs[] = [
        'templates/' . $subdir . '/js', 
        'templates/' . $subdir
	];
    
	// automatically add JS files
    foreach ($js_subdirs as $first_level_dir)
	{
        foreach ($first_level_dir as $directory)
		{

			// 2
			$footersFile = LEPTON_PATH.'/'.$directory.'/footers.inc.php';
// $sAdditionalInfo .= "<!-- [1]".$footersFile." -->";
			if (file_exists($footersFile))
			{
// $sAdditionalInfo .= "<!-- [2]".$footersFile." -->";
			    LEPTON_core::addItems($for, LEPTON_PATH.'/'.$directory, true);
			}

            $file = $directory.'/'.$for.'_body.js';
// $sAdditionalInfo .= "<!-- ".$directory. " -- ".$file." -->";
            if (file_exists(LEPTON_PATH.'/'.$file))
            {
                $FOOTERS[$for]['js'][] = $file;
                //break;
			}
		}
	}
	
	$output = '';
// $sAdditionalInfo .= '<!-- '.LEPTON_tools::display($FOOTERS[$for])." -->";    
    foreach ($FOOTERS[$for]['js'] as $arr)
    {
        $output .= '<script src="'.LEPTON_URL.'/'.$arr.'"></script>'."\n";
    }

    define('LEP_FOOTERS_SENT', true);

    $sAdditionalInfo .= "\n<!-- get_page_footer - ".$for."-->\n";

//  Aldus: 2023-09-20: Im frontend wildes echo und im backend ein return????
    if ($for == 'frontend')
	{
		echo $sAdditionalInfo.$output;
        return "";
	
	} 
	else 
	{
		return $sAdditionalInfo.$output;
	}
}
