<?php require_once("../../db.php"); ?>

<?php try {
	
		$arrayOfValues = explode(",", $_GET["serialized_client_ids"]);
		$questionMarks = join(",", array_pad(array(), count($arrayOfValues), "?"));
		
		
		$core = Core::getInstance();
		//$stmt = $core->dbh->prepare("SELECT * FROM messages LEFT JOIN myclients on mess_client_id = client_id WHERE mess_client_id in ($questionMarks) and mess_id in (SELECT MAX(mess_id) FROM messages GROUP BY mess_client_id) group by mess_client_id order by mess_date");
		$stmt = $core->dbh->prepare("SELECT m.*, myclients.* FROM messages m INNER JOIN (SELECT mess_client_id, MAX(mess_date) as mess_date FROM messages GROUP BY mess_client_id) as mymax USING (mess_client_id, mess_date) LEFT JOIN myclients on myclients.client_id = m.mess_client_id WHERE m.mess_client_id in ($questionMarks) ORDER BY m.mess_date");
		
		$stmt -> execute($arrayOfValues);
		$results = $stmt -> fetchAll(PDO::FETCH_ASSOC);
		
	
		foreach ($results as $key => $value) {
			$results[$key]["shorten_message"] = mb_substr($value["mess_message"], 0, $cf_howlongstring_gc);
			$results[$key]["mess_date"] = date('d.m.Y. H:i:s', strtotime($value["mess_date"]));
			$results[$key]["js_mess_date"] = strtotime($value["mess_date"]);
		}
		
		echo json_encode($results);
		
	} catch(PDOException $pe) {
		
		trigger_error('Could not connect to MySQL database. ' . $pe->getMessage() , E_USER_ERROR);
		
	}
?>