<?php

/**
 * Configuration Manager  ArraySubs
 *
 * This class manages configuration settings for theArraySubs plugin
 * using a singleton pattern to ensure only one instance exists.
 *
 * @package ArraySubs
 * @subpackage Supports
 * @since 1.0.0
 */

namespace ArraySubs\Supports;

use ArraySubs\Supports\Traits\Singleton;
use ArraySubs\Features\MainAdmin\REST\LicenseController;

if (! defined('ABSPATH')) {
    exit; // Exit if accessed directly
}

/**
 * Wrapper for plugin configuration storage.
 */
class Config
{
    use Singleton;

    protected ?string $configPath = null;

    protected array $configData = [];

    public function __construct(?string $configPath = null)
    {
        $this->configPath = $configPath;
    }

    public static function get($key, $default = null): mixed
    {
        $instance = self::instance();

        // Handle dot notation for nested keys
        if (str_contains($key, '.')) {
            $keys = explode('.', $key);
            $data = $instance->configData;

            foreach ($keys as $segment) {
                if (is_array($data) && array_key_exists($segment, $data)) {
                    $data = $data[$segment];
                } else {
                    return $default;
                }
            }

            return $data;
        }

        // Direct key access
        return $instance->configData[$key] ?? $default;
    }
    public static function has($key): bool
    {
        if (empty($key)) {
            return false;
        }

        if (self::get($key, '__not_exists__') !== '__not_exists__') {
            return true;
        }
        return false;
    }

    public static function add($key, $value): void
    {
        // check if the license is activated 
        // if not activated, do not allow adding config for key contains 'proplugin'

        if (LicenseController::status() !== true && str_contains($key, 'proplugin')) {
            return;
        }

        $instance = self::instance();

        // Handle dot notation for nested keys
        if (str_contains($key, '.')) {
            $keys = explode('.', $key);
            $data = &$instance->configData;

            // Navigate/create nested structure
            foreach ($keys as $segment) {
                if (!isset($data[$segment]) || !is_array($data[$segment])) {
                    $data[$segment] = [];
                }
                $data = &$data[$segment];
            }

            // Set the value at the deepest level
            $data = $value;
        } else {
            // Direct key assignment
            $instance->configData[$key] = $value;
        }
    }
}
