<?php
if (isset($c_files) && $c_files){
	if (!isset($files_parent_guidv4)) {
		$files_parent_guidv4 = NULL;
	}
	
	$data = array();
	$sql_tmp = "SELECT guidv4, title, parent_guidv4 FROM files_levels WHERE language = :language GROUP BY guidv4 ORDER BY title 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='files_parent_guidv4' class='form-label tree'>".LABEL_FILES_LEVEL."</label>
	<div class='form-cols'>
		<div class='form-col form-full'>
			<div class='form-controls tree-select'>";
	if (isset($files_parent_guidv4) && $files_parent_guidv4){
		print "<input type='hidden' name='files_parent_guidv4' class='files_parent_guidv4' value='".$files_parent_guidv4."' />";
	}
	print "
				<div class='files_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($files_parent_guidv4);
	$script['single'] = "true";
	$script['placeholder'] = LABEL_SEARCH;
	$script['empty'] = LABEL_NO_RESULTS;
	
	$script['js'] = <<<JS
		if ($('.files_formselect').length != 0){
			const formselect = new Treeselect({
			  parentHtmlContainer: document.querySelector('.files_formselect'),
			  options: {$script['options']},
				value: {$script['value']},
			  id: "files_parent_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) => {
			$('.files_parent_guidv4').remove();
			if (e.detail) $('<input type="hidden" name="files_parent_guidv4" class="files_parent_guidv4" value="'+e.detail+'\" />').insertBefore('.files_formselect');
		});
		JS;
	$script['js'] .= <<<JS
		}
		JS;
	print "<script>".$script['js']."</script>";

}