<?php

declare(strict_types=1);

$candidates = array_filter([
    getenv('GTSIT_DB_ENV') ?: null,
    dirname(__DIR__) . '/.secrets/db.env',
    '/home/hosting_users/gts0201/.gtsit-db.env',
]);

$values = [];
foreach ($candidates as $candidate) {
    if (!is_readable($candidate)) {
        continue;
    }

    foreach (file($candidate, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) ?: [] as $line) {
        $line = trim($line);
        if ($line === '' || str_starts_with($line, '#') || !str_contains($line, '=')) {
            continue;
        }

        [$key, $value] = array_map('trim', explode('=', $line, 2));
        $values[$key] = trim($value, "\"'");
    }
    break;
}

return [
    'host' => $values['DB_HOST'] ?? 'localhost',
    'port' => (int) ($values['DB_PORT'] ?? 3306),
    'name' => $values['DB_NAME'] ?? '',
    'user' => $values['DB_USER'] ?? '',
    'password' => $values['DB_PASSWORD'] ?? '',
    'charset' => 'utf8mb4',
];
