<?php require_once('../../db.php'); ?>
<?php 
// if isset post
if ( isset($_POST["post_client_id"]) && isset($_POST["post_agent"]) ) {
		
	
	// first look if client already exists!!!
	try {
		$core = Core::getInstance();
		$stmt = $core->dbh->prepare("UPDATE myclients SET ag = :ag WHERE client_id = :client_id");
		$stmt -> bindParam("ag", $_POST["post_agent"], PDO::PARAM_INT);
		$stmt -> bindParam("client_id", $_POST["post_client_id"], PDO::PARAM_INT);
		$stmt -> execute();
		$row_count = $stmt -> rowCount();
		$row = $stmt -> fetch();
		
		if ($row_count > 0) {
			
			// if agent has been updated, then copy first message into messages
			// first fetch that client!
			try {
				$core = Core::getInstance();
				$stmt = $core->dbh->prepare("SELECT client_id, init_message, date_in FROM myclients WHERE client_id = :client_id");
				$stmt -> bindParam("client_id", $_POST["post_client_id"], PDO::PARAM_INT);
				$stmt -> execute();
				$row = $stmt -> fetch();
			} catch (PDOException $pe) {
				trigger_error('Could not connect to MySQL database. ' . $pe->getMessage() , E_USER_ERROR);
			}
			// secondly insert that message
			try {
				$core = Core::getInstance();
				$stmt = $core->dbh->prepare("INSERT INTO messages (mess_client_id, mess_message, mess_date) VALUES (:mess_client_id, :mess_message, :mess_date)");
				$stmt -> bindParam("mess_client_id", $row["client_id"], PDO::PARAM_INT);
				$stmt -> bindParam("mess_message", $row["init_message"], PDO::PARAM_STR);
				$stmt -> bindParam("mess_date", $row["date_in"], PDO::PARAM_STR);
				$stmt -> execute();
				$row_count2 = $stmt -> rowCount();
				if ($row_count > 0) {
					echo "true";
				} else {
					echo "There has been an error";
				}
			} catch (PDOException $pe) {
				trigger_error('Could not connect to MySQL database. ' . $pe->getMessage() , E_USER_ERROR);
			}
		} else if ($row_count == 0) {
			echo "false";
		} else {
			echo "There has been an errror";
		}
		
		
	} catch(PDOException $pe) {
		trigger_error('Could not connect to MySQL database. ' . $pe->getMessage() , E_USER_ERROR);
	}
	
}
?>