<?php

include_once 'logging.php';

class Database {
  // DB Params
  private $db_name;
  private $conn;

  public function __construct() {
    $this->db_name = $_SESSION['db_name'];
    $this->conn = null;
  }

 
  // DB Connect
  public function connect() {
    if (!$this->conn) {
      try {
        $this->conn = new PDO('sqlite:' . $this->db_name);
        $this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
        _log('Database Says: ' . $_SESSION['db_name'] . ' Connected');
      } catch(PDOException $e) {
        _log("Error!: " . $e->getMessage());
        print "Error!: " . $e->getMessage() . "<br/>";
      }
    } else {
      // Close the existing connection to the database
      $this->conn = null;
      _log('Database Says: ' . $_SESSION['db_name'] . ' Connection Closed');
      // Create a new connection to the database
      $this->conn = new PDO('sqlite:' . $this->db_name);
      $this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
      _log('Database Says: ' . $_SESSION['db_name'] . ' Connected');
    }
    return $this->conn;
  }
}

?>