<?php

class AppDB {

   const TABLE_USERS = "users";
   const TABLE_COOKIES = "cookies";
   const TABLE_SETTINGS = "settings";
   const TABLE_ALBUMS = "albums";
   const TABLE_IMAGES = "images";
   const TABLE_LINKS = "links";

   const DBVERSION = "A000001";

   public static function getDBH() {
      $dbh = null;
      $dbh = new PDO("mysql:host=" . DBHOST . ";dbname=" . DBNAME, DBUSER, DBPASS);
      // Try to connect to the database
      try {
         if ( DBTYPE == "mysql" ) {
            $dbh = new PDO("mysql:host=" . DBHOST . ";dbname=" . DBNAME, DBUSER, DBPASS);
         } else if ( DBTYPE == "sqlite" ) {
            $dbh = new PDO("sqlite:" . SQLITEDB);
            $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            $dbh->exec("PRAGMA foreign_keys = ON");
         } else {
            throw new Exception("Bad database configuration in config file!");
         }
      } catch (PDOException | Exception $e) {
         //header('Location: error_db.php?connection=');
         echo "Couldn't connect to DB!";
         exit();
      }

      try {
         $query = "SELECT version FROM " . AppDB::TABLE_SETTINGS;
         $sth = $dbh->prepare($query);
         $sth->execute();
         $row = $sth->fetch(PDO::FETCH_ASSOC);
         if ( !is_array($row) ) throw new Exception("Table seems to be missing");
      } catch (PDOException | Exception $e) {
         header('Location: error_db.php?tables=');
         exit();
      }

      if ( !isset($row['version']) || ($row['version'] != AppDB::DBVERSION) ) {
         //header("Location: error_db.php?version=");
         exit();
      }
      return $dbh;
   }

}

// vim: set ts=3:sw=3
