<?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

$oLS = new LEPTON_securecms();
if (!$oLS->checkLepToken())
{
    die( "invalid call");
}

$search_text = LEPTON_core::getValue('searchtext') ?? "";
$search_type = LEPTON_core::getValue('searchtype') ?? "";

$results = [];
if ($search_text != "")
{
    switch( $search_type )
    {
        case 'title':
            $query = "SELECT `page_title`,`menu_title`,`page_id`,`visibility`,`admin_groups` from `".TABLE_PREFIX."pages` WHERE `page_title` LIKE '%".$search_text."%' ORDER BY `page_title`";
            break;

        case 'page_id':
            $search_text = intval($search_text);
            $query = ( 0 <> $search_text )
                ? "SELECT `page_title`,`menu_title`,`page_id`,`visibility`, `admin_groups` from `".TABLE_PREFIX."pages` WHERE `page_id` LIKE '%".intval($search_text)."%' ORDER BY `page_id`"
                : ""
                ;
            break;

        case 'section_id':
            $search_text = intval($search_text);
            $query = ( 0 <> $search_text )
                ? "SELECT * from `".TABLE_PREFIX."pages` AS p JOIN `".TABLE_PREFIX."sections` as s WHERE (`section_id` LIKE '%".intval($search_text)."%') AND (s.page_id = p.page_id) ORDER BY p.`page_title`"
                : ""
                ;
            break;

        case 'module':
            $query = ( "" <> $search_text )
                ? "SELECT * from `".TABLE_PREFIX."pages` AS p JOIN `".TABLE_PREFIX."sections` as s WHERE (`module` LIKE '%".($search_text)."%') AND (s.page_id = p.page_id) ORDER BY p.`page_title`"
                : ""
                ;
            break;

        default:
            $query = "";
            break;
    }

    if (!empty($query))
    {
        $database->execute_query($query, true, $results, true);
        
        $aUserGroups = LEPTON_core::getValue("groups_id", "string", "session", ",");
        foreach ($results as &$ref)
        {
            $ref['admin_groups'] = explode(",", $ref['admin_groups']);
            $ref['userAllowed'] = !empty(array_intersect($aUserGroups, $ref['admin_groups']));
        }
    }
}

/**
 * Get user permissions for pages
 */
$admin = LEPTON_admin::getInstance('Pages', 'start', false, false);
$aPermissions = [
    'pages' => $admin->getPagesPermissions('*'),
    'view'  => $admin->getPagesPermissions('view'),
    'add'   => $admin->getPagesPermissions('add'),
    'modify' => $admin->getPagesPermissions('modify'),
    'settings' => $admin->getPagesPermissions('settings'),
    'delete' => $admin->getPagesPermissions('delete')
];

$oTwig = lib_twig_box::getInstance();

//  Keep in mind that this file is called via ajax and we have to return a json encoded string here
echo json_encode(
    $oTwig->render(
        "@theme/pages_search_results.lte",
        [
            'db_error'  => $database->get_error(),
            'leptoken'  => get_leptoken(),
            'results'   => $results,
            'permissions' => $aPermissions
        ]
    )
);
