<?php require_once('../../db.php'); ?>
<?php 
// if isset post
if ( isset($_POST["client_number"]) && isset($_POST["init_message"]) ) {
	
	
	// first look if client already exists!!!
	try {
		$core = Core::getInstance();
		$stmt = $core->dbh->prepare("SELECT client_id FROM myclients WHERE client_number = :client_number");
		$stmt -> bindParam("client_number", $_POST["client_number"], PDO::PARAM_STR);
		$stmt -> execute();
		$row_count = $stmt -> rowCount();
		$row = $stmt -> fetch();
		
		
	} catch(PDOException $pe) {
		trigger_error('Could not connect to MySQL database. ' . $pe->getMessage() , E_USER_ERROR);
	}
	
	if ($row_count < 1) {
		try {
			$core = Core::getInstance();
			$stmt = $core->dbh->prepare("INSERT INTO myclients (client_number, init_message) VALUES (:client_number, :init_message)");
			$stmt -> bindParam("client_number", $_POST["client_number"], PDO::PARAM_STR);
			$stmt -> bindParam("init_message", $_POST["init_message"], PDO::PARAM_STR);
			
			if ($stmt->execute()) {
				echo "true";
			} else {
				echo "Message has not been added";
			}
			
		} catch(PDOException $pe) {
			trigger_error('Could not connect to MySQL database. ' . $pe->getMessage() , E_USER_ERROR);
		}
	} else {
		try {
			$whosent = "0";
			$core = Core::getInstance();
			$stmt = $core->dbh->prepare("INSERT INTO messages (mess_client_id, mess_message, mess_whosent) VALUES (:mess_client_id, :mess_message, :mess_whosent)");
			$stmt -> bindParam("mess_client_id", $row["client_id"], PDO::PARAM_INT);
			$stmt -> bindParam("mess_message", $_POST["init_message"], PDO::PARAM_STR);
			$stmt -> bindParam("mess_whosent", $whosent, PDO::PARAM_STR);
			
			if ($stmt->execute()) {
				echo "true";
			} else {
				echo "Message has not been added";
			}
		} catch(PDOException $pe) {
			trigger_error('Could not connect to MySQL database. ' . $pe->getMessage() , E_USER_ERROR);
		}
		// echo "Message has not been added, duplicated number.";
	}
}
?>