<?php
/**
 * Helper Function Library
 *
 * @version     1.0.$Revision:$
 * @version     SVN: $Id:$
 * @package     bplan-base/globals
 * @subpackage  Libraries
 * @author      Emilio Cannarozzo <emilio.cannarozzo@bplan-solutions.de>
 * @author      Wassilios Meletiadis <wassilios.meletiadis@bplan-solutions.de>
 * @copyright   Copyright (C) 2025, 2026 bplan-solutions GmbH & Co. KG <https://www.bplan-solutions.de/>
 * /Δ\
 */


use BplanBase\Globals\Env\EnvCrypt;
use BplanBase\Globals\Env\EnvFile;
use Illuminate\Support\Str;


if (!function_exists('decrypt_env')) {

    /**
     *
     * @param       string $key
     *
     * @param       mixed $default
     *
     * @return      mixed
     *
     * @version     1.1.0 / 2026-04-26
     * @author      Emilio Cannarozzo <emilio.cannarozzo@bplan-solutions.de>
     * @author      Wassilios Meletiadis <wassilios.meletiadis@bplan-solutions.de>
     */
    function decrypt_env(string $key, mixed $default = null)
    {
        $value = env($key, $default);

        if ($value === null || $value === '') {
            return $default;
        }
        if (Str::startsWith($value, '*')) {
            $plainPassword = ltrim($value, '*');
            /*
            **  Verschlüsseln und aktualisieren. */
            EnvFile::load(base_path('.env'))
                ->set($key, '"'.EnvCrypt::encrypt($plainPassword).'"')
                ->save();

            return $plainPassword;
        }
        return EnvCrypt::decrypt($value, $default);

    } // decrypt_env()
}


if (!function_exists('env_to_array')) {

    /**
     *
     * @param       string $key
     *
     * @param       string $values
     *
     * @param       string $separator
     *
     * @version     1.0.0 / 2025-08-24
     * @author      Emilio Cannarozzo <emilio.cannarozzo@bplan-solutions.de>
     * @author      Wassilios Meletiadis <wassilios.meletiadis@bplan-solutions.de>
     */
    function env_to_array(string $key, string $separator = ',')
    {
        $values = env($key, null);

        if ($values === null || trim($values) === '') {
            return [];
        }
        $values = explode($separator, trim($values));

        return array_map(function ($value) {
            return trim($value);

        }, $values);

    } // env_to_array()
}
