<?php

/**
 * 文件功能：后台签到奖励规则管理控制器
 *
 * 提供连续签到奖励档位的列表、新增、编辑、启停和删除功能。
 */

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\SaveSignInRewardRuleRequest;
use App\Models\SignInRewardRule;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\View\View;

/**
 * 类功能：管理后台每日签到奖励规则。
 */
class SignInRewardRuleController extends Controller
{
    /**
     * 方法功能：展示签到奖励规则列表。
     */
    public function index(): View
    {
        $rules = SignInRewardRule::query()
            ->orderBy('sort_order')
            ->orderBy('streak_days')
            ->get();

        return view('admin.sign-in-rules.index', compact('rules'));
    }

    /**
     * 方法功能：新增签到奖励规则。
     */
    public function store(SaveSignInRewardRuleRequest $request): RedirectResponse
    {
        SignInRewardRule::query()->create($this->payload($request));

        return redirect()->route('admin.sign-in-rules.index')->with('success', '签到奖励规则已创建。');
    }

    /**
     * 方法功能：更新签到奖励规则。
     */
    public function update(SaveSignInRewardRuleRequest $request, SignInRewardRule $signInRewardRule): RedirectResponse
    {
        $signInRewardRule->update($this->payload($request));

        return redirect()->route('admin.sign-in-rules.index')->with('success', '签到奖励规则已更新。');
    }

    /**
     * 方法功能：切换签到奖励规则启用状态。
     */
    public function toggle(SignInRewardRule $signInRewardRule): JsonResponse
    {
        $signInRewardRule->update(['is_enabled' => ! $signInRewardRule->is_enabled]);

        return response()->json([
            'ok' => true,
            'is_enabled' => $signInRewardRule->is_enabled,
            'message' => $signInRewardRule->is_enabled ? '规则已启用。' : '规则已停用。',
        ]);
    }

    /**
     * 方法功能：删除签到奖励规则。
     */
    public function destroy(SignInRewardRule $signInRewardRule): RedirectResponse
    {
        $signInRewardRule->delete();

        return redirect()->route('admin.sign-in-rules.index')->with('success', '签到奖励规则已删除。');
    }

    /**
     * 方法功能：整理后台表单提交的数据。
     *
     * @return array<string, mixed>
     */
    private function payload(SaveSignInRewardRuleRequest $request): array
    {
        $data = $request->validated();
        $data['is_enabled'] = $request->boolean('is_enabled');

        foreach (['identity_badge_code', 'identity_badge_name', 'identity_badge_icon', 'identity_badge_color'] as $field) {
            $data[$field] = filled($data[$field] ?? null) ? trim((string) $data[$field]) : null;
        }

        return $data;
    }
}
