<?php
$module_ini = get_encryption_ini($backend_module);
$encryption_key = $module_ini['encryption_key'] ?? null;
$pepper = $module_ini['pepper'] ?? null;
if ($sub_page == 1){
	print "
<div class='container'>
	<form action='".$_SERVER['REQUEST_URI']."' method='post' enctype='multipart/form-data'>
		<div class='form'>
			<div class='form-head toggle ";
	if (isset($_SESSION['backend']['toggle_filter']) && $_SESSION['backend']['toggle_filter']) print'toggled';
	print "'>
				<i class='material-icons md-24'>filter_alt</i>".LABEL_FILTER."<i class='ico-toggle material-icons md-24'>expand_less</i>
			</div>
			<div class='form-content ";
	if (isset($_SESSION['backend']['toggle_filter'])) print $_SESSION['backend']['toggle_filter'];
	print "' data-module='".$module."' data-backend-module='".$backend_module."'>
				<input type='hidden' name='csrf_token' value='".htmlspecialchars(csrf_token())."'>
				<input type='hidden' name='filter' value='1' />
				<input type='hidden' name='export' value='0' />
				<input type='hidden' name='order' value='".$order."' />
				<input type='hidden' name='lastorder' value='".$lastorder."' />
				<input type='hidden' name='orderdir' value='".$orderdir."' />";
				
	include('includes/function/c_active.php');
	include('includes/function/c_delete.php');
	
	if (isset($c_period) && $c_period) include('includes/filter/period.php');
	
	include('includes/filter/search.php');
					
	print "<hr/>";
	
	include('includes/filter/c_options.php');
	print "
				<div class='form-action'>
					<button type='submit' class='btn search' title='".LABEL_DO_FILTER."'><i class='material-icons md-24'>filter_alt</i>".LABEL_DO_FILTER."</button>
				</div><!-- /.form-action -->
				
			</div><!-- /.form-content -->
		</div><!-- /.form -->";
		

	if (isset($c_period) && $c_period) {
		$datetime_from = DateTime::createFromFormat('Y-m-d', $datetime_from)->setTime(0, 0, 0);
		$datetime_to = DateTime::createFromFormat('Y-m-d', $datetime_to)->setTime(23, 59, 59);
		$datetime_from = $datetime_from->getTimestamp();
		$datetime_to = $datetime_to->getTimestamp();
	}
				
	$sql = "SELECT * FROM ".$module." ";
	
	if (isset($c_period) && $c_period) {
		if ($datetime_to){
			$sql .= "WHERE datetime BETWEEN :datetime_from AND :datetime_to ";
		} else {
			$sql .= "WHERE datetime >= :datetime_from ";
		}
	} else $sql .= "WHERE 1 ";
	
	if (!$_SESSION['backend']['permissions']['admin']) $sql .= "AND id = :id ";
	
	if (($c_active_1 AND $c_active_0) OR (!$c_active_1 AND !$c_active_0)){
	} else {
		$sql .= "AND ( ";
		if ($c_active_1 == 1) $sql .= "c_active = '1' ";
		if ($c_active_0 == 1) $sql .= "c_active = '0' ";
		$sql .= ") ";
	}
	
	if ($search){
		$search_hash = NULL;
		
		if (file_exists('modules/'.$backend_module.'/encrypt_config.php')){
			$encrypt_config = include 'modules/'.$backend_module.'/encrypt_config.php';
			$table_config = $encrypt_config[$module] ?? [];
		
			$search_sql_parts = [];
			$search_sql_parts[] = "datetime LIKE :search";
			
			foreach ($table_config AS $key => $value){
				if (!empty($table_config[$key]['plain']) && check_column($module, $key."_plain")) {
					$search_sql_parts[] = $key."_plain LIKE :search";
				} else if (check_column($module, $key."_hash")) {
					$search_sql_parts[] = $key."_hash = :search_hash";
					if ($search_hash === null){
    				if ($module_ini && !empty($pepper)) {
    					$search_hash = hash_value($search, $pepper);
    				}
					}
				} else {
					$search_sql_parts[] = $key." LIKE :search";
				}
			}
			$search_sql = implode(" OR ", $search_sql_parts);
			$sql .= "AND (".$search_sql.") ";
		} else {
			$sql.= "AND (
						lastname LIKE :search OR firstname LIKE :search OR username LIKE :search OR email LIKE :search )";
		}
	}
	
	if ($order == 'datetime'){
		$sql .= "ORDER BY ".$order." ".$orderdir.", id DESC";
	} else {
		$sql .= "ORDER BY ".$order." ".$orderdir;
	}
	
	$result = $conn->prepare($sql);
	
	if (isset($c_period) && $c_period) {
		if ($datetime_to){
			$result->bindValue(':datetime_from', $datetime_from, PDO::PARAM_INT);
			$result->bindValue(':datetime_to', $datetime_to, PDO::PARAM_INT);
		} else {
			$result->bindValue(':datetime_from', $datetime_from, PDO::PARAM_INT);
		}
	}
	
	if (!$_SESSION['backend']['permissions']['admin']) $result->bindValue(':id', $_SESSION['backend']['id_session'], PDO::PARAM_INT);
	
	if ($search){
		$result->bindValue(':search', "%{$search}%", PDO::PARAM_STR);
		if ($search_hash !== null) {
			$result->bindValue(':search_hash', $search_hash, PDO::PARAM_STR);
		}
	}
	
	$result->execute();
		
	$count = $result->rowCount();
	
	$_SESSION['cmt'][$backend_module][$module]['id_list'] = array();
	$_SESSION['cmt'][$backend_module][$module]['pages'] = 1;
	if (isset($admin_settings['module'][$module.'_filter'])) $_SESSION['cmt'][$backend_module][$module]['pages'] = ceil($count / $admin_settings['module'][$module.'_filter']);

	print "
		<div class='button'>
			<a href='#' class='btn add' data-module='".$module."' data-backend-module='".$backend_module."'><i class='material-icons md-24'>add</i>".LABEL_NEW_ENTRY."</a>
		</div><!-- /.button -->
	
		<div class='table'>
		
			<div class='table-head'>
				<div class='table-row'>
					<div class='table-cell size-small'><a href='#' class='order' data-order='datetime'>".LABEL_DATETIME;
	if ($order == 'datum') print "<i class='ico-toggle material-icons md-24 md-white ".$orderdir."'>expand_less</i>";
	print "</a></div><!-- /.table-cell -->
					<div class='table-cell size-small'><a href='#' class='order' data-order='lastname'>".LABEL_LASTNAME;
	if ($order == 'lastname') print "<i class='ico-toggle material-icons md-24 md-white ".$orderdir."'>expand_less</i>";
	print "</a></div><!-- /.table-cell -->
					<div class='table-cell size-small'><a href='#' class='order' data-order='firstname'>".LABEL_FIRSTNAME;
	if ($order == 'firstname') print "<i class='ico-toggle material-icons md-24 md-white ".$orderdir."'>expand_less</i>";
	print "</a></div><!-- /.table-cell -->
					<div class='table-cell size-medium'><a href='#' class='order' data-order='username'>".LABEL_USERNAME;
	if ($order == 'username') print "<i class='ico-toggle material-icons md-24 md-white ".$orderdir."'>expand_less</i>";
	print "</a></div><!-- /.table-cell -->
					<div class='table-cell'><a href='#' class='order' data-order='email'>".LABEL_EMAIL;
	if ($order == 'email') print "<i class='ico-toggle material-icons md-24 md-white ".$orderdir."'>expand_less</i>";
	print "</a></div><!-- /.table-cell -->
					<div class='table-cell size-xxsmall'><a href='#' class='order' data-order='c_active'><i class='material-icons md-24 md-white'>toggle_on</i>";
	if ($order == 'c_active') print "<i class='ico-toggle material-icons md-24 md-white ".$orderdir."'>expand_less</i>";
	print "</a></div><!-- /.table-cell -->
					<div class='table-cell toolbar'></div><!-- /.table-cell -->
				</div><!-- /.table-row -->
			</div><!-- /.table-head -->";
			
	if ($count){
		print "
			<div class='table-body ";
		if (!$_SESSION['backend']['settings']['context']) print "no-context";
		print "'>";
		while($arr = $result->fetch()){
			$_SESSION['cmt'][$backend_module][$module]['id_list'][$arr['id']] = $arr['id'];
		}
	}
}

