<?php
/**
 * PDO singleton database connection.
 * Use db() to get the shared instance anywhere.
 */

declare(strict_types=1);

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

    public static function pdo(): PDO
    {
        if (self::$instance === null) {
            $host    = (string)env('DB_HOST', 'localhost');
            $name    = (string)env('DB_NAME');
            $user    = (string)env('DB_USER');
            $pass    = (string)env('DB_PASS', '');
            $charset = (string)env('DB_CHARSET', 'utf8mb4');

            $dsn = "mysql:host={$host};dbname={$name};charset={$charset}";
            $opts = [
                PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
                PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
                PDO::ATTR_EMULATE_PREPARES   => false,
                PDO::ATTR_STRINGIFY_FETCHES  => false,
                PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES {$charset} COLLATE {$charset}_unicode_ci",
            ];

            try {
                self::$instance = new PDO($dsn, $user, $pass, $opts);
            } catch (PDOException $e) {
                Logger::error('Database connection failed', ['error' => $e->getMessage()]);
                throw new RuntimeException('Database connection failed', 0, $e);
            }
        }
        return self::$instance;
    }

    private function __construct() {}
    private function __clone() {}
}

/** Convenience function */
function db(): PDO
{
    return DB::pdo();
}
