<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;

class GameBuyBonusConfigController
{
    /**
     * Bonus购买回报配置列表（可编辑）
     */
    public function index(Request $request)
    {
        $configs = DB::connection('write')
            ->table('QPPlatformDB.dbo.GameBuyBonusConfig')
            ->orderBy('MultiMin', 'asc')
            ->get();

        return view('admin.game_buy_bonus_config.index', compact('configs'));
    }

    /**
     * 批量更新配置（只更新有变动的数据）
     */
    public function update(Request $request)
    {
        try {
            $configs = $request->input('configs', []);

            if (empty($configs)) {
                return apiReturnFail('没有需要更新的数据');
            }

            DB::beginTransaction();

            $updatedIds = [];
            $updatedCount = 0;
            
            foreach ($configs as $configId => $data) {
                // 构建更新数据（只包含提交的字段）
                $updateData = [];
                
                if (isset($data['MultiMin'])) {
                    $updateData['MultiMin'] = round((float)$data['MultiMin'], 2);
                }
                if (isset($data['MultiMax'])) {
                    $updateData['MultiMax'] = round((float)$data['MultiMax'], 2);
                }
                if (isset($data['Weight'])) {
                    $updateData['Weight'] = (int)$data['Weight'];
                }
                if (isset($data['WeightAdjust'])) {
                    $updateData['WeightAdjust'] = $data['WeightAdjust'];
                }

                // 只有有数据时才更新
                if (!empty($updateData)) {
                    DB::connection('write')
                        ->table('QPPlatformDB.dbo.GameBuyBonusConfig')
                        ->where('ConfigID', $configId)
                        ->update($updateData);
                    
                    $updatedIds[] = $configId;
                    $updatedCount++;
                }
            }

            DB::commit();

            // 清除可能的缓存
            Redis::del('game_buy_bonus_config_cache');

            \Log::info('Bonus购买回报配置更新成功', [
                'admin_id' => $request->session()->get('admin')->id ?? 0,
                'updated_count' => $updatedCount,
                'config_ids' => $updatedIds
            ]);

            return apiReturnSuc("配置更新成功，共更新 {$updatedCount} 条数据");

        } catch (\Exception $e) {
            DB::rollBack();
            \Log::error('Bonus购买回报配置更新失败', [
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString()
            ]);
            return apiReturnFail('更新失败: ' . $e->getMessage());
        }
    }
}