if (isset($_SESSION['cmt'][$backend_module][$module]['id_list']) && count($_SESSION['cmt'][$backend_module][$module]['id_list']) >= 1){
	
	$q_array = $_SESSION['cmt'][$backend_module][$module]['id_list'];
	if (isset($admin_settings['module'][$module.'_filter']) && count($_SESSION['cmt'][$backend_module][$module]['id_list']) > $admin_settings['module'][$module.'_filter']) {
		$q_array = array_slice($_SESSION['cmt'][$backend_module][$module]['id_list'], 0, $admin_settings['module'][$module.'_filter'], true);
	}
	
	$q_array = join(",", $q_array);
	
	$sql = "SELECT * FROM ".$module." AS module WHERE id IN ($q_array) ORDER BY FIELD (id, $q_array) ";
	if (isset($admin_settings['module'][$module.'_filter'])) $sql.= "LIMIT :limit ";
	$result = $conn->prepare($sql);
	if (isset($admin_settings['module'][$module.'_filter'])) $result->bindValue(':limit', $admin_settings['module'][$module.'_filter'], PDO::PARAM_INT);
	$result->execute();
	
	if ($result->rowCount()){
		while ($arr = $result->fetch()){
			unset($_SESSION['cmt'][$backend_module][$module]['id_list'][$arr['id']]);
			$datetime = date("d.m.Y - H:i", $arr['datetime']);
			
			$lastname = $arr['lastname'];
			$firstname = $arr['firstname'];
			$email = $arr['email'];
			
			if ($module_ini && $encryption_key && isset($arr)) {
				if (file_exists('modules/'.$backend_module.'/encrypt_config.php')){
					$encrypt_config = include 'modules/'.$backend_module.'/encrypt_config.php';
					$table_config = $encrypt_config[$module] ?? [];
					
					foreach ($table_config as $key => $config) {
						if (isset($arr[$key])) {
							${$key} = decrypt_field($arr, $key, $encryption_key);
						}
					}
				}
			}
			
			print "
				<div class='table-row ";
			if (!$arr['c_active']) print "inactive";
			print "' data-id='".$arr['id']."' data-module='".$module."' data-backend-module='".$backend_module."'>
					<div class='table-cell'>".$datetime."</div><!-- /.table-cell -->
					<div class='table-cell'>".$lastname."</div><!-- /.table-cell -->
					<div class='table-cell'>".$firstname."</div><!-- /.table-cell -->
					<div class='table-cell'>".$arr['username']."</div><!-- /.table-cell -->
					<div class='table-cell'>".$email."</div><!-- /.table-cell -->
					<div class='table-cell aligncenter c_active'>
						<a href='#' id='".$arr['id']."' class='activate' title='";
			if ($arr['c_active'] == 1) print LABEL_DEACTIVATE;
			else print LABEL_ACTIVATE;
			print "'>";
			if ($arr['c_active'] == 1) print "<i class='material-icons md-24'>toggle_on</i>";
			else print "<i class='material-icons md-24 md-grey'>toggle_off</i>";
			print "</a></div><!-- /.table-cell -->
					<div class='table-cell toolbar'>
						<a href='#' class='edit' data-id='".$arr['id']."' data-module='".$module."' data-backend-module='".$backend_module."' title='".LABEL_EDIT."'><i class='material-icons md-22'>edit</i></a>
						<a href='#' class='copy' data-id='".$arr['id']."' data-module='".$module."' data-backend-module='".$backend_module."' title='".LABEL_COPY."'><i class='material-icons md-22'>content_copy</i></a>
						<a href='#' class='delete' data-id='".$arr['id']."' title='".LABEL_DELETE."'><i class='material-icons md-22'>delete_forever</i></a>
					</div><!-- /.table-cell -->
				</div><!-- /.table-row -->";
		}
		
		if ($sub_page == 1){
			print "
			</div><!-- /.table-body -->
		</div><!-- /.table -->";
		}
	}
}

if ($sub_page == 1){
	print "
	</form>
</div><!-- /.container -->
<div class='context-menu'>
 <ul>
    <li><a href='#' class='edit' title='".LABEL_EDIT."'><i class='material-icons md-24'>edit</i>".LABEL_EDIT."</a></li>
    <li><a href='#' class='copy' title='".LABEL_COPY."'><i class='material-icons md-24'>content_copy</i>".LABEL_COPY."</a></li>
    <li><a href='#' class='delete' title='".LABEL_DELETE."'><i class='material-icons md-24'>delete_forever</i>".LABEL_DELETE."</a></li>
 </ul>
</div>";
}