<?php

/**
 *  @module          lepSem
 *  @version         see info.php of this module
 *  @author          Wolfgang Studer
 *  @copyright       2025 Wolfgang Studer
 *  @license         GNU General Public License
 *  @license terms   see info.php of this module
 *  @platform        see info.php of this module
*/

/*
 * Toggle the open_tree flag in pages DB table
 */

// 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.php


// Define the content-type for the ajax response
header('Content-Type: application/json');
http_response_code(200); // Always OK, failures are handled in JS

while( 1 == 1)
{
	// invalid request
	if ($_SERVER['REQUEST_METHOD'] !== 'POST')
	{
		$final = set_failure('invalid request method');
		break;
	}

	// validation of input variables
	$validateFields = array(
		'page_id'   => array ('type' => 'integer+', 'default' => 0),
		'open_tree' => array ('type' => 'integer+', 'default' => 0)
	);

	$oREQUEST = LEPTON_request::getInstance();
	$validFields = $oREQUEST->testPostValues($validateFields);
	if ( count($validFields) == 0 )
	{
		$final = set_failure('missing valid fields');
		break;
	}

	$pageId = $validFields[ 'page_id' ];
	$openTree = $validFields[ 'open_tree' ] == 1 ? 0 : 1;
	if ( empty( $pageId ))
	{
		$final = set_failure('missing valid fields');
		break;
	}

	// define the databae instance
	$database = LEPTON_database::getInstance();

	// update open tree flag
	if ( $pageId > 0 )
	{
		// keep image name and path untouched but set image to archived
		$data = array('open_tree' => $openTree );

		// update DB
		$database->build_and_execute(
			'UPDATE',
			TABLE_PREFIX . 'pages',
			$data,
			"`page_id` = " . $pageId,
			false
		);
	}

	// Data processing success
	$response = array(
		'open_tree'  => $openTree
	);

	// return back to calling JS
	$final = json_encode([
		'result'  => 'success',
		'data'    => $response
	]);
	break;
}

// set output for ajax return
echo $final;
return;


function set_failure( $msg ): string
{
	// return error back to calling JS
	return json_encode([
		'result'  => 'failed',
		'data'    => array( 'message' => $msg )
	]);
}

?>
