<?php

namespace App\Support;

use App\Models\Setting;

class ConfigStore
{
    /**
     * Get a configuration value
     * If key has no dots, treat as group retrieval
     * Also checks if the key might be an array-style setting (e.g., emails.repairs.managers -> managers.0, managers.1)
     *
     * @param string $key
     * @param mixed $default
     * @return mixed
     */
    public static function get($key, $default = null)
    {
        // If key has no dots, treat as group retrieval
        if (strpos($key, '.') === false) {
            $groupSettings = Setting::getGroup($key);
            return !empty($groupSettings) ? $groupSettings : $default;
        }

        // First try to get it as a single setting
        $value = Setting::get($key, null);

        // If not found and default is an array, try to get as a group
        // This handles cases like 'emails.repairs.managers' which should return ['managers.0' => 'email@example.com']
        if ($value === null && is_array($default)) {
            $groupSettings = Setting::getGroup($key);
            if (!empty($groupSettings)) {
                return $groupSettings;
            }
        }

        return $value !== null ? $value : $default;
    }

    /**
     * Set a configuration value
     *
     * @param string $key
     * @param mixed $value
     * @return mixed
     */
    public static function set($key, $value)
    {
        return Setting::set($key, $value);
    }

    /**
     * Store a configuration value (alias for set)
     *
     * @param string $key
     * @param mixed $value
     * @return mixed
     */
    public static function store($key, $value)
    {
        return Setting::store($key, $value);
    }

    /**
     * Delete a configuration value
     *
     * @param string $key
     * @return bool
     */
    public static function delete($key)
    {
        return Setting::deleteKey($key);
    }

    /**
     * Clear all configuration cache
     */
    public static function clear()
    {
        Setting::clear();
    }

    /**
     * Get all configuration values
     *
     * @return array
     */
    public static function all()
    {
        $settings = Setting::all();
        $result = [];
        
        foreach ($settings as $setting) {
            $result[$setting->key] = Setting::get($setting->key);
        }
        
        return $result;
    }

    /**
     * Get configuration values by group
     *
     * @param string $group
     * @return array
     */
    public static function getGroup($group)
    {
        return Setting::getGroup($group);
    }
} 