<?php
/**
 * Concord CRM - https://www.concordcrm.com
 *
 * @version   1.4.1
 *
 * @link      Releases - https://www.concordcrm.com/releases
 * @link      Terms Of Service - https://www.concordcrm.com/terms
 *
 * @copyright Copyright (c) 2022-2024 KONKORD DIGITAL
 */

namespace App\Installer;

use Exception;

class EnvironmentManager
{
    protected string $envFilePath;

    /**
     * Initialize new EnvironmentManager instance.
     */
    public function __construct(?string $envFilePath = null)
    {
        $this->envFilePath = $envFilePath ?: app()->environmentFilePath();
    }

    /**
     * Save the form content to the .env file.
     */
    public function saveEnvFile(Environment $env): bool
    {
        $contents = '# Read more about editing the environment file: https://www.concordcrm.com/docs/config#edit-env-file'."\n\n";

        $contents .= 'APP_NAME=\''.$env->getName()."'\n".
        '# DO NOT EDIT THE APPLICATION KEY'."\n".
        'APP_KEY='.$env->getKey()."\n".
        'IDENTIFICATION_KEY='.$env->getIdentificationKey()."\n".
        'APP_URL='.$env->getUrl()."\n".
        '#APP_DEBUG=true'."\n\n".
        'DB_CONNECTION=mysql'."\n".
        'DB_HOST='.$env->getDbHost()."\n".
        'DB_PORT='.$env->getDbPort()."\n".
        'DB_DATABASE='.$env->getDbName()."\n".
        'DB_USERNAME='.$env->getDbUser()."\n".
        'DB_PASSWORD=\''.$env->getDbPassword()."'\n\n".
        'MAIL_MAILER=array'."\n";

        $contents = $this->includeAdditional($contents, $env->getAdditional());

        try {
            file_put_contents($this->envFilePath, $contents);
        } catch (Exception) {
            return false;
        }

        return true;
    }

    /**
     * Include the additional env variables.
     */
    protected function includeAdditional(string $contents, array $additional): string
    {
        if (count($additional) > 0) {
            $contents .= "\n";

            foreach ($additional as $key => $value) {
                $contents .= $key.'='.$value."\n";
            }
        }

        return $contents;
    }

    /**
     * Get the environment file path.
     */
    public function getEnvFilePath(): string
    {
        return $this->envFilePath;
    }

    /**
     * Guess the application URL.
     */
    public static function guessUrl(): string
    {
        $guessedUrl = isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) == 'on' ? 'https' : 'http';
        $guessedUrl .= '://'.$_SERVER['HTTP_HOST'];
        $guessedUrl .= str_replace(basename($_SERVER['SCRIPT_NAME']), '', $_SERVER['SCRIPT_NAME']);
        $guessedUrl = preg_replace('/install.*/', '', $guessedUrl);

        return rtrim($guessedUrl, '/');
    }
}
