<?php

namespace App\Config;

use PDO;
use PDOException;
use App\Utils\Env;

class Database {
    private static $instance = null;
    private $connection;

    private function __construct() {
        $host = Env::get('DB_HOST', 'localhost');
        $db   = Env::get('DB_NAME', 'messrypt_nons');
        $user = Env::get('DB_USER', 'roomessrypt_nonst');
        $pass = Env::get('DB_PASS', 'messrypt_nons');
        $charset = 'utf8mb4';

        $dsn = "mysql:host=$host;dbname=$db;charset=$charset";
        $options = [
            PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
            PDO::ATTR_EMULATE_PREPARES   => false,
            PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8mb4 COLLATE utf8mb4_unicode_ci; SET time_zone = '+03:00';"
        ];

        try {
            $this->connection = new PDO($dsn, $user, $pass, $options);
        } catch (\PDOException $e) {
            throw new \PDOException($e->getMessage(), (int)$e->getCode());
        }
    }

    public static function getInstance() {
        if (self::$instance == null) {
            self::$instance = new Database();
        }
        return self::$instance;
    }

    public function getConnection() {
        return $this->connection;
    }
}
