<?php

/**
 * env() — Environment Variable Helper
 *
 * Reads a value from $_ENV with optional type casting and a safe default fallback.
 * $_ENV is populated by Bootstrap (INIT-003) which parses the .env file.
 *
 * This function is a pure global utility — no class, no instantiation.
 * It is always loaded before any config file that calls it.
 *
 * Type coercion rules:
 *   "true"  / "(true)"  → (bool) true
 *   "false" / "(false)" → (bool) false
 *   "null"  / "(null)"  → null
 *   "empty" / "(empty)" → (string) ""
 *   Numeric string      → (int) or (float)
 *   Quoted string       → string with quotes stripped
 *   ""  (empty string)  → $default
 *   Key not set         → $default
 *
 * @package Inveetaire
 * @ref     DBP v1.0 Ch.4, Ch.10, INIT-005
 */

if (!function_exists('env')) {

    /**
     * Retrieve a typed value from the environment.
     *
     * @param string $key     The environment variable name (e.g. 'APP_DEBUG').
     * @param mixed  $default Fallback value when the key is absent or empty.
     *
     * @return mixed
     */
    function env(string $key, $default = null)
    {
        // Key not present in $_ENV — return default immediately.
        // Uses array_key_exists so a key explicitly set to null is still found.
        if (!array_key_exists($key, $_ENV)) {
            return $default;
        }

        $value = $_ENV[$key];

        // Empty string — treat as "not configured", return default.
        if ($value === '') {
            return $default;
        }

        // Cast well-known string representations to their typed equivalents.
        switch (strtolower(trim((string) $value))) {
            case 'true':
            case '(true)':
                return true;

            case 'false':
            case '(false)':
                return false;

            case 'null':
            case '(null)':
                return null;

            case 'empty':
            case '(empty)':
                return '';
        }

        // Strip surrounding double or single quotes.
        // Handles values like: APP_NAME="Inveetaire" or APP_KEY='secret'
        if (is_string($value) && strlen($value) > 1) {
            $first = $value[0];
            $last  = $value[strlen($value) - 1];

            if (($first === '"' && $last === '"') || ($first === "'" && $last === "'")) {
                return substr($value, 1, -1);
            }
        }

        // Cast numeric strings to the appropriate PHP type.
        // Avoids "0123" being cast (leading zero = not a standard integer).
        if (is_numeric($value) && !preg_match('/^0\d/', $value)) {
            return strpos($value, '.') !== false
                ? (float) $value
                : (int) $value;
        }

        return $value;
    }

}
