<?php
function saveContentIdData() {
	global $config, $path, $_SESSION;

	$filePath = $path . $_SESSION['page_url'] . ".page.php";
	$data = $_POST['saveContentIdData'] ?? '';
	$file = simplexml_load_file($filePath);
	$langNode = $file->content->{$_SESSION['lng']};

	$file->content->{$_SESSION['lng']} = '';
	$node = dom_import_simplexml($langNode);
	$doc = $node->ownerDocument;

	if ($node->appendChild($doc->createCDATASection("\n" . $data . "\n")) && $file->asXML($filePath)) {
		return ['result' => 1];
	}
	return ['result' => 0];
}

function floatsBlock() {
	global $config, $path, $_SESSION;

	$filePath = $path . $_SESSION['page_url'] . ".page.php";
	$file = simplexml_load_file($filePath);

	$data = json_decode($_POST['floatsBlock'], true);
	$left = $data['left'] ?? [];
	$right = $data['right'] ?? [];

	unset($file->lblock->block);
	unset($file->rblock->block);

	foreach ($left as $b) {
		$n = $file->lblock->addChild('block');
		$n->addAttribute('url', htmlspecialchars($b['pluginUrl'], ENT_QUOTES, 'UTF-8'));
		$n->addAttribute('title', htmlspecialchars($b['title'], ENT_QUOTES, 'UTF-8'));
		$n->addAttribute('tclass', htmlspecialchars($b['tclass'], ENT_QUOTES, 'UTF-8'));
		$n->addAttribute('bclass', htmlspecialchars($b['bclass'], ENT_QUOTES, 'UTF-8'));
	}

	foreach ($right as $b) {
		$n = $file->rblock->addChild('block');
		$n->addAttribute('url', htmlspecialchars($b['pluginUrl'], ENT_QUOTES, 'UTF-8'));
		$n->addAttribute('title', htmlspecialchars($b['title'], ENT_QUOTES, 'UTF-8'));
		$n->addAttribute('tclass', htmlspecialchars($b['tclass'], ENT_QUOTES, 'UTF-8'));
		$n->addAttribute('bclass', htmlspecialchars($b['bclass'], ENT_QUOTES, 'UTF-8'));
	}

	$dom = new DOMDocument('1.0', 'UTF-8');
	$dom->preserveWhiteSpace = false;
	$dom->formatOutput = true;
	$dom->loadXML($file->asXML());

	return ['result' => $dom->save($filePath) ? 1 : 0];
}

function newTitle() {
	global $config, $path, $_SESSION;

	$title = htmlspecialchars($_POST['newTitle'] ?? '', ENT_QUOTES, 'UTF-8');
	$filePath = $path . "data/filepath." . $_SESSION['lng'] . ".php";
	$file = simplexml_load_file($filePath);

	$p = rtrim($config['REQUEST_URI'], '.html');
	$parts = explode('/', $p);
	$node = $file->index;

	foreach ($parts as $n) {
		if ($n !== '') {
			if (isset($node->$n)) {
				$node = $node->$n;
			} else {
				return ['error' => "Node not found: $n"];
			}
		}
	}

	$node['title'] = $title;

	if ($file->asXML($filePath)) {
		return ['result' => 'ok'];
	}
	return ['error' => 'Save failed'];
}

function saveContentIdDataHow() {
	global $config, $path, $_SESSION;

	$_SESSION['page_url'] = $_POST['page_url'] . str_replace('.page.php', '', $_POST['nameFile']);
	$filePath = $path . $_POST['page_url'] . $_POST['nameFile'];
	$content = $_POST['saveContentIdData'] ?? '';
	$file = simplexml_load_file($filePath);

	$langNode = $file->content->{$_SESSION['lng']};
	$file->content->{$_SESSION['lng']} = '';
	$node = dom_import_simplexml($langNode);
	$doc = $node->ownerDocument;
	$node->appendChild($doc->createCDATASection("\n" . $content . "\n"));

	$file->rblock = '';
	$file->lblock = '';
	$blocks   = $_POST['floatsBlock'] ?? [];
	$titles   = $_POST['title']       ?? [];
	$urls     = $_POST['pluginUrl']   ?? [];
	$tclasses = $_POST['tclass']      ?? [];
	$bclasses = $_POST['bclass']      ?? [];

	foreach ($blocks as $i => $blockName) {
		$n = $file->$blockName->addChild('block');
		$n->addAttribute('url', htmlspecialchars($urls[$i], ENT_QUOTES, 'UTF-8'));
		$n->addAttribute('title', htmlspecialchars($titles[$i], ENT_QUOTES, 'UTF-8'));
		$n->addAttribute('tclass', htmlspecialchars($tclasses[$i], ENT_QUOTES, 'UTF-8'));
		$n->addAttribute('bclass', htmlspecialchars($bclasses[$i], ENT_QUOTES, 'UTF-8'));
	}

	$dom = new DOMDocument('1.0','UTF-8');
	$dom->preserveWhiteSpace = false;
	$dom->formatOutput = true;
	$dom->loadXML($file->asXML());

	return ['result' => $dom->save($filePath) ? 1 : 0];
}

