<?php

declare(strict_types=1);

namespace App\Framework\Config;

class Configuration
{
    private array $config = [];

    /**
     * Lädt Konfigurationen aus einer oder mehreren Quellen
     */
    public function __construct(array $config = [])
    {
        $this->config = $config;
    }

    /**
     * Lädt Konfigurationen aus PHP-Dateien
     */
    public function loadFromFile(string $path): self
    {
        if (file_exists($path) && is_readable($path)) {
            $fileConfig = require $path;
            if (is_array($fileConfig)) {
                $this->config = array_merge($this->config, $fileConfig);
            }
        }

        return $this;
    }

    /**
     * Lädt Konfigurationen aus einem Verzeichnis
     */
    public function loadFromDirectory(string $directory): self
    {
        if (!is_dir($directory)) {
            return $this;
        }

        foreach (glob($directory . '/*.php') as $file) {
            $this->loadFromFile($file);
        }

        return $this;
    }

    /**
     * Gibt einen Konfigurationswert zurück
     */
    public function get(string $key, mixed $default = null): mixed
    {
        $keys = explode('.', $key);
        $value = $this->config;

        foreach ($keys as $segment) {
            if (!is_array($value) || !array_key_exists($segment, $value)) {
                return $default;
            }
            $value = $value[$segment];
        }

        return $value;
    }

    /**
     * Setzt einen Konfigurationswert
     */
    public function set(string $key, mixed $value): self
    {
        $keys = explode('.', $key);
        $config = &$this->config;

        foreach ($keys as $i => $segment) {
            if ($i === count($keys) - 1) {
                $config[$segment] = $value;
                break;
            }

            if (!isset($config[$segment]) || !is_array($config[$segment])) {
                $config[$segment] = [];
            }

            $config = &$config[$segment];
        }

        return $this;
    }

    /**
     * Prüft, ob ein Konfigurationswert existiert
     */
    public function has(string $key): bool
    {
        $keys = explode('.', $key);
        $config = $this->config;

        foreach ($keys as $segment) {
            if (!is_array($config) || !array_key_exists($segment, $config)) {
                return false;
            }
            $config = $config[$segment];
        }

        return true;
    }

    /**
     * Gibt alle Konfigurationswerte zurück
     */
    public function all(): array
    {
        return $this->config;
    }
}
