<?php

namespace App\Helpers;

class ConfigManager
{
    private $configFile;

    public function __construct(string $configFile)
    {
        $this->configFile = $configFile;
    }

    public function getSetting($key = null)
    {
        // Read the JSON file
        $config = $this->readConfigFile();

        if (empty($key)) {
            // If $key is null or empty, return the entire config array
            return $config ?? null;
        } else {
            // Split the key into sections
            $sections = explode('.', $key);

            // Traverse through the sections to get the value
            $nestedConfig = $config;
            foreach ($sections as $section) {
                if (isset($nestedConfig[$section])) {
                    $nestedConfig = $nestedConfig[$section];
                } else {
                    return null; // Return null if the key doesn't exist
                }
            }

            return $nestedConfig;
        }
    }


    public function setSetting($key, $value)
    {
        // Read the existing JSON file
        $config = $this->readConfigFile();

        // Update or add the new value under 'app'
        $config['app'][$key] = $value;

        // Write the updated content back to the file
        $this->writeConfigFile($config);
    }

    private function readConfigFile()
    {
        return json_decode(file_get_contents($this->configFile), true);
    }

    private function writeConfigFile($config)
    {
        file_put_contents($this->configFile, json_encode($config, JSON_PRETTY_PRINT));
    }
}
