<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Http\helper\NumConfig;

class ProtectLevelController extends Controller
{
    protected $table = 'QPAccountsDB.dbo.ProtectLevel';

    // 列表
    public function index()
    {
        $list = DB::connection('read')->table($this->table)
            ->orderBy('VIP')
            ->get();

        // 获取配置值（合并查询）
        $statusInfo = DB::connection('read')->table('QPAccountsDB.dbo.SystemStatusInfo')
            ->whereIn('StatusName', ['ProtectLevelDownDays', 'ProtectLevelExpireDays'])
            ->pluck('StatusValue', 'StatusName');

        $downDays = $statusInfo['ProtectLevelDownDays'] ?? null;
        $expireDays = $statusInfo['ProtectLevelExpireDays'] ?? null;

        return view('admin.protect_level.index', compact('list', 'downDays', 'expireDays'));
    }

    // 增加
    public function add(Request $request)
    {
        if ($request->isMethod('get')) {
            return view('admin.protect_level.add');
        }

        $data = $request->only([
            'ID', 'Recharge', 'VIP', 'LevelUpBonus',
            'MinRecharge', 'WithdrawLimit', 'DailyWithdraws',
            'WithdrawFeeRate', 'Alpha', 'CustomServiceType',
            'RechargeExtraSendRate', 'SuperballNum', 'BirthdayValue',
        ]);

        // 简单验证（ID唯一性后面手动检查）
        $this->validate($request, [
            'ID' => 'required|integer',
            'Recharge' => 'required|numeric|min:0',
            'VIP' => 'required|integer|min:0',
            'LevelUpBonus' => 'required|integer|min:0',
            'MinRecharge' => 'required|integer|min:0',
            'WithdrawLimit' => 'required|integer|min:0',
            'DailyWithdraws' => 'required|integer|min:0|max:255',
            'WithdrawFeeRate' => 'required|numeric|min:0',
            'Alpha' => 'required|numeric|min:0',
            'CustomServiceType' => 'required|integer|in:1,2',
            'RechargeExtraSendRate' => 'required|numeric|min:0',
            'SuperballNum' => 'required|integer|min:0',
            'BirthdayValue' => 'required|integer|min:0',
        ]);
        // 唯一性检查
        if (DB::connection('read')->table($this->table)->where('ID', $data['ID'])->exists()) {
            return apiReturnFail('ID already exists');
        }
        $data['BirthdayValue'] = $data['BirthdayValue'] * NumConfig::NUM_VALUE;
        DB::connection('write')->table($this->table)->insert($data);
        return apiReturnSuc();
    }

    // 修改
    public function edit(Request $request, $id)
    {
        if ($request->isMethod('get')) {
            $info = DB::connection('read')->table($this->table)
                ->where('ID', $id)
                ->first();
            return view('admin.protect_level.edit', compact('info'));
        }

        $post = $request->only([
            'Recharge', 'VIP', 'LevelUpBonus',
            'MinRecharge', 'WithdrawLimit', 'DailyWithdraws',
            'WithdrawFeeRate', 'Alpha', 'CustomServiceType',
            'RechargeExtraSendRate', 'SuperballNum', 'BirthdayValue',
        ]);

        // 字段校验
        $this->validate($request, [
            'Recharge' => 'required|numeric|min:0',
            'VIP' => 'required|integer|min:0',
            'LevelUpBonus' => 'required|integer|min:0',
            'MinRecharge' => 'required|integer|min:0',
            'WithdrawLimit' => 'required|integer|min:0',
            'DailyWithdraws' => 'required|integer|min:0|max:255',
            'WithdrawFeeRate' => 'required|numeric|min:0',
            'Alpha' => 'required|numeric|min:0',
            'CustomServiceType' => 'required|integer|in:1,2',
            'RechargeExtraSendRate' => 'required|numeric|min:0',
            'SuperballNum' => 'required|integer|min:0',
            'BirthdayValue' => 'required|integer|min:0',
        ]);
        $post['BirthdayValue'] = $post['BirthdayValue'] * NumConfig::NUM_VALUE;
        DB::connection('write')->table($this->table)
            ->where('ID', $id)
            ->update($post);

        return apiReturnSuc();
    }

    // 删除
    public function delete($id)
    {
        DB::connection('write')->table($this->table)
            ->where('ID', $id)
            ->delete();

        return apiReturnSuc();
    }

    // 保存配置
    public function saveConfig(Request $request)
    {
        $this->validate($request, [
            'down_days' => 'required|integer|min:1',
            'expire_days' => 'required|integer|min:1',
        ]);

        $downDays = $request->input('down_days');
        $expireDays = $request->input('expire_days');

        // 更新或创建 ProtectLevelDownDays 配置
        DB::connection('write')->table('QPAccountsDB.dbo.SystemStatusInfo')
            ->updateOrInsert(
                ['StatusName' => 'ProtectLevelDownDays'],
                ['StatusValue' => $downDays]
            );

        // 更新或创建 ProtectLevelExpireDays 配置
        DB::connection('write')->table('QPAccountsDB.dbo.SystemStatusInfo')
            ->updateOrInsert(
                ['StatusName' => 'ProtectLevelExpireDays'],
                ['StatusValue' => $expireDays]
            );

        return apiReturnSuc();
    }
}
