<?php

namespace RtRasel\LaravelInstaller\Helpers;

use Exception;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\File;

class EnvironmentManager
{
    /**
     * @var string
     */
    private $envPath;

    /**
     * @var string
     */
    private $envExamplePath;

    /**
     * Set the .env and .env.example paths.
     */
    public function __construct()
    {
        $this->envPath = base_path('.env');
        $this->envExamplePath = base_path('.env.example');
    }

    /**
     * Create the content of the .env file.
     *
     * @return string
     */
    private function createEnvContent()
    {
        if (!file_exists($this->envPath)) {
            if (file_exists($this->envExamplePath)) {
                copy($this->envExamplePath, $this->envPath);
            } else {
                touch($this->envPath);
            }
        }
    }

    /**
     * Get the the .env file path.
     *
     * @return string
     */
    public function getEnvPath()
    {
        return $this->envPath;
    }

    /**
     * Get the the .env.example file path.
     *
     * @return string
     */
    public function getEnvExamplePath()
    {
        return $this->envExamplePath;
    }


    /**
     * Save the form content to the .env file.
     *
     * @param  Request  $request
     * @return string
     */
    public function saveFile(Request $request)
    {
        $this->createEnvContent();

        $results = __('Your .env file settings have been saved.');

        $envFileData = [
            'APP_ENV'   => 'production',
            'APP_URL'   => $request->root(),
            'DB_HOST' => $request->database_hostname,
            'DB_PORT' => $request->database_port,
            'DB_DATABASE' => $request->database_name,
            'DB_USERNAME' => $request->database_username,
            'DB_PASSWORD' => $request->database_password,
        ];

        try {
            $this->setEnvValues($envFileData);
            return $this->response($results, 'success');
        } catch (Exception $e) {
            $results = __('Unable to save the .env file, Please create it manually.');
            return $this->response($results, 'error');
        }

        return $results;
    }

    private function setEnvValues(array $keyValuePairs)
    {
        // Read the current contents of the .env file
        $contents = File::get($this->envPath);

        // Update the contents with the new key-value pairs
        foreach ($keyValuePairs as $key => $value) {
            // Generate a new value for the key
            $newValue = is_string($value) ? '"' . $value . '"' : $value;

            // Create a regex pattern for the key
            $pattern = "/^{$key}=.*/m";

            // Replace the value in the contents
            $contents = preg_replace($pattern, "{$key}={$newValue}", $contents);
        }

        // Write the updated contents back to the .env file
        File::put($this->envPath, $contents);
    }

    /**
     * Return a formatted error messages.
     *
     * @param  string  $message
     * @param  string  $status
     * @return array
     */
    private function response($message, $status)
    {
        return [
            'status' => $status,
            'message' => $message
        ];
    }
}
