<?php

class Database
{
    private string $host = 'localhost';
    private string $database = 'pet_shop';
    private string $username = 'root';
    private string $password = '';

    /**
     * One request may instantiate many models. Reuse one PDO handle so those
     * models do not each open a separate MySQL connection.
     */
    private static ?PDO $connection = null;

    public function __construct()
    {
        $testDatabase = getenv('PET_SPA_TEST_DB');

        if (
            is_string($testDatabase)
            && preg_match('/^pet_shop_e2e_[a-z0-9_]+$/', $testDatabase)
        ) {
            $this->database = $testDatabase;
        }
    }

    public function databaseName(): string
    {
        return $this->database;
    }

    public function connect(): PDO
    {
        if (self::$connection === null) {

            try {

                $dsn = "mysql:host={$this->host};dbname={$this->database};charset=utf8mb4";

                self::$connection = new PDO(
                    $dsn,
                    $this->username,
                    $this->password
                );

                // Nếu SQL lỗi thì PDO sẽ báo exception
                self::$connection->setAttribute(
                    PDO::ATTR_ERRMODE,
                    PDO::ERRMODE_EXCEPTION
                );

                // Khi SELECT thì mặc định trả về associative array
                self::$connection->setAttribute(
                    PDO::ATTR_DEFAULT_FETCH_MODE,
                    PDO::FETCH_ASSOC
                );

                // Không giả lập prepared statement
                self::$connection->setAttribute(
                    PDO::ATTR_EMULATE_PREPARES,
                    false
                );

                $appTimezone =
                    $GLOBALS['config']['timezone']
                    ?? 'Asia/Ho_Chi_Minh';

                $timezoneOffset =
                    (new DateTimeImmutable(
                        'now',
                        new DateTimeZone($appTimezone)
                    ))->format('P');

                self::$connection->exec(
                    'SET time_zone = '
                    . self::$connection->quote($timezoneOffset)
                );

            } catch (PDOException $e) {

                die(
                    'Không thể kết nối cơ sở dữ liệu: '
                    . $e->getMessage()
                );
            }
        }

        return self::$connection;
    }
}
