<?php
function handleRequest($handleRequestAction) {
    $action = preg_replace('/[^a-zA-Z0-9_]/', '', $handleRequestAction);
    if (function_exists($action)) {
        call_user_func($action);
    } else {
        echo json_encode([
            'error' => 'Неизвестное действие',
            'action' => $handleRequestAction,
            'post_data' => $_POST,
            'get_data' => $_GET,
            'server' => $_SERVER['REQUEST_URI']
        ]);
    }
}

function handleJsonRpcRequest($action) {
    $input = json_decode(file_get_contents('php://input'), true);
    $params = $input['params'] ?? [];
    $id = $input['id'] ?? null;
    $result = is_callable($action)
        ? call_user_func($action, $params[0] ?? null)
        : null;
    echo json_encode([
        'jsonrpc' => '2.0',
        'result'  => $result,
        'id'      => $id
    ]);
}

#подключение плагинов
function includePhp() {
    global $path;
    $html = '';
    $pluginDir = $path . 'main_plugin/';
    if (is_dir($pluginDir)) {
        $dirs = array_diff(scandir($pluginDir), ['.', '..']);
        foreach ($dirs as $dir) {
            if (is_dir($pluginDir . $dir)) {
                $file = $pluginDir . $dir . '/plug.php';
                if (is_file($file)) {
                    ob_start();
                    include $file;
                    $html .= ob_get_clean();
                }
            }
        }
    }
    return $html;
}

function API() {
    global $config, $path, $_SESSION;
    $config['page_error'] = '';

    if (isset($_POST['LogPage'])) {
        $_SESSION['log_in'] = true;
    }

    if (isset($_POST['logoff'])) {
        if (isset($_SESSION)) {
            unset($_SESSION);
            session_destroy();
        }
        echo json_encode(['status' => 'logged_off']);
    }

    if (isset($_POST['log'])) {
        if ($_POST['log'] == "Войти") {
            if (check($_POST['login'], md5($_POST['pass']))) {
                $_SESSION['username'] = $_POST['login'];
                $_SESSION['pass'] = $_POST['pass'];
                $_SESSION['Login'] = 'true';
                $_SESSION['log_in'] = false;
                echo json_encode(['status' => 'true']);
            } else {
                $_SESSION['Login'] = 'false';
                echo json_encode(['status' => 'false']);
            }
        }
    }
}

function SetConfig()
{
global $config, $path;
$xmlstr = simplexml_load_file($path . 'config/config_site.php');
$config['icon'] = $xmlstr->general->icon; # иконка сайта
$config['encoding'] = $xmlstr->general->encoding; # Кодировка
$config['users'] = $xmlstr->general->users;
$config['usersRequest'] = $xmlstr->general->usersrequest;

$xmlstr = simplexml_load_file($path . 'data/users.php');
$config['emailAdmin'] = '';
foreach ($xmlstr->users->user as $user) {
    $access = explode(',', (string)$user['access']);
    $access = array_map('trim', $access);
    if (in_array('creatingAccounts', $access)) {
        $config['emailAdmin'] = (string)$user['email'];
        break;
    }
}
}

function adminsConfig() {
    global $path;
    $xml = simplexml_load_file($path . 'data/users.php');

    $admins = [];
    foreach ($xml->users->user as $user) {
        $accessList = array_map('trim', explode(', ', (string)$user['access']));

        if (in_array('Admin', $accessList, true)) {
            $admins[] = (string)$user['name'];
        }
    }

    return $admins;
}

# Генерация меню. По умолчанию ссылка активной страницы выделяется классом "selected"
function GetMenuItems($menuVar){
	global $config;
	$menu = '';
	for ($i = 0; $i <= count($menuVar)-1; $i+=1)
		{
		$menu.= '<a href="'.$config['server'].$menuVar[$i]['url'].'.html" title="'.$menuVar[$i]['title'].'">'.$menuVar[$i]['name'] . '</a> ';
		if ($i <= count($menuVar)-2)
			{
				$menu.= ':: ';
			}	
		}
	return $menu;	
}

