<?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($_POST['search']) === true){
		$search = $_POST['search'];
	} else {
		echo "invalid character found in search.";
		exit;
	}
} else {
	$search = "";
}

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

# set the limit for the profile list
$limit = 10;

foreach ($cnames as $code => $country) {
	if (empty($search)) {
		$available[] = $country;
	} else if (stripos($country, $search)!==false || strtolower($code) == strtolower($search)) {
		$available[] = $country;
	}
	if (count($available) >= $limit) {
		break;
	}
}

# Output available
echo json_encode($available);
?>
