<?

require_once ('DBConfig.php');
require_once ('Logger.php');

class DB
{
  protected static $logger;
  protected static $conn;


  /**
   * Constructor function
   *
   */
  public function __construct($servername = null, $username = null, $password = null, $database = null, $port = null, $charset = 'utf8', $characterset = 'UTF-8')
  {
    // if params were passed as array
    if (is_array($servername)) {
        foreach ($servername as $key => $val) {
            $$key = $val;
        }
    } else if (is_null($servername)) {
      return;
    }

    try {
      /*
      $this::$db = new PDO("sqlsrv:server=$servername;Database=$database;ConnectionPooling=0", $username, $password,
        array(
            PDO::ATTR_PERSISTENT => true,
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
        )
      );


            $this::$db = new PDO( "sqlsrv:server=$servername;Database=$database;ConnectionPooling=0", $username, $password);
            $this::$db->setAttribute( PDO::ATTR_PERSISTENT, true );
            $this::$db->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
      */
      $server = $servername;
      $connectionInfo = array( "Database"=>$database, "UID"=>$username, "PWD"=>$password, );
      $this::$conn = sqlsrv_connect( $server, $connectionInfo );

      $this::$logger = Logger::getInstance($_SERVER['PHP_SELF']);
    } catch (Exception $e) {
      echo ("Error connecting to SQL Server: " . $e->getMessage());
    }
  }

  public function getInstance()
  {
    if ($this::$conn===null) new DB(DBConfig::getInstance());
    return $this::$conn;
  }

}
