<?php

namespace lib\Database;

use lib\Database\QueryBuilder;
use PDO;

class DB
{
  private static ?PDO $pdo = null;

  public static function init(): void {}

  public static function getPDO(): PDO
  {
    if (self::$pdo === null) {
      $driver  = $_ENV['DATABASE_DRIVER'] ?? $_SERVER['DATABASE_DRIVER'] ?? 'mysql';
      $host    = $_ENV['DATABASE_HOST'] ?? $_SERVER['DATABASE_HOST'] ?? 'localhost';
      $dbname  = $_ENV['DATABASE_DB'] ?? $_SERVER['DATABASE_DB'] ?? 'test';
      $charset = $_ENV['DATABASE_CHARSET'] ?? $_SERVER['DATABASE_CHARSET'] ?? 'utf8';
      $user    = $_ENV['DATABASE_ID'] ?? $_SERVER['DATABASE_ID'] ?? 'root';
      $pass    = $_ENV['DATABASE_PASSWORD'] ?? $_SERVER['DATABASE_PASSWORD'] ?? '';
      $dsn     = sprintf("%s:host=%s;dbname=%s;charset=%s", $driver, $host, $dbname, $charset);
      self::$pdo = new \PDO($dsn, $user, $pass);
      self::$pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
    }
    return self::$pdo;
  }
}
