<?php

namespace App\Core;

/**
 * ITSWEBER CMS – Configuration
 *
 * Loads and provides access to PHP array config files.
 */
class Config
{
    private string $configPath;
    private array $loaded = [];

    public function __construct(string $configPath)
    {
        $this->configPath = rtrim($configPath, '/');
    }

    /**
     * Get a config value using dot notation.
     * Example: get('database.host') loads app/Config/database.php and returns ['host'].
     */
    public function get(string $key, mixed $default = null): mixed
    {
        $parts = explode('.', $key);
        $file = array_shift($parts);

        $config = $this->load($file);
        if ($config === null) {
            return $default;
        }

        if (empty($parts)) {
            return $config;
        }

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

        return $value;
    }

    /**
     * Load a config file.
     */
    private function load(string $name): ?array
    {
        if (isset($this->loaded[$name])) {
            return $this->loaded[$name];
        }

        $file = $this->configPath . '/' . $name . '.php';
        if (!file_exists($file)) {
            return null;
        }

        $this->loaded[$name] = require $file;
        return $this->loaded[$name];
    }

    /**
     * Get the config directory path.
     */
    public function path(): string
    {
        return $this->configPath;
    }
}
