<?php

namespace SSCI\Classes;

/**
 * Configuration Class
 * Manages application configuration
 */
class Config
{
    private static array $config = [];

    /**
     * Load configuration file
     */
    public static function load(string $filename): array
    {
        if (isset(self::$config[$filename])) {
            return self::$config[$filename];
        }

        $path = __DIR__ . '/../../config/' . $filename . '.php';

        if (!file_exists($path)) {
            return [];
        }

        self::$config[$filename] = require $path;
        return self::$config[$filename];
    }

    /**
     * Get config value
     */
    public static function get(string $key, mixed $default = null): mixed
    {
        $parts = explode('.', $key);
        $file = array_shift($parts);
        $config = self::load($file);

        foreach ($parts as $part) {
            if (isset($config[$part])) {
                $config = $config[$part];
            } else {
                return $default;
            }
        }

        return $config ?? $default;
    }

    /**
     * Set config value
     */
    public static function set(string $key, mixed $value): void
    {
        $parts = explode('.', $key);
        $file = array_shift($parts);

        if (!isset(self::$config[$file])) {
            self::load($file);
        }

        $current = &self::$config[$file];
        foreach ($parts as $part) {
            if (!isset($current[$part])) {
                $current[$part] = [];
            }
            $current = &$current[$part];
        }

        $current = $value;
    }
}
