<?PHP
	// definitions for Word_Test_Error class: word test error (only added no updates)
class Word_Test_Error {
	var $id;
	var $user_id;
	var $meaning_id;
	var $wrong_word_id;
	var $date_added;
	var $status;

	// constructor for Word_Test_Error (default language to English)
	function __construct ($user_id, $meaning_id, $wrong_word_id) {
		$this->id = "";
		$this->user_id = $user_id;
		$this->meaning_id = $meaning_id;
		$this->wrong_word_id = $wrong_word_id;
		$this->date_added = "";
		$this->status = "";
	}

	// use database row to set object's values
	function setValues ($row) {
		$this->id = $row['id'];
		$this->user_id = $row['user_id'];
		$this->meaning_id = $row['meaning_id'];
		$this->wrong_word_id = $row['wrong_word__id'];
		$this->date_added = $row['date_added'];
		$this->status = "read from db";
	}

	// create json string (allows this object to be created in JavaScript)
	function toJson () {
		$json = '{"type":"Word_Test_Error"';
		$json .= ',"id":"' . $this->id . '"';
		$json .= ',"user_id":"' . $this->user_id . '"';
		$json .= ',"meaning_id":"' . $this->meaning_id . '"';
		$json .= ',"wrong_word_id":"' . $this->wrong_word_id . '"';
		$json .= ',"date_added":"' . $this->date_added . '"';
		$json .= ',"status":"' . $this->status . '"';
		$json .= '}';
		return $json;
	}

	// uses id to retrieve from db
	function getById ($db_link) {

		$db_sql = "SELECT * FROM word_test_errors WHERE id = " . $this->id;
		$result = $db_link->connection->query($db_sql);
		if ( $result ) {
			$row = $result->fetch_array();
			if ($row) {
				$this->setValues($row);
				
			} else {
				$this->status = "Row not found on word_test_errors table with key: id=" . $this->id;
			}
		} else {
			$this->status = "MySql error: " . $db_link->connection->error;
		}
	}

	// store object on database, optionally refresh object from database (caters for database generated values)
	function store ($db_link, $refresh = true) {

		// check minimum info supplied
		if (empty($this->user_id) || empty($this->meaning_id) || empty($this->wrong_word_id)) {
			$this->status = "Insufficient key information supplied: user_id, meaning_id and wrong_word_id required";
			return; // skip out
		}

        // only insert rows (no update)
		$columns = "user_id";
		$values = $this->user_id;

		$columns .= ", meaning_id";
		$values .= ", " . $this->meaning_id;

		$columns .= ", wrong_word_id";
		$values .= ", " . $this->wrong_word_id;

		$db_sql = "INSERT INTO word_test_errors (" . $columns . ") VALUES(" . $values . ")";

        if($result = $db_link->connection->query($db_sql)){
			$this->id = $db_link->connection->insert_id;
			// reread from db to get all values (some can be populated on INSERT)
			$this->getById($db_link);
			$this->status = "New word test error added!";
		} else {
			$this->status = "Insert error: " . $db_sql . ", Db error: " . $db_link->connection->error;
	    }
	}
}

?>