#Формировани блоков $BlockVar масив влоков $side тип блока tclass bclass
function GetBlock ($BlockVar, $side) {
	global $path, $ansv, $REQUEST_URI,$menu, $config, $EditPage;
	$Block = '';
	if (is_countable($BlockVar) && count($BlockVar) > 0){ 
		for ($i = 0; $i <= count($BlockVar)-1; $i+=1){
			ob_start();
			include $path . $BlockVar[$i]['url'].'plug.php';
			$Xblock = ob_get_contents();
			ob_end_clean();

			$Block.='<div plugin-url="'.$BlockVar[$i]['url'].'">';
			if ($BlockVar[$i]['title']!=''){
				$Block.='<div plugin-title="pluginTitle" tclass="tclass" class="'.$BlockVar[$i]['tclass'].'">'.$BlockVar[$i]['title'].'</div>';
			}
			$Block.='<div bclass="bclass" class="'.$BlockVar[$i]['bclass'].'"><div class="bcont">'.$Xblock.'</div></div>';
			$Block.= '</br> ';
			$Block.='</div>';
			
		}
	}
	return $Block;	

	// $Block.='<div class="'.$BlockVar[$i]['bclass'].'"><div class="bcont">ku ku</div></div>';
	/*is_countable($$BlockVar) && count($BlockVar)
	$Block = "";
	if (is_countable($$BlockVar)  && count($BlockVar) > 0){
		$Block = "true";
	}
	else{
		$Block = "false";
	}
	$Block = count($BlockVar);*/
}
# Функция обработки ошибки
function error404($pageout = false, $encoding = 'utf-8')
{
	header('Cache-Control: no-cache, no-store');
	header('Content-Type: text/html; charset=' . $encoding);
	header($_SERVER['SERVER_PROTOCOL'] . ' 404 Not Found');
	if ($pageout)
		readfile('404.shtml');
	die;
}

# Функция обработки ошибки
function error405($pageout = false, $encoding = 'utf-8')
{
	header('Cache-Control: no-cache, no-store');
	header('Content-Type: text/html; charset=' . $encoding);
	header($_SERVER['SERVER_PROTOCOL'] . ' 405 Not Found');
	if ($pageout)
		readfile('405.shtml');
	die;
}

# Функция HTTP авторизации. Логин и пароль задаются в файле users.xml
# Форма авторизации
function Log_Form($Vector,$act) {
	if ($Vector=='h')	$sep	= ' ';
	else				$sep	= '<br/>';
	$string = '<form action="'.$_SERVER["REQUEST_URI"].'" method="post">';
	$string .= '<input type="hidden" name="handleRequestAction" value="API">';
	switch ($act){
		case 'log_on':{
			$string .= '<label>Логин: </label>';
			$string .= $sep;
			$string .= '<input type = "text" name = "login">';
			$string .= $sep;
			$string .= '<label>Пароль: </label>';
			$string .= $sep;
			$string .= '<input type = "password" name = "pass" autocomplete>';
			$string .= $sep;
			$string .= '<form method="post"><input type="hidden" name="handleRequestAction" value="API">
    			<input type="submit" name="log" value="Войти"></form>';
			break;
			}
		case 'log_off':{
		    $string .= '<form method="post"><input type="hidden" name="handleRequestAction" value="API">
    			<input type="submit" name="logoff" value="Выйти"></form>';
			break;
			}
		case 'log_err':{
			$string .= '<label>Фигню написал, батинька!!! </label>';
			$string .= $sep;
		    $string .= '<form method="post"><input type="hidden" name="handleRequestAction" value="API">
    			<input type="submit" name="LogPage" value="Попробуйте ещё раз"></form>';
			break;
			}
		}
	$string .= '</form>';
	$_SESSION['Login']	='';

	return $string;
}

