<?php

namespace App\Http\Controllers\Admin;

use App\Game\Banner;
use App\Game\WebThemeConfig;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class BannerController
{
    public function index(Request $request)
    {
        $query = Banner::query();

        // 可以根据主题筛选
        if ($request->has('theme_key') && !empty($request->theme_key)) {
            $query->where('theme_key', $request->theme_key);
        }

        $list = $query->orderByRaw('ISNULL(b_order), b_order ASC')
            ->orderBy('bid', 'desc')
            ->paginate(20);

        // 获取所有主题用于筛选
        $themes = WebThemeConfig::all();

        return view('admin.banner.index', [
            'list' => $list,
            'theme_key' => $request->theme_key ?? '',
            'themes' => $themes
        ]);
    }

    public function add(Request $request)
    {
        if ($request->isMethod('post')) {
            $validator = Validator::make($request->all(), [
                'img' => 'required|string',
                'alt' => 'nullable|string',
                'link_game' => 'nullable|integer',
                'link_module' => 'nullable|integer',
                'theme_key' => 'nullable|string|max:30',
                'link' => 'nullable|string|max:200',
                'b_order' => 'nullable|integer',
                'state' => 'nullable|integer',
            ]);

            if ($validator->fails()) {
                return apiReturnFail($validator->errors()->first());
            }

            $data = $request->only([
                'img', 'img_pt', 'img_es', 'alt', 'link_game', 'link_module',
                'theme_key', 'link', 'b_order', 'state'
            ]);

            // 默认值处理
            $data['link'] = $data['link'] ?? '';
            $data['state'] = isset($data['state']) && $data['state'] !== '' ? (int)$data['state'] : 127;
            $data['b_order'] = $data['b_order'] !== '' ? $data['b_order'] : null;

            Banner::create($data);

            return apiReturnSuc();
        }

        $themes = WebThemeConfig::all();
        return view('admin.banner.add', ['themes' => $themes]);
    }

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

        if ($request->isMethod('post')) {
            $validator = Validator::make($request->all(), [
                'img' => 'required|string',
                'alt' => 'nullable|string',
                'link_game' => 'nullable|integer',
                'link_module' => 'nullable|integer',
                'theme_key' => 'nullable|string|max:30',
                'link' => 'nullable|string|max:200',
                'b_order' => 'nullable|integer',
                'state' => 'nullable|integer',
            ]);

            if ($validator->fails()) {
                return apiReturnFail($validator->errors()->first());
            }

            $data = $request->only([
                'img', 'img_pt', 'img_es', 'alt', 'link_game', 'link_module',
                'theme_key', 'link', 'b_order', 'state'
            ]);

            $data['link'] = $data['link'] ?? '';
            $data['state'] = isset($data['state']) && $data['state'] !== '' ? (int)$data['state'] : 127;
            $data['b_order'] = $data['b_order'] !== '' ? $data['b_order'] : null;

            $info->update($data);

            return apiReturnSuc();
        }

        $themes = WebThemeConfig::all();
        return view('admin.banner.edit', [
            'info' => $info,
            'themes' => $themes
        ]);
    }

    public function delete($id)
    {
        $info = Banner::findOrFail($id);
        $info->delete();

        return apiReturnSuc();
    }

    /**
     * 同步当前 banner（事件）到其他所有主题
     * 规则：通过 link 字段识别"事件"
     *       其他主题如果没有相同 link 的 banner，则复制过去
     */
    public function sync($id)
    {
        $info = Banner::findOrFail($id);

        if (empty($info->link)) {
            return apiReturnFail('当前 Banner 没有设置 link(事件)，无法识别为一个事件进行同步');
        }

        $themes = WebThemeConfig::all();
        $copied = 0;
        $skipped = 0;

        foreach ($themes as $theme) {
            $themeKey = $theme->ThemeKey;

            // 跳过当前 banner 所在的主题
            if ($themeKey === $info->theme_key) {
                continue;
            }

            // 检查该主题下是否已存在相同 link 的 banner
            $exists = Banner::where('theme_key', $themeKey)
                ->where('link', $info->link)
                ->exists();

            if ($exists) {
                $skipped++;
                continue;
            }

            // 复制一份到该主题（使用原始属性，避免 accessor 处理过的 img）
            $new = $info->replicate();
            $new->theme_key = $themeKey;
            $new->save();
            $copied++;
        }

        return apiReturnSuc([
            'copied' => $copied,
            'skipped' => $skipped,
        ], '', "同步完成：新增 {$copied} 个，跳过 {$skipped} 个已存在");
    }
}
