<?php
if (!isset($default_guidv4)) {
	$default_guidv4 = NULL;
}

$data = array();
$sql_tmp = "SELECT guidv4, title, parent_guidv4 FROM content_levels WHERE language = :language GROUP BY guidv4 ORDER BY sortorder ASC";
$result_tmp = $conn->prepare($sql_tmp);
if (isset($language) && $language) $result_tmp->bindValue(':language', $language, PDO::PARAM_STR);
else $result_tmp->bindValue(':language', $_SESSION['backend']['language'], PDO::PARAM_STR);
$result_tmp->execute();

if ($result_tmp->rowCount()){
	while($arr_tmp = $result_tmp->fetch()){
		$data[] = $arr_tmp;
	}
}

print "
<div class='form-row'>
	<label for='default_guidv4' class='form-label tree'>".LABEL_DEFAULT_GUIDV4."</label>
	<div class='form-cols'>
		<div class='form-col form-full'>
			<div class='form-controls tree-select'>";
if (isset($default_guidv4) && $default_guidv4){
	print "<input type='hidden' name='default_guidv4' class='default_guidv4' value='".$default_guidv4."' />";
}
print "
				<div class='default_formselect'></div>
			</div><!-- /.form-controls -->
		</div><!-- /.form-col -->
	</div><!-- /.form-cols -->
</div><!-- /.form-row -->

<hr />";

$script = array();
$script['js'] = NULL;
$script['options'] = json_encode(build_tree($data, true));
$script['value'] = json_encode($default_guidv4);
$script['single'] = "true";
$script['placeholder'] = LABEL_SEARCH;
$script['empty'] = LABEL_NO_RESULTS;

$script['js'] = <<<JS
	if ($('.default_formselect').length != 0){
		const formselect = new Treeselect({
		  parentHtmlContainer: document.querySelector('.default_formselect'),
		  options: {$script['options']},
			value: {$script['value']},
		  id: "default_guidv4",
		  openLevel: 5,
		  placeholder: "{$script['placeholder']}",
		  emptyText: "{$script['empty']}",
		  isIndependentNodes: true,
		  isSingleSelect: {$script['single']},
		  iconElements: {
		  	arrowUp: "<i class='material-icons md-20'>expand_less</i>",
		  	arrowDown: "<i class='material-icons md-20'>expand_more</i>",
		  	arrowRight: "<i class='material-icons md-20'>chevron_right</i>",
		  	attention: "<i class='material-icons md-20 md-blue'>warning_amber</i>",
		  	clear: "<i class='material-icons out md-20'>cancel</i>",
		  	cross: "<i class='material-icons md-20'>close</i>",
		  	check: "<i class='material-icons md-16'>check</i>",
		  	partialCheck: "<i class='material-icons md-16'>remove</i>"
		  }
		});
	JS;

$script['js'] .= <<<JS
	formselect.srcElement.addEventListener('input', (e) => {
		$('.default_guidv4').remove();
		if (e.detail) $('<input type="hidden" name="default_guidv4" class="default_guidv4" value="'+e.detail+'\" />').insertBefore('.default_formselect');
	});
	JS;
$script['js'] .= <<<JS
	}
	JS;
print "<script>".$script['js']."</script>";
