<?php
/// file: app/Core/Config.php

declare(strict_types=1);

namespace App\Core;

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

    public static function load(string $configDir): void
    {
        if (! is_dir($configDir)) {
            return;
        }
        foreach (glob($configDir . '/*.php') ?: [] as $file) {
            $key = basename($file, '.php');
            /** @var mixed $data */
            $data = require $file;
            if (is_array($data)) {
                self::$items[$key] = $data;
            }
        }
    }

    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;
    }

    /** @param array<string, mixed> $merge */
    public static function set(string $key, array $merge): void
    {
        self::$items[$key] = array_replace_recursive(self::$items[$key] ?? [], $merge);
    }
}
