<?php
declare(strict_types=1);

$databaseConfig = [
    'host' => getenv('BULO_DB_HOST') ?: '127.0.0.1',
    'name' => getenv('BULO_DB_NAME') ?: 'bulo',
    'user' => getenv('BULO_DB_USER') ?: 'root',
    'pass' => getenv('BULO_DB_PASS') ?: '',
    'charset' => getenv('BULO_DB_CHARSET') ?: 'utf8mb4',
];

$localDatabaseConfig = __DIR__ . '/database.local.php';
if (is_file($localDatabaseConfig)) {
    $loadedDatabaseConfig = require $localDatabaseConfig;
    if (is_array($loadedDatabaseConfig)) {
        $databaseConfig = array_replace($databaseConfig, $loadedDatabaseConfig);
    }
}

define('DB_HOST', (string) $databaseConfig['host']);
define('DB_NAME', (string) $databaseConfig['name']);
define('DB_USER', (string) $databaseConfig['user']);
define('DB_PASS', (string) $databaseConfig['pass']);
define('DB_CHARSET', (string) $databaseConfig['charset']);

function db(): PDO
{
    static $pdo = null;

    if ($pdo instanceof PDO) {
        return $pdo;
    }

    $dsn = 'mysql:host=' . DB_HOST . ';dbname=' . DB_NAME . ';charset=' . DB_CHARSET;
    $pdo = 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,
    ]);

    return $pdo;
}
