<?php
/*
 * jde, 08/08/17, updated to run as a class
 *
 * jde, Original coding,  August 09 as part of helpsys, taken from Chapman&Chapman book
 **/

require_once 'db.inc.php';

class History {

    function __construct( ) {
    }

	function addToHistory($term, $user, $history) {
//var_dump($term, $user, $history);
		$records = dbQuery("select term from histories where term='$term'");
		if (mysql_num_rows($records) == 0) // term not found, so insert it with new count of 0
			$result = dbQuery("insert into histories values('$user', '$term', 0)");
		else
			$result = dbQuery("update histories set n = n + 1 where term ='$term'");
		return $result;
	}

/*
	public function showRecentSearches( $user ) {
		$resultString = "";
		$history = $this->getHistoryList($user);
		if ( count($history) == 0 )
			$resultString = "User hasn't searched for any terms<br/>";
		else {
			$resultString = "<select id=\"term2\" name=\"term2\">";
			$resultString .= "<option label=\"Recent searches\" value=\"\" selected=\"selected\">Recent searches</option>";
			foreach ( $history as $h ) {
				$resultString .= "<option label=\"$h\" value=\"$h\">$h</option>";
			}
			$resultString .= "</select>";
		}
        return $resultString;
	}
*/
	
	function showRecentSearches($history) {
		if ($history == null) return "";
		$s = "<select id=\"term2\" name=\"term2\">";
		$s .= "<option label=\"Recent Searches\" value =\"\" selected=\"selected\">Recent Searches</option>";
		foreach ($history as $h)
			$s .= "<option label=\"$h\" value=\"$h\">$h</option>";
		$s .= "</select>";
		return $s;
	}

	public function getHistoryList( $user ) {
		$hist = [];
		$query = "select term from histories where user='$user' order by n";
		$records = dbQuery($query);
		$noRecords = (mysql_num_rows($records));
		if ( $noRecords != 0 ) {
			for ( $i = 0; $i < $noRecords; $i++ ) {
				$record =  mysql_fetch_array( $records );
				$hist[] = $record['term'];
			}
		}
		return $hist;
	}


}
