<?php

/**
 * Load the environment variables from the .env file.
 */
function env_load($filePath)
{
    if (!file_exists($filePath)) throw new Exception("The .env file does not exist. (el)");

    $lines = file($filePath, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
    foreach ($lines as $line) {
        $line = trim($line);

        // Skip lines that are empty after trimming or are comments
        if ($line === '' || str_starts_with($line, '#')) continue;

		// Skip lines without an '=' character
        if (strpos($line, '=') === false) continue;

        [$name, $value] = explode('=', $line, 2);

        $name = trim($name);
        $value = trim($value, " \t\n\r\0\x0B\"'"); // Trim whitespace and quotes

        if (!array_key_exists($name, $_SERVER) && !array_key_exists($name, $_ENV)) {
            putenv("$name=$value");
            $_ENV[$name] = $value;
            $_SERVER[$name] = $value;
        }
    }
}


/**
 * Retrieve an environment variable.
 */
function env($key, $default = null)
{
	$v = $_ENV[$key] ?? $_SERVER[$key] ?? (getenv($key) ?: $default);
	return match(true) {
		$v === 'true'  => true,
		$v === 'false' => false,
		is_numeric($v) => (int) $v,
		is_float($v)   => (float) $v,
		default        => $v
	};
}
