<?php
/**
 * 芋头CMS
 * ============================================================================
 * 版权所有 2016-2028 沅陵县乌托邦网络服务有限公司，并保留所有权利。
 * 网站地址: http://www.yutoucms.cn
 * ----------------------------------------------------------------------------
 * 如果商业用途务必到官方购买正版授权, 以免引起不必要的法律纠纷.
 * ============================================================================
 * Author: 芋头 <mxgsf@qq.com>
 * Date: 2026-5-20
 */

namespace Core\Lib;

class ShopConfig
{
    public static function defaults()
    {
        return [
            'review_enabled' => '1',
            'review_audit' => '1',
        ];
    }

    public static function get($db)
    {
        $defaults = self::defaults();
        $rows = $db->fetchAll("SELECT config_key, config_value FROM {$db->table('config')} WHERE config_group = 'shop'");
        $config = $defaults;
        foreach ($rows as $row) {
            $key = (string) ($row['config_key'] ?? '');
            if ($key !== '' && array_key_exists($key, $defaults)) {
                $config[$key] = (string) ($row['config_value'] ?? '');
            }
        }
        return $config;
    }

    public static function save($db, array $data)
    {
        $defaults = self::defaults();
        foreach ($defaults as $key => $defaultValue) {
            $value = isset($data[$key]) ? (string) $data[$key] : $defaultValue;
            $exists = $db->fetch("SELECT id FROM {$db->table('config')} WHERE config_key = ? LIMIT 1", [$key]);
            if ($exists) {
                $db->update('config', ['config_value' => $value, 'config_group' => 'shop'], 'config_key = ?', [$key]);
            } else {
                $db->insert('config', [
                    'config_key' => $key,
                    'config_value' => $value,
                    'config_type' => 'text',
                    'config_group' => 'shop',
                ]);
            }
        }
    }

    public static function enabled($db, $key)
    {
        $config = self::get($db);
        return isset($config[$key]) && (string) $config[$key] === '1';
    }
}
