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

<?php try {
	
		$from_record = 0;
		$reverse = true;
		if (isset($_GET["from_record"]) && is_numeric($_GET["from_record"])) {
			$from_record = $_GET["from_record"];
			$reverse = false;
		}
	
		$core = Core::getInstance();
		$stmt = $core->dbh->prepare("SELECT * FROM messages WHERE mess_client_id = :mess_client_id order by mess_date DESC limit :from_record, $cf_max_main_chat");
		$stmt -> bindParam("mess_client_id", $_GET["id"], PDO::PARAM_INT);
		$stmt -> bindParam("from_record", $from_record, PDO::PARAM_INT);
		
		$stmt -> execute();
		if ($reverse == true) {
			$results = array_reverse($stmt -> fetchAll(PDO::FETCH_ASSOC));
		} else {
			$results = $stmt -> fetchAll(PDO::FETCH_ASSOC);
		}
		
		
		foreach ($results as $key => $value) {
			//$results[$key]["mess_dateReadable"] = timeAgo($results[$key]["mess_date"]);
			$results[$key]["mess_dateReadable"] = $results[$key]["mess_date"];
			$results[$key]["mess_message"] = formatMsgMultiPart($results[$key]["mess_message"]);
		}
		
		echo json_encode($results);	
		
	} catch(PDOException $pe) {
		trigger_error('Could not connect to MySQL database. ' . $pe->getMessage() , E_USER_ERROR);
	}
?>