<?php
// components/ConfigStore.php
// Facade for configuration and status across providers (mock/live)

namespace Components;

class ConfigStore
{
    private const STORE_FILE = 'var/config_store.json';
    private const MODULE_CONFIG_KEY = 'module_config';

    /** Resolve absolute path to store file and ensure directory exists */
    private static function storePath(): string
    {
        $root = defined('BEEZUI_ROOT') ? BEEZUI_ROOT : dirname(__DIR__);
        $path = $root . DIRECTORY_SEPARATOR . self::STORE_FILE;
        $dir = dirname($path);
        if (!is_dir($dir)) {
            @mkdir($dir, 0775, true);
        }
        return $path;
    }

    /** Read entire store (associative array); return [] if missing or invalid */
    private static function readStore(): array
    {
        $path = self::storePath();
        if (!is_file($path)) {
            return [];
        }
        $json = @file_get_contents($path);
        if ($json === false || $json === '') {
            return [];
        }
        $data = json_decode($json, true);
        return is_array($data) ? $data : [];
    }

    /** Write entire store atomically; ignore errors silently */
    private static function writeStore(array $store): void
    {
        $path = self::storePath();
        $json = json_encode($store, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
        if ($json === false) {
            return; // nothing we can do
        }
        @file_put_contents($path, $json, LOCK_EX);
    }

    /** Return full config map: module => values */
    public static function getAllConfigs(): array
    {
        // Delegate to active provider (mock/live)
        return \Components\Data\DataRegistry::config()->getAllConfigs();
    }

    /** Return module config values (assoc array); [] if none */
    public static function getModuleConfig(string $module): array
    {
        return \Components\Data\DataRegistry::config()->getModuleConfig($module);
    }

    /** Persist module config values */
    public static function setModuleConfig(string $module, array $values, bool $processOnlyGivenFields = false): void
    {
        \Components\Data\DataRegistry::config()->setModuleConfig($module, $values, $processOnlyGivenFields);
    }

    /** Return full status map derived from module_config: module => 'on'|'' */
    public static function getAllStatuses(): array
    {
        return \Components\Data\DataRegistry::config()->getAllStatuses();
    }

    /** Return true if module is ON */
    public static function isModuleOn(string $module): bool
    {
        return \Components\Data\DataRegistry::config()->isModuleOn($module);
    }

    /** Set module status on/off, stored as *_STATUS inside module_config */
    public static function setModuleStatus(string $module, bool $on): void
    {
        \Components\Data\DataRegistry::config()->setModuleStatus($module, $on);
    }

    /**
     * UI open state map: module => bool
     * Returns associative array suitable for Alpine initialization
     */
    public static function getUiOpenMap(): array
    {
        return \Components\Data\DataRegistry::config()->getUiOpenMap();
    }

    /** Persist a single module UI open/closed state. */
    public static function setUiOpenState(string $module, bool $open): void
    {
        \Components\Data\DataRegistry::config()->setUiOpenState($module, $open);
    }

    /** Optional: list known config keys for a module */
    public static function listKeys(string $module): array
    {
        return \Components\Data\DataRegistry::config()->listKeys($module);
    }

    /** Return true if the module configuration has been saved at least once. */
    public static function isConfigured(string $module): bool
    {
        return \Components\Data\DataRegistry::config()->isConfigured($module);
    }

    /** Mark the module as configured. */
    public static function setConfigured(string $module): void
    {
        \Components\Data\DataRegistry::config()->setConfigured($module);
    }

    /** Clear the configured marker for the module (e.g., after uninstall). */
    public static function clearConfigured(string $module): void
    {
        \Components\Data\DataRegistry::config()->clearConfigured($module);
    }

    /**
     * Read the full newsletter UI state blob for the current user.
     * Keys: sidebar_width, sidebar_collapsed, selected_slug, smart_layout, smart_hidden, sections_open.
     */
    public static function getNewsletterUiState(): array
    {
        return \Components\Data\DataRegistry::config()->getNewsletterUiState();
    }

    /**
     * Merge and persist newsletter UI state fields for the current user.
     */
    public static function setNewsletterUiState(array $patch): void
    {
         \Components\Data\DataRegistry::config()->setNewsletterUiState($patch);
    }
}