<?php
declare(strict_types=1);

namespace App\Core;

use PDO;
use RuntimeException;

class Database
{
    private static ?PDO $connection = null;

    public static function connection(?array $config = null): PDO
    {
        if (self::$connection instanceof PDO) {
            return self::$connection;
        }

        $config ??= $GLOBALS['zalorox_config'] ?? [];
        $db = $config['db'] ?? [];

        if (!extension_loaded('pdo_mysql')) {
            throw new RuntimeException('pdo_mysql extension is required.');
        }

        $charset = $db['charset'] ?? 'utf8mb4';
        $dsn = sprintf(
            'mysql:host=%s;port=%d;dbname=%s;charset=%s',
            $db['host'] ?? '127.0.0.1',
            (int) ($db['port'] ?? 3306),
            $db['name'] ?? '',
            $charset
        );

        self::$connection = new PDO($dsn, $db['user'] ?? '', $db['pass'] ?? '', [
            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 {$charset} COLLATE {$charset}_unicode_ci",
        ]);

        return self::$connection;
    }

    public static function pdo(array $config): PDO
    {
        return self::connection($config);
    }
}
