<?php
declare(strict_types=1);

function env_bool(string $key, bool $default = false): bool
{
    $value = getenv($key);
    if ($value === false) {
        return $default;
    }

    $value = strtolower(trim((string)$value));
    if ($value === '') {
        return $default;
    }

    return in_array($value, ['1', 'true', 'on', 'yes'], true);
}

function db_connection_settings(): array
{
    return [
        'server' => getenv('DB_SERVER') ?: '(local)',
        'options' => [
            'Database' => getenv('DB_NAME') ?: 'HanaSoftDatabase',
            'UID' => getenv('DB_USER') ?: 'sa',
            'PWD' => getenv('DB_PASSWORD') ?: 'Banthan123@',
            'CharacterSet' => 'UTF-8',
            'LoginTimeout' => (int)(getenv('DB_LOGIN_TIMEOUT') ?: 5),
            'ReturnDatesAsStrings' => true,
            'Encrypt' => env_bool('DB_ENCRYPT', false),
            'TrustServerCertificate' => env_bool('DB_TRUST_SERVER_CERT', true),
        ],
    ];
}

function db_connect()
{
    $settings = db_connection_settings();
    $connection = sqlsrv_connect($settings['server'], $settings['options']);

    if ($connection === false) {
        $errors = sqlsrv_errors(SQLSRV_ERR_ERRORS);
        $details = [];

        if (is_array($errors)) {
            foreach ($errors as $error) {
                $code = $error['code'] ?? '';
                $message = $error['message'] ?? '';
                $details[] = trim(($code ? $code . ': ' : '') . $message);
            }
        }

        $detailsMessage = $details ? ' Details: ' . implode(' | ', $details) : '';
        throw new RuntimeException('SQL Server connection failed.' . $detailsMessage);
    }

    return $connection;
}

function db_disconnect($connection): void
{
    if (is_resource($connection)) {
        sqlsrv_close($connection);
    }
}
