<?php require_once("../../db.php"); ?>
<?php 
	// first get all the details from the message!
	if ( isset($_POST["id"]) ) {
		try {
			// select this message
			$core = Core::getInstance();
			$stmt = $core->dbh->prepare("SELECT * FROM messages LEFT JOIN myclients ON mess_client_id = client_id WHERE mess_id = :mess_id");
			$stmt -> bindParam("mess_id", $_POST["id"], PDO::PARAM_INT);
			$stmt -> execute();	
			$row_count = $stmt -> rowCount();
			$row = $stmt -> fetch();
			
			// delete this message and its logs
			try {
				$core = Core::getInstance();
				$stmt = $core->dbh->prepare("DELETE FROM messages WHERE mess_id = :mess_id");
				$stmt -> bindParam("mess_id", $_POST["id"], PDO::PARAM_INT);
				$stmt -> execute();
				
				try {
					$core = Core::getInstance();
					$stmt = $core->dbh->prepare("DELETE FROM messages_log WHERE mlog_mess_id = :mess_id");
					$stmt -> bindParam("mess_id", $_POST["id"], PDO::PARAM_INT);
					$stmt -> execute();
				
				} catch(PDOException $pe) {
					trigger_error('Could not connect to MySQL database. ' . $pe->getMessage() , E_USER_ERROR);
				}
				
				
			} catch(PDOException $pe) {
				trigger_error('Could not connect to MySQL database. ' . $pe->getMessage() , E_USER_ERROR);
			}
			
		} catch(PDOException $pe) {
			trigger_error('Could not connect to MySQL database. ' . $pe->getMessage() , E_USER_ERROR);	
		}
		// if recors exists ??
		if ($row_count > 0) {
		
			try {
			
				$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)");
				$mess_whosent = "1";
				$stmt -> bindParam("mess_client_id", $row["mess_client_id"], PDO::PARAM_INT);
				$stmt -> bindParam("mess_message", $row["mess_message"], PDO::PARAM_STR);
				$stmt -> bindParam("mess_whosent", $mess_whosent, PDO::PARAM_STR);
				
				
				$stmt -> execute();
				$row_count_insert = $stmt -> rowCount();
				
				if ($row_count_insert > 0) {
					echo "true";
					$last_insert_id = $core->dbh->lastInsertId();
					pushSMS($row["ag"], $row["client_number"], $row["mess_message"], $last_insert_id);
				}
				
				
			} catch(PDOException $pe) {
				
				trigger_error('Could not connect to MySQL database. ' . $pe->getMessage() , E_USER_ERROR);
				
			}
		}
		
	}
?>