<?php

declare(strict_types=1);

namespace System\Configuration;

final class Config
{
    /**
     * Loaded configuration.
     *
     * @var array<string, mixed>
     */
    private static array $items = [];

    /**
     * Load every PHP config file from config/.
     */
    public static function load(string $directory): void
    {
        if (!is_dir($directory)) {
            throw new \RuntimeException(
                "Configuration directory not found: {$directory}"
            );
        }

        $files = glob($directory . DIRECTORY_SEPARATOR . '*.php');

        if ($files === false) {
            return;
        }

        foreach ($files as $file) {

            $name = basename($file, '.php');

            self::$items[$name] = require $file;
        }
    }

    /**
     * Get configuration value using dot notation.
     */
    public static function get(
        string $key,
        mixed $default = null
    ): mixed {

        $segments = explode('.', $key);

        $value = self::$items;

        foreach ($segments as $segment) {

            if (!is_array($value) || !array_key_exists($segment, $value)) {
                return $default;
            }

            $value = $value[$segment];
        }

        return $value;
    }

    /**
     * Return all loaded configuration.
     */
    public static function all(): array
    {
        return self::$items;
    }
}