<?php


if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) || strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) !== 'xmlhttprequest') {
	die('Ajax only');
}

include_once "../common.inc.php";

if(!isset($_POST['search'])){
	echo "Missing parameters.";
	exit;
}

# if the request is not empty do a check else we want to get all profiles within the limit
if(!empty($_POST['search'])){
	# Returns TRUE if every character in text is either a letter or a digit, FALSE otherwise. 

	if(ctype_alnum(str_replace('.', '', $_POST['search'])) === true) {
		$search = $_POST['search'];
	} else {
		echo json_encode(array("Status" => "Error", "Message" => "invalid character found in search."));
		exit;
	}
} else {
	$search = "";
}

# default set an empty available array
$available = [];

# set the limit for the profile list
if(empty($search)) {
	$limit = 15;
} else {
	$limit = 100;
}


# We are admin in case if not using valid login or we truly are admin
if($session->isAdmin() || $session->allProfiles ){
	# set default variables needed for query
	$search_sql = "";
	$sql_vals = [];

	if(!empty($search)){
		# we need an LIKE !
		$search_sql = "WHERE profilename LIKE ?";
		$sql_vals[] = "%$search%";
	}

	# add limit as query value
	$sql_vals[] = $limit;

	# select limited profiles with search
	$q = "SELECT profilename FROM ". TBL_PROFILES . " {$search_sql} ORDER BY lastused DESC LIMIT ?";
	$r = $db->Execute($q, $sql_vals);
	while ($row = $r->fetchRow()) {
		if ($row['profilename']=="AggregateProfiles" && !empty($_REQUEST['multi'])) {
			continue;
		}
		$available[] = array("label" => $row['profilename'], "value" => $row['profilename']); 
	}

} else {
	# We are logged in as a user... get the profiles I may look into
	$i = 0;
	foreach ($session->user_profiles as $p) {
		# we already found enough profiles
		if($i >= $limit){
			break;
		}

		if ($p=="AggregateProfiles" && !empty($_REQUEST['multi'])) {
			continue;
		}

		if(!empty($search) && stripos($p,$search) === false){
			# search does not match 
			continue;
		} else {
			# search does match
			$available[] = array("label" => $p, "value" => $p); 
			$i ++;
		}
	}
}

# now add an option to select all
if(!empty($_REQUEST['multi'])){
	$all=[];
	foreach ($available as $v) {
		$all[] = $v['value'];
	}
	$all = implode(",",$all);
	$available[] = array("label" => ' - Select All - ', "value" => $all);
}
# Output available profiles
echo json_encode($available);
?>