function createNewFile() {
	global $config, $path, $_SESSION;

	$_SESSION['page_url'] = $_POST['page_url'] . str_replace('.page.php', '', $_POST['nameFile']);
	$savePath = $path . $_POST['page_url'] . $_POST['nameFile'];
	$template = $path . "data/template.page.php";
	$data = $_POST['saveContentIdData'] ?? '';

	if (!file_exists($template)) return ['result' => 0];
	if (file_put_contents($savePath, file_get_contents($template)) === false) return ['result' => 0];

	$file = simplexml_load_file($savePath);
	$node = $file->content->{$_SESSION['lng']};
	$file->content->{$_SESSION['lng']} = '';
	$dom = dom_import_simplexml($node)->ownerDocument;
	dom_import_simplexml($node)->appendChild($dom->createCDATASection("\n".$data."\n"));
	return ['result' => $file->asXML($savePath) ? 1 : 0];
}

function checkFileExists() {
	global $path;
	$f = $path . ($_POST['page_url'] ?? '') . ($_POST['nameFile'] ?? '');
	return ['exists' => file_exists($f) ? 1 : 0];
}

function managerPlugin() {
	$a = $_POST['action'];
	$n = $_POST['pluginName'] ?? '';
	$d = __DIR__ . '/../../plugin/';
	switch ($a) {
		case 'check':
			return ['status' => (is_dir($d.$n) ? 'exists' : 'not_exists')];
		case 'create':
			if (!file_exists($d.$n)) {
				umask(0);
				mkdir($d.$n, 0777, true);
				file_put_contents($d.$n.'/plug.php', "<?php\n echo '<div class=\"pluginEditable\" contenteditable=\"true\"></div>'; \n?>");
				return ['status' => 'created', 'plugin' => $n];
			}
			return ['status' => 'already_exists'];
		case 'add':
			$list = array_map('basename', array_filter(glob($d.'*'), 'is_dir'));
			return ['plugins' => $list];
		case 'save':
			$url = $_POST['pluginUrlSave'] ?? '';
			$html = $_POST['pluginInnerHtml'] ?? '';
			$name = basename(parse_url($url, PHP_URL_PATH));
			$file = $d.$name.'/plug.php';
			$res = file_put_contents($file, "<?php\n echo '<div class=\"pluginEditable\" contenteditable=\"true\">".$html."</div>';\n?>");
			return ['status' => $res !== false ? 'saved' : 'error'];
	}
	return ['error' => 'Unknown action'];
}

function loadPlugin() {
	$name = $_POST['pluginName2'] ?? '';
	$dir = __DIR__ . '/../../plugin/' . $name . '/plug.php';
	if (!file_exists($dir)) return ['error' => 'not_found'];
	ob_start();
	include($dir);
	return ['html' => ob_get_clean()];
}

function uploadUserImage() {
	global $config, $path, $_SESSION;

	$dir = 'img/users_img/' . $_SESSION['username'] . "/";
	$f = $_FILES['userImg']['name'];
	$b = pathinfo($f, PATHINFO_FILENAME);
	$e = pathinfo($f, PATHINFO_EXTENSION);

	if (!is_dir($dir)) mkdir($dir, 0755, true);
	$n = $b;
	$i = 1;
	while (file_exists($dir . $n . '.' . $e)) $n = $b . '_' . ++$i;
	$target = $dir . $n . '.' . $e;

	if (move_uploaded_file($_FILES['userImg']['tmp_name'], $target)) {
		return ['path' => str_replace('\\', '/', $target)];
	}
	return ['error' => 'upload_failed'];
}

function nameUser() {
	global $config;
	return ['user' => $config['User']];
}
?>