<?php
/**
 * Transalation class
 * @todo: on hold. Shall we use a Translation table ?
 * Based on Transladb Francisco Presencia Fandos
 * @Requires  PHP 5.3+
 * @use: $_ = new Translation();
 */
class Translation {
	// This stores the language of the translations. Format: "en", "es", "fr", etc
	private $language;
	// This will add a new translation if the keyword is not in the database yet. Dissable in production (recommended)
	private $autoAdd;
  
	public function __construct ( $language = "en", $autoAdd = 1 ){
		$this->language		= $language;
		$this->autoAdd		= $autoAdd;
    }

	// Requires PHP 5.3+. Simplifies the calling method to echo $_('keyword');
	public function __invoke($key){
		// $id = substr($key, 0, 200);		// A reasonable limit for the keyword. It'll work even if it's longer..
		$hash = md5( $key );
		
		// If there's no text string yet
		
		
		/*
		if (!($text == $this->retrieve($id)) && $this->autoAdd){
			// Add the string dynamically to database so it doesn't break the coding flow.
			$text = $this->add($Id, $Key);
		}
		*/
		
		$text = $this->retrieve( $hash );
		return $text;
    }

	// Adds to database a new translation row in English. This method is disabled in production (and can be deleted).
	private function add ($Id, $Text){
		// Ignore not to overwrite the old translations.
		$STH = $this->DB->prepare("INSERT IGNORE INTO translations (keyword, en) VALUES (?, ?)");
		$STH->execute(array($Id, $Text));
		return $Text;
	}
	
	// It returns the right cell, however it might be empty.
	private function retrieve ( $hash ){
		$con = new Connection();
		$sql = "SELECT translation FROM translations WHERE hash='$hash' LIMIT 1";
		$rv = $con->execute( $sql );
		
		unset( $con );
		return $rv;
	}
}
?>
