<?php

namespace App\Http\Controllers\Admin;

use App\Game\WebThemeConfig;
use App\Game\WebRegionConfig;
use Illuminate\Http\Request;

class WebThemeConfigController
{
    public function index(Request $request)
    {
        $list = WebThemeConfig::orderBy('id', 'asc')->paginate(40);

        return view('admin.web_theme_config.index', [
            'list' => $list,
        ]);
    }

    public function add(Request $request)
    {
        if ($request->isMethod('post')) {
            $post = $request->post();

            // 处理 BindRegions，将字符串转换为数组
            if (isset($post['BindRegions']) && is_string($post['BindRegions'])) {
                $regionIds = array_filter(array_map('trim', explode(',', $post['BindRegions'])));
                $post['BindRegions'] = array_map('intval', $regionIds);
            }

            WebThemeConfig::create($post);

            // 更新对应 Region 的 ThemeKey
            if (!empty($post['BindRegions']) && !empty($post['ThemeKey'])) {
                WebRegionConfig::whereIn('id', $post['BindRegions'])
                    ->update(['ThemeKey' => $post['ThemeKey']]);
            }

            return apiReturnSuc();
        }

        $regions = WebRegionConfig::orderBy('GroupID', 'asc')->orderBy('id', 'asc')->get();
        return view('admin.web_theme_config.add', ['regions' => $regions]);
    }

    public function edit(Request $request, $id)
    {
        $info = WebThemeConfig::findOrFail($id);

        if ($request->isMethod('post')) {
            $post = $request->post();

            // 处理 BindRegions
            if (isset($post['BindRegions']) && is_string($post['BindRegions'])) {
                $regionIds = array_filter(array_map('trim', explode(',', $post['BindRegions'])));
                $post['BindRegions'] = array_map('intval', $regionIds);
            }

            // 清除原有绑定的 Region 的 ThemeKey
            if (!empty($info->BindRegions)) {
                WebRegionConfig::whereIn('id', $info->BindRegions)
                    ->update(['ThemeKey' => '']);
            }

            $info->update($post);

            // 更新新绑定的 Region 的 ThemeKey
            if (!empty($post['BindRegions']) && !empty($post['ThemeKey'])) {
                WebRegionConfig::whereIn('id', $post['BindRegions'])
                    ->update(['ThemeKey' => $post['ThemeKey']]);
            }

            return apiReturnSuc();
        }

        $regions = WebRegionConfig::orderBy('GroupID', 'asc')->orderBy('id', 'asc')->get();
        return view('admin.web_theme_config.edit', [
            'info' => $info,
            'regions' => $regions
        ]);
    }

    public function delete($id)
    {
        $info = WebThemeConfig::findOrFail($id);

        // 清除绑定的 Region 的 ThemeKey
        if (!empty($info->BindRegions)) {
            WebRegionConfig::whereIn('id', $info->BindRegions)
                ->update(['ThemeKey' => '']);
        }

        $info->delete();

        return apiReturnSuc();
    }
}