# Проверка логина и пароля
function check($login, $pass) {
    global $config, $uxml, $path;
    $xmlstr = simplexml_load_file($path . $config['users']);
    $result = false;
    foreach ($xmlstr->users->user as $user) {
        if ((string)$user['name'] === $login && (string)$user['pass'] === $pass) {
            $result = true;
        }
    }
    return $result;
}

function LngMenu() {
	$s = '<ul><li>' . $_SESSION['lng'] . '<ul><span id="f">';
	
	if ($_SESSION['lng'] != 'lv') {
		$s .= '<button id="lng_lv" onclick="sendLanguageRequest(\'lv\')" type="button" title="Latviski" value="lv"><span>LV</span></button><br>';
	}
	if ($_SESSION['lng'] != 'en') {
		$s .= '<button id="lng_en" onclick="sendLanguageRequest(\'en\')" type="button" title="English" value="en"><span>EN</span></button><br>';
	}
	if ($_SESSION['lng'] != 'ru') {
		$s .= '<button id="lng_ru" onclick="sendLanguageRequest(\'ru\')" type="button" title="По русски" value="ru"><span>RU</span></button><br>';
	}
	
	$s .= '</span></ul></li></ul>';
	
	$s .= '
<script>
async function sendLanguageRequest(language) {
if (document.getElementById("basis3")) {
   if (document.getElementById("basis3").style.visibility === "visible" && window.contentIsEdit == true) {
      messageQueue.push("Сохранить данные?");
      try {
         const userConfirmed = await messageCreateQuestion();
         if (userConfirmed) {
            if (window.newPageFunValue == "newPage") {
               document.getElementById("saveHow").click();
               messageFunction("Сохраните новую страницу!");
               return;
            } else {
               await saveChanges();
            }
         }
      } catch (error) {
         console.log("Ошибка: ", error);
      }
   }
}
   
   var form = document.createElement("form");
   form.method = "post";
   form.action = "";
   
   var inputLng = document.createElement("input");
   inputLng.type = "hidden";
   inputLng.name = "lng";
   inputLng.value = language;
   form.appendChild(inputLng);
   
   var inputAction = document.createElement("input");
   inputAction.type = "hidden";
   inputAction.name = "handleRequestAction";
   inputAction.value = "API";
   form.appendChild(inputAction);
   
   document.getElementById("f").appendChild(form);
   form.submit();   
}
</script>
';
	
	return $s;
}

function SetLng(){
	global $_SESSION, $path;
	if (isset($_POST['lng']) && $_POST['lng'] != '')
        $_SESSION['lng'] = $_POST['lng'];
    if (empty($_SESSION['lng'])){
        $s = explode(',', $_SERVER['HTTP_ACCEPT_LANGUAGE']);
        $a = explode('-', $s[0]);
        $_SESSION['lng'] = $a[0];
    }
    return $_SESSION['lng'];
}  

function GetRequestURL($URL){
$c=explode('.',$URL);
if ($c[1]=='html'&&count($c)!=1){
	$mURL['act']	='view';
	$mURL['str'] = explode('/',$c[0]);
	$mURL['str'][0]="index";
	if ($mURL['str'][1]=='index'){
		$mURL['str'][1]='';
		}
	if ($mURL['str'][count($mURL['str'])-1]==''){
		array_pop($mURL['str']);
		}
	}
else{
	if ($c[1]=='xml'&&count($c)!=1){
		$mURL['act']	='edit';
	$mURL['str'] = explode('/',$c[0]);
	$mURL['str'][0]="index";
		}
	else{
		$mURL['str']='error';
		}
	}
return $mURL;
}

