<?
require_once "interface.Address_Book.php";

class Address_Book_DB implements Address_Book {
	const INSERT_ENTRY = 'INSERT INTO data (name, tel, mail)
	 		      VALUES(:name, :tel, :mail)';
	const SELECT_ENTRY = 'SELECT name AS NAME, tel AS TEL, mail AS MAIL
			      FROM data WHERE name LIKE :name
			      	           OR tel LIKE :tel
					   OR mail LIKE :mail';
		

	private $dbh;

	public function __construct($dsn, $user = null, $pass = null) {
		$this->dbh = new PDO($dsn, $user, $pass,
		array( PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));

		$this->dbh->exec("CREATE TABLE IF NOT EXISTS data
			(name TEXT, tel TEXT, mail TEXT)");

		$this->dbh->beginTransaction();

		$sth = $this->dbh->prepare("SELECT COUNT(*) AS COUNT FROM data");
		$sth->execute();
		$r = $sth->fetch();

		if ($r['COUNT'] == 0) 
			$this->insert(array("Hans Hanson", "0815", "hans@hanson.de"));
		$this->dbh->commit();
	}

	private function insert($entry) {
		static $sth = null;

		if ($sth === null)
			$sth = $this->dbh->prepare(self::INSERT_ENTRY);
		
		$sth->execute(array("name" => $entry[0],
				    "tel"  => $entry[1],
				    "mail" => $entry[2]));
	}
			
	public function get_all_entries() {
		$entries = array();
		fseek($this->fh, 0, SEEK_SET);
		while($line = stream_get_line($this->fh, 0, self::RS)) {
			if ($line === FALSE) break;
			$entries[] = explode(self::FS, $line);
		}
		return $entries;
	}

	public function add_entry($entry) {
		$fields = array('name', 'tel', 'mail');
		$new = array();
		foreach($fields as $key) {
			if (!isset($entry[$key])) return;
			$new[$key] = $entry[$key];
			trim($new[$key]);
			preg_replace('/['.self::RS.self::FS.' ]+/', ' ', $new[$key]);
			if (empty($new[$key])) return;
		}

		flock($this->fh, LOCK_EX);
		fputs($this->fh, join(self::FS, $new) . self::RS);
		flock($this->fh, LOCK_UN);
		header("Location: $_SERVER[PHP_SELF]?action=add");
		exit;
	}

	public function search_entries($pattern) {
		static $sth = null;

		if ($sth === null)
			$sth = $this->dbh->prepare(self::SELECT_ENTRY);

		$pattern = trim($pattern);
		if (empty($pattern)) return;

		$pattern = trim($pattern, '%');
		$pattern = "%$pattern%";

		$sth->execute(array("name" => $pattern,
				    "tel" => $pattern,
				    "mail" => $pattern));
		$entries = array();
		while ($r = $sth->fetch()) {
			$entries[] = array('name' => $r['NAME'],
					   'tel' => $r['TEL'],
					   'mail' => $r['MAIL']);
		}
		return $entries;
	}

	public function delete_entries($ids) { }
}

?>
