<?php
ApplicationSettings::RegisterDefaultSetting("database", "host", "localhost");
ApplicationSettings::RegisterDefaultSetting("database", "database", "php-mvc");
ApplicationSettings::RegisterDefaultSetting("database", "username", "root");
ApplicationSettings::RegisterDefaultSetting("database", "password", "");

class BaseRepository {
	protected static $PDO=null;

	protected static function SetupPDO(){
		if (self::$PDO!=null)
			return;
		$host=ApplicationSettings::GetSetting("database", "host");
		$db=ApplicationSettings::GetSetting("database", "database");
		$username=ApplicationSettings::GetSetting("database", "username");
		$password=ApplicationSettings::GetSetting("database", "password");
		self::$PDO=new PDO("mysql:host=$host;dbname=$db",$username,$password);
		self::$PDO->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE,PDO::FETCH_ASSOC);
	}
	
	public static function GetPDO(){
		self::SetupPDO();
		return self::$PDO;
	}
	
	public function __construct() {
		self::SetupPDO();
	}
	
	protected function DoBasicSelectQuery($table, $field, array $keyValuePair=null){
		$sql="SELECT `$field` FROM `$table`";
		$execData=array();
		
		if ($keyValuePair!=null && count($keyValuePair)>0){
			$sql.=" WHERE ";
			foreach ($keyValuePair as $key=>$value){
				$sql.="$key=:$key";
				$execData[":$key"]=$value;
			}
		}
		
		self::SetupPDO();
		$prep=self::$PDO->prepare($sql);
		$prep->execute($execData);
		return $prep->fetchAll(PDO::FETCH_COLUMN);
	}
}