# Генерация меню. По умолчанию ссылка активной страницы выделяется классом "selected"
function GetXMLMenu($menuVar,$RURLstr,$ItemNo,$Vector){
	global $config, $path, $_SESSION;

	$child_menu = "";
	$topURL = '';

	if ($ItemNo!=0) {
		for ($i = 1; $i <= $ItemNo; $i+=1) {
			$topURL		.=$RURLstr[$i].'/';
			$menuVar	=$menuVar->{$RURLstr[$i]};
		}
	}
	
	$i = 0;
	foreach ($menuVar->children() as $child_page) {
		if (FindPageUser($child_page['users'],$_SESSION['username'])) {
			if ($i!=0) {
				if ($Vector!='v') {
					$child_menu		.=' :: ';
				} else {
					$child_menu		.='<br>';
				}
			}
			$child_menu	.= '<a href="'.$config['server'].$topURL.$child_page->getName().'.html">' . $child_page['title'] . '</a>';
			$i=$i+1;
		}
	}

	return	$child_menu;
}
function GetSideXMLMenu($menuVar,$RURLstr,$ItemNo){
	global $config, $path, $_SESSION;

	$child_menu = "";
	$topURL = '';

	if ($ItemNo!=0) {
		for ($i = 1; $i <= $ItemNo; $i+=1) {
			$topURL		.=$RURLstr[$i].'/';
			$menuVar	=$menuVar->{$RURLstr[$i]};
		}
	}

	$child_menu.='<div class="side-menu-header">';
	$child_menu.='<label for="menu-toggle" class="menu-btn close">×</label>';
	$child_menu.='<a href="'.$config['server'].'" class="side-home">Home</a>';
	$child_menu.='</div>';

	foreach ($menuVar->children() as $child_page) {
		if (FindPageUser($child_page['users'],$_SESSION['username'])) {
			$child_menu.='<a href="'.$config['server'].$topURL.$child_page->getName().'.html" class="side-link">'.$child_page['title'].'</a>';
		}
	}

	return $child_menu;
}

function FindPageUser($PageUser,$user){
if ($PageUser==''){
	$test =true;
	}
else{
	$test	=false;
	$PageUser	=explode(',',$PageUser);
	for ($i = 0; $i <= count($PageUser)-1; $i+=1){
		if ($PageUser[$i]==$user){
			$test =true;
			}
		}
	}
return $test;
}

function URLstr($FPfile,$RURLstr){
global $path, $server;
$xmlstr 				=simplexml_load_file($FPfile);
$ansv['sitename'] 		=$xmlstr->sitename;
$ansv['XML'] 			=$xmlstr;
$ansv['pageURL'] 		=$xmlstr->sitename;
$fileURL				='http://'.$_SERVER['HTTP_HOST'];
$ansv['URLLine']		="";
if ($RURLstr!='error'){
	for ($i = 0; $i <= count($RURLstr)-1; $i+=1){
		if ($xmlstr->{$RURLstr[$i]}['name']!=''){
			if ($i!=count($RURLstr)-1)	{
				if ($i!=0){
					$fileURL		.='/'.$xmlstr->{$RURLstr[$i]}->getName();
					$end			='.html';
					}
				else{
					$end			='/index.html';
					}
				$ansv['URLLine'] 	.= '<a href="'.$fileURL.$end.'" title="'.$xmlstr->{$RURLstr[$i]}['title'].'">'.$xmlstr->{$RURLstr[$i]}['name'].'</a>>>';
				}
			else{
				$ansv['URLLine']	.= $xmlstr->{$RURLstr[$i]}['name'];
				$ansv['FileURL']	= $xmlstr->{$RURLstr[$i]}['url'];
				$ansv['template']	= $xmlstr->{$RURLstr[$i]}['template'];
				$ansv['title']		= $xmlstr->{$RURLstr[$i]}['title'];
				$ansv['page']		= $xmlstr->{$RURLstr[$i]};
				}
		$xmlstr = $xmlstr->{$RURLstr[$i]};
		}
		else {
			$ansv['URLLine'] = 'error';
			$ansv['FileURL'] = 'error';
			}
	}
	}

	return $ansv;
}

function SetXML($file){

}
?>