<?php
class ConnectionManager
{
	/**
	 * Cached Connection objects
	 * @type Array
	 */
	protected $cache = array();

	/**
	 * Project connections data
	 * @type Array
	 */
	protected $_connectionsData;

	/**
	 * Project connections data
	 * @type Array
	 */
	protected $_connectionsIdByName = array();

	
	/**
	 * An array storing the correspondence between project
	 * datasource tables names and connections ids
	 * @type Array
	 */	
	protected $_tablesConnectionIds;
	
	
	/**
	 * @constructor
	 */
	function __construct()
	{
		$this->_setConnectionsData();
		$this->_setTablesConnectionIds();
	}
	
	/**
	 * Get connection object by the table name
	 * @param String tName
	 * @return Connection
	 */
	public function byTable( $tName )
	{
		$connId = $this->_tablesConnectionIds[ $tName ];
		if( !$connId )
			return $this->getDefault();
		return $this->byId( $connId );
	}

	/**
	 * Get connection object by the connection name
	 * @param String connName
	 * @return Connection
	 */	
	public function byName( $connName )
	{
		$connId = $this->getIdByName( $connName );
		if( !$connId )
			return $this->getDefault();
		return $this->byId( $connId );
	}
	
	/**
	 * Get connection id by the connection name
	 * @param String connName
	 * @return String
	 */	
	protected function getIdByName( $connName )
	{
		return $this->_connectionsIdByName[ $connName ];
	}
	
	/**
	 * Get connection object by the connection id 
	 * @param String connId
	 * @return Connection
	 */	
	public function byId( $connId )
	{
		if( !isset( $this->cache[ $connId ] ) )
			$this->cache[ $connId ] = $this->getConnection( $connId );

		return $this->cache[ $connId ];
	}
	
	/**
	 * Get the default db connection class
	 * @return Connection
	 */
	public function getDefault()
	{
		return $this->byId( "test2_at_localhost" );
	}

	/**
	 * Get the users table db connection 
	 * @return Connection
	 */	
	public function getForLogin()
	{
		return $this->byId( "test2_at_localhost" );
	}
	
	/**
	 * Get the log table db connection 
	 * @return Connection
	 */	
	public function getForAudit()
	{
		return $this->byId( "test2_at_localhost" );
	}
	
	/**
	 * Get the locking table db connection 
	 * @return Connection
	 */		
	public function getForLocking()
	{
		return $this->getDefault();
	}	
	
	/**
	 * Get the 'ug_groups' table db connection 
	 * @return Connection
	 */	
	public function getForUserGroups()
	{
		return $this->getDefault();
	}		

	/**
	 * Get the saved searches table db connection 
	 * @return Connection
	 */	
	public function getForSavedSearches()
	{
		return $this->byId( "test2_at_localhost" );
	}

	/**
	 * Get the webreports tables db connection 
	 * @return Connection
	 */		
	public function getForWebReports()
	{
		return $this->getDefault();
	}
	
	/**
	 * @param String connId
	 * @return Connection
	 */
	protected function getConnection( $connId )
	{
		include_once getabspath("connections/Connection.php");
		
		$data = $this->_connectionsData[ $connId ];	
		switch( $data["connStringType"] )
		{
			case "mysql":
				if( useMySQLiLib() )
				{
					include_once getabspath("connections/MySQLiConnection.php");
					return new MySQLiConnection( $data );
				}
				
				include_once getabspath("connections/MySQLConnection.php");	
				return new MySQLConnection( $data );	

			case "mssql":
			case "compact":
				if( useMSSQLWinConnect() )
				{
					include_once getabspath("connections/MSSQLWinConnection.php");
					return new MSSQLWinConnection( $data );
				}
				if( isSqlsrvExtLoaded() )
				{
					include_once getabspath("connections/MSSQLSrvConnection.php");	
					return new MSSQLSrvConnection( $data );
				}
				
				if( function_exists("mssql_connect") ) {
					include_once getabspath("connections/MSSQLUnixConnection.php");
					return new MSSQLUnixConnection( $data );			
				}

				if( class_exists("PDO") ) {
					include_once getabspath("connections/PDOConnection.php");
					$drivers = pdo_drivers();
					if( in_array( "sqlsrv", $drivers) )
					{
						$data["PDOString"] = "sqlsrv:Server=" . $data["connInfo"][0] . ";Database=" . $data["connInfo"][3];
						$data["PDOUser"] = $data["connInfo"][1];
						$data["PDOPass"] = $data["connInfo"][2];
						return new PDOConnection( $data );			
					}
					if( in_array( "dblib", $drivers) )
					{
						$data["PDOString"] = "dblib:host=" . $data["connInfo"][0] . ";dbname=" . $data["connInfo"][3];
						$data["PDOUser"] = $data["connInfo"][1];
						$data["PDOPass"] = $data["connInfo"][2];
						return new PDOConnection( $data );			
					}
				}
				echo "No SQL Server driver found in your PHP settings.";
				if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
					echo "<br>To enable SQL Server support add the following line to php.ini file:";
					echo "<br>extension=php_com_dotnet.dll";
				}
				exit();

			case "msaccess":
			case "odbc":
			case "odbcdsn":
			case "custom":
			case "file":
				if( stripos($data["ODBCString"], 'Provider=') !== false )
				{
					include_once getabspath("connections/ADOConnection.php");
					return new ADOConnection( $data );
				}
				
				include_once getabspath("connections/ODBCConnection.php");
				return new ODBCConnection( $data );
			
			case "oracle":
				include_once getabspath("connections/OracleConnection.php");
				return new OracleConnection( $data );

			case "postgre":
				include_once getabspath("connections/PostgreConnection.php");
				return new PostgreConnection( $data );

			case "db2":
				include_once getabspath("connections/DB2Connection.php");
				return new DB2Connection( $data );

			case "informix":
				include_once getabspath("connections/InformixConnection.php");
				return new InformixConnection( $data );

			case "sqlite":
				include_once getabspath("connections/SQLite3Connection.php");
				return new SQLite3Connection( $data );
			case "pdo":
				include_once getabspath("connections/PDOConnection.php");
				return new PDOConnection( $data );
		}
	}

	public function getConectionsIds()
	{
		$connectionsIds = array();
		foreach ($this->_connectionsData as $connId => $data) {
			$connectionsIds[] = $connId;
		}

		return $connectionsIds;
	}

	/**
	 * Set the data representing the project's 
	 * db connection properties
	 */	 
	protected function _setConnectionsData()
	{
		// content of this function can be modified on demo account
		// variable names $data and $connectionsData are important

		$connectionsData = array();
		
		$data = array();
		$data["dbType"] = 0;
		$data["connId"] = "test2_at_localhost";
		$data["connName"] = "tharanga at localhost";
		$data["connStringType"] = "mysql";
		$data["connectionString"] = "mysql;localhost;root;;;tharanga;;1"; //currently unused

		$this->_connectionsIdByName["tharanga at localhost"] = "test2_at_localhost";
		
		$data["connInfo"] = array();
		$data["ODBCUID"] = "root";
		$data["ODBCPWD"] = "";
		$data["leftWrap"] = "`";
		$data["rightWrap"] = "`";
		
		$data["DBPath"] = "db"; //currently unused	
		$data["useServerMapPath"] = 1; //currently unused
		
$host="localhost";
$user="ebizsoco_samagi";
$pwd="82311645288asd";
$port="3306";
$sys_dbname="ebizsoco_newsamagi2";
$data["connInfo"][0] = $host;
$data["connInfo"][1] = $user;
$data["connInfo"][2] = $pwd;
$data["connInfo"][3] = $port;
$data["connInfo"][4] = $sys_dbname;
;
		// encription set
		$data["EncryptInfo"] = array();
		$data["EncryptInfo"]["mode"] = 0;
		$data["EncryptInfo"]["alg"]  = 128;
		$data["EncryptInfo"]["key"]  = "";

		$connectionsData["test2_at_localhost"] = $data;
		$this->_connectionsData = &$connectionsData;
	}
	
	/**
	 * Set the data representing the correspondence between 
	 * the project's table names and db connections
	 */	 
	protected function _setTablesConnectionIds()
	{
		$connectionsIds = array();
		$connectionsIds["sales"] = "test2_at_localhost";
		$connectionsIds["sales_details"] = "test2_at_localhost";
		$connectionsIds["product"] = "test2_at_localhost";
		$connectionsIds["customer"] = "test2_at_localhost";
		$connectionsIds["category"] = "test2_at_localhost";
		$connectionsIds["brand"] = "test2_at_localhost";
		$connectionsIds["units"] = "test2_at_localhost";
		$connectionsIds["sys_manage"] = "test2_at_localhost";
		$connectionsIds["company_profile"] = "test2_at_localhost";
		$connectionsIds["details"] = "test2_at_localhost";
		$connectionsIds["seasonal discounts"] = "test2_at_localhost";
		$connectionsIds["special_discount"] = "test2_at_localhost";
		$connectionsIds["product1"] = "test2_at_localhost";
		$connectionsIds["Users"] = "test2_at_localhost";
		$connectionsIds["payments"] = "test2_at_localhost";
		$connectionsIds["credit_sales"] = "test2_at_localhost";
		$connectionsIds["purchasing"] = "test2_at_localhost";
		$connectionsIds["purchasing_details"] = "test2_at_localhost";
		$connectionsIds["product_purchasing"] = "test2_at_localhost";
		$connectionsIds["customer1"] = "test2_at_localhost";
		$connectionsIds["Advance_purchasing"] = "test2_at_localhost";
		$connectionsIds["payment_for_pur"] = "test2_at_localhost";
		$connectionsIds["Payment of arrears"] = "test2_at_localhost";
		$connectionsIds["Advance_purchasing2"] = "test2_at_localhost";
		$connectionsIds["attendance"] = "test2_at_localhost";
		$connectionsIds["attendance_master"] = "test2_at_localhost";
		$connectionsIds["salary_voucher"] = "test2_at_localhost";
		$connectionsIds["salary_advance"] = "test2_at_localhost";
		$connectionsIds["payment_of_loan_installments"] = "test2_at_localhost";
		$connectionsIds["salaries_and_allowances"] = "test2_at_localhost";
		$connectionsIds["attendance Report"] = "test2_at_localhost";
		$connectionsIds["attendance11"] = "test2_at_localhost";
		$connectionsIds["loans."] = "test2_at_localhost";
		$connectionsIds["salary_list"] = "test2_at_localhost";
		$connectionsIds["salary_summary"] = "test2_at_localhost";
		$connectionsIds["salary_slips"] = "test2_at_localhost";
		$connectionsIds["loans"] = "test2_at_localhost";
		$connectionsIds["loa_types"] = "test2_at_localhost";
		$connectionsIds["loa_types1"] = "test2_at_localhost";
		$connectionsIds["bank_accounts"] = "test2_at_localhost";
		$connectionsIds["bank_activity"] = "test2_at_localhost";
		$connectionsIds["Acc 1 Chart"] = "test2_at_localhost";
		$connectionsIds["Acc 2 Chart"] = "test2_at_localhost";
		$connectionsIds["Acc 3 Chart"] = "test2_at_localhost";
		$connectionsIds["Acc 4 Chart"] = "test2_at_localhost";
		$connectionsIds["Acc 5 Chart"] = "test2_at_localhost";
		$connectionsIds["Acc 6 Chart"] = "test2_at_localhost";
		$connectionsIds["Account - 1"] = "test2_at_localhost";
		$connectionsIds["All Acc's Chart"] = "test2_at_localhost";
		$connectionsIds["Account - 2"] = "test2_at_localhost";
		$connectionsIds["Account - 3"] = "test2_at_localhost";
		$connectionsIds["Account - 4"] = "test2_at_localhost";
		$connectionsIds["Account - 5"] = "test2_at_localhost";
		$connectionsIds["Account - 6"] = "test2_at_localhost";
		$connectionsIds["Resultant Account"] = "test2_at_localhost";
		$connectionsIds["loans status"] = "test2_at_localhost";
		$connectionsIds["expens"] = "test2_at_localhost";
		$connectionsIds["expense_category"] = "test2_at_localhost";
		$connectionsIds["expenditure_data"] = "test2_at_localhost";
		$connectionsIds["cheque_register"] = "test2_at_localhost";
		$connectionsIds["cheque_register_m"] = "test2_at_localhost";
		$connectionsIds["buyers"] = "test2_at_localhost";
		$connectionsIds["cheque_register4pay"] = "test2_at_localhost";
		$connectionsIds["stock_transfer"] = "test2_at_localhost";
		$connectionsIds["stock_tracnsfers"] = "test2_at_localhost";
		$connectionsIds["stock_transfer - receiving"] = "test2_at_localhost";
		$connectionsIds["stock receiving"] = "test2_at_localhost";
		$connectionsIds["stk_tra_dat_4_recev"] = "test2_at_localhost";
		$connectionsIds["expen_source"] = "test2_at_localhost";
		$connectionsIds["expen_detail"] = "test2_at_localhost";
		$connectionsIds["daily_report"] = "test2_at_localhost";
		$connectionsIds["purchasing_summary"] = "test2_at_localhost";
		$connectionsIds["purchasing data"] = "test2_at_localhost";
		$connectionsIds["sales_detail"] = "test2_at_localhost";
		$connectionsIds["purchasing_Control"] = "test2_at_localhost";
		$connectionsIds["sales Bill"] = "test2_at_localhost";
		$connectionsIds["sales_details.."] = "test2_at_localhost";
		$connectionsIds["Payment for purchasing"] = "test2_at_localhost";
		$connectionsIds["buyers_advance"] = "test2_at_localhost";
		$connectionsIds["buyers1advance"] = "test2_at_localhost";
		$connectionsIds["advances_to_supplier"] = "test2_at_localhost";
		$connectionsIds["advances_to_supplier1"] = "test2_at_localhost";
		$connectionsIds["supplier_advance_cut"] = "test2_at_localhost";
		$connectionsIds["advances_to_supplier_status"] = "test2_at_localhost";
		$connectionsIds["Payment in advance"] = "test2_at_localhost";
		$connectionsIds["opening_balance"] = "test2_at_localhost";
		$connectionsIds["opening_balance_details"] = "test2_at_localhost";
		$connectionsIds["recovery of arrears"] = "test2_at_localhost";
		$connectionsIds["credit_sales11"] = "test2_at_localhost";
		$connectionsIds["buyers advance"] = "test2_at_localhost";
		$connectionsIds["payment_Report_admin"] = "test2_at_localhost";
		$connectionsIds["quick_purchasing"] = "test2_at_localhost";
		$connectionsIds["purchasing_details1"] = "test2_at_localhost";
		$connectionsIds["Payment_r_4_xprinter"] = "test2_at_localhost";
		$connectionsIds["stock_balance"] = "test2_at_localhost";
		$connectionsIds["daily_reportS"] = "test2_at_localhost";
		$connectionsIds["purchasing_details Report"] = "test2_at_localhost";
		$connectionsIds["daily_report - 1"] = "test2_at_localhost";
		$connectionsIds["daily_report -2"] = "test2_at_localhost";
		$connectionsIds["daily_report - 3"] = "test2_at_localhost";
		$connectionsIds["sales_history"] = "test2_at_localhost";
		$connectionsIds["sales_history_total"] = "test2_at_localhost";
		$connectionsIds["Purchasing List"] = "test2_at_localhost";
		$connectionsIds["purchasing_list2"] = "test2_at_localhost";
		$connectionsIds["new_start6_audit"] = "test2_at_localhost";
		$connectionsIds["new_start6_locking"] = "test2_at_localhost";
		$connectionsIds["new_start8_settings"] = "test2_at_localhost";
		$connectionsIds["theme_list"] = "test2_at_localhost";
		$connectionsIds["Profile"] = "test2_at_localhost";
		$connectionsIds["daily_report - 4"] = "test2_at_localhost";
		$this->_tablesConnectionIds = &$connectionsIds;
	}
	
	/**
	 * Check if It's possible to add to one table's sql query 
	 * an sql subquery to another table.
	 * Access doesn't support subqueries from the same table as main.
	 * @param String dataSourceTName1
	 * @param String dataSourceTName2
	 * @return Boolean
	 */
	public function checkTablesSubqueriesSupport( $dataSourceTName1, $dataSourceTName2 )
	{
		$connId1 = $this->_tablesConnectionIds[ $dataSourceTName1 ];
		$connId2 = $this->_tablesConnectionIds[ $dataSourceTName2 ];
		
		if( $connId1 != $connId2 )
			return false;

		if( $this->_connectionsData[ $connId1 ]["dbType"] == nDATABASE_Access && $dataSourceTName1 == $dataSourceTName2 )
			return false;
			
		return true;	
	}
	
	/**
	 * Close db connections
	 * @destructor
	 */
	function __desctruct() 
	{
		foreach( $this->cache as $connection )
		{
			$connection->close();
		}
	}
}
?>