<?php

namespace App\Core\Services;

use Illuminate\Support\Facades\File;

/**
 * Environment Service
 * Handles reading and writing to .env file
 */
class EnvService
{
    /**
     * Update or add environment variable
     */
    public function set(string $key, string $value): bool
    {
        $envFile = base_path('.env');

        if (! File::exists($envFile)) {
            return false;
        }

        $envContent = File::get($envFile);

        // Escape value if it contains spaces or special characters
        if (preg_match('/\s/', $value) || strpos($value, '#') !== false) {
            $value = '"'.addslashes($value).'"';
        }

        // Check if key exists
        if (preg_match("/^{$key}=.*/m", $envContent)) {
            // Update existing key
            $envContent = preg_replace("/^{$key}=.*/m", "{$key}={$value}", $envContent);
        } else {
            // Add new key at the end
            $envContent .= "\n{$key}={$value}";
        }

        return File::put($envFile, $envContent) !== false;
    }

    /**
     * Get environment variable value
     */
    public function get(string $key, ?string $default = null): ?string
    {
        return env($key, $default);
    }

    /**
     * Update multiple environment variables
     */
    public function setMultiple(array $variables): bool
    {
        foreach ($variables as $key => $value) {
            if (! $this->set($key, $value)) {
                return false;
            }
        }

        return true;
    }
}
