<?php
declare(strict_types=1);

$envPath = __DIR__ . '/../.env';
if (is_file($envPath)) {
    foreach (parse_ini_file($envPath) as $k => $v) {
        putenv("$k=$v");
    }
}

$defaultExternalConfig = dirname(__DIR__, 3) . DIRECTORY_SEPARATOR . 'fleet-db.php';
$projectExternalConfig = dirname(__DIR__) . DIRECTORY_SEPARATOR . 'fleet-db.php';
$externalConfig = getenv('FLEET_DB_CONFIG') ?: (is_file($defaultExternalConfig) ? $defaultExternalConfig : (is_file($projectExternalConfig) ? $projectExternalConfig : ''));
$dbConfig = [];

if ($externalConfig !== '' && is_file($externalConfig)) {
    $dbConfig = require $externalConfig;
}

$host = $dbConfig['host'] ?? getenv('FLEET_DB_HOST');
$dbname = $dbConfig['database'] ?? getenv('FLEET_DB_NAME');
$username = $dbConfig['username'] ?? getenv('FLEET_DB_USER');
$password = $dbConfig['password'] ?? getenv('FLEET_DB_PASSWORD');
if ($host === 'localhost') { $host = '127.0.0.1'; }

if (!$host || !$dbname || !$username) {
    throw new RuntimeException('Database configuration is missing. Set FLEET_DB_CONFIG outside webroot or FLEET_DB_* environment variables.');
}

$dsn = "mysql:host={$host};dbname={$dbname};charset=utf8mb4";

$options = [
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
];

global $pdo;
$pdo = new PDO($dsn, $username, $password, $options);
