<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redis;

class CommonConfigController extends Controller
{
    public function index()
    {
        $defaultConfig = [
            ["RechargeMin" => 0, "RechargeMax" => 1, "FreeWinMax" => 1000, "RechargeMaxPercent" => 0, "TaxPercent" => 100],
            ["RechargeMin" => 1, "RechargeMax" => 101, "FreeWinMax" => 20, "RechargeMaxPercent" => 80, "TaxPercent" => 100],
            ["RechargeMin" => 101, "RechargeMax" => 501, "FreeWinMax" => 100, "RechargeMaxPercent" => 70, "TaxPercent" => 95],
            ["RechargeMin" => 501, "RechargeMax" => 1001, "FreeWinMax" => 400, "RechargeMaxPercent" => 60, "TaxPercent" => 90],
            ["RechargeMin" => 1001, "RechargeMax" => 10001, "FreeWinMax" => 8000, "RechargeMaxPercent" => 55, "TaxPercent" => 85],
            ["RechargeMin" => 10001, "RechargeMax" => 99999999, "FreeWinMax" => 0, "RechargeMaxPercent" => 50, "TaxPercent" => 80]
        ];

        // 从 Redis 获取公用配置数据
        $configData = Redis::get("GameConfigX_Common");
        $config = $configData ? json_decode($configData, true) : $defaultConfig;

        // 从 Redis 获取库存模式配置数据
        $specialConfigData = Redis::get("GameConfigX_Special");
        $specialConfig = $specialConfigData ? json_decode($specialConfigData, true) : $defaultConfig;

        return view('admin.common_config.index', compact('config', 'specialConfig'));
    }

    public function update(Request $request)
    {
        $config = $request->input('config');
        $configType = $request->input('config_type', 'common'); // 获取配置类型，默认为 common

        $redisKey = $configType === 'special' ? 'GameConfigX_Special' : 'GameConfigX_Common';

        \Log::info('公用配置更新请求', [
            'config_type' => $configType,
            'config' => $config,
            'all_data' => $request->all()
        ]);

        if (!$config) {
            \Log::error('公用配置更新失败：参数错误');
            return response()->json(['status' => 'error', 'message' => '参数错误']);
        }

        try {
            $configData = json_decode($config, true);
            if (json_last_error() !== JSON_ERROR_NONE) {
                \Log::error('公用配置更新失败：JSON格式错误', ['error' => json_last_error_msg()]);
                throw new \Exception('JSON格式错误: ' . json_last_error_msg());
            }

            Redis::set($redisKey, $config);
            \Log::info('公用配置更新成功', ['redis_key' => $redisKey]);
            return response()->json(['status' => 'success', 'message' => '更新成功']);
        } catch (\Exception $e) {
            \Log::error('公用配置更新失败：异常', ['message' => $e->getMessage()]);
            return response()->json(['status' => 'error', 'message' => $e->getMessage()]);
        }
    }

}
