<?php

/**
 * 文件功能：节日福利后台管理控制器
 *
 * 管理员可在此创建、编辑、删除节日福利活动，
 * 也可手动立即触发活动，以及查看领取明细。
 *
 * @author  ChatRoom Laravel
 *
 * @version 1.0.0
 */

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Jobs\TriggerHolidayEventJob;
use App\Models\HolidayEvent;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;

class HolidayEventController extends Controller
{
    /**
     * 节日福利活动列表页。
     */
    public function index(): View
    {
        $events = HolidayEvent::query()
            ->orderByDesc('send_at')
            ->paginate(20);

        return view('admin.holiday-events.index', compact('events'));
    }

    /**
     * 新建活动表单页。
     */
    public function create(): View
    {
        return view('admin.holiday-events.create');
    }

    /**
     * 保存新活动。
     */
    public function store(Request $request): RedirectResponse
    {
        $data = $request->validate([
            'name' => 'required|string|max:100',
            'description' => 'nullable|string|max:500',
            'total_amount' => 'required|integer|min:1',
            'max_claimants' => 'required|integer|min:0',
            'distribute_type' => 'required|in:random,fixed',
            'min_amount' => 'nullable|integer|min:1',
            'max_amount' => 'nullable|integer|min:1',
            'fixed_amount' => 'nullable|integer|min:1',
            'send_at' => 'required|date',
            'expire_minutes' => 'required|integer|min:1|max:1440',
            'repeat_type' => 'required|in:once,daily,weekly,monthly,cron',
            'cron_expr' => 'nullable|string|max:100',
            'target_type' => 'required|in:all,vip,level',
            'target_value' => 'nullable|string|max:50',
            'enabled' => 'boolean',
        ]);

        $data['status'] = 'pending';
        $data['enabled'] = $request->boolean('enabled', true);

        HolidayEvent::create($data);

        return redirect()->route('admin.holiday-events.index')->with('success', '节日福利活动创建成功！');
    }

    /**
     * 编辑活动表单页。
     */
    public function edit(HolidayEvent $holidayEvent): View
    {
        return view('admin.holiday-events.edit', ['event' => $holidayEvent]);
    }

    /**
     * 更新活动。
     */
    public function update(Request $request, HolidayEvent $holidayEvent): RedirectResponse
    {
        $data = $request->validate([
            'name' => 'required|string|max:100',
            'description' => 'nullable|string|max:500',
            'total_amount' => 'required|integer|min:1',
            'max_claimants' => 'required|integer|min:0',
            'distribute_type' => 'required|in:random,fixed',
            'min_amount' => 'nullable|integer|min:1',
            'max_amount' => 'nullable|integer|min:1',
            'fixed_amount' => 'nullable|integer|min:1',
            'send_at' => 'required|date',
            'expire_minutes' => 'required|integer|min:1|max:1440',
            'repeat_type' => 'required|in:once,daily,weekly,monthly,cron',
            'cron_expr' => 'nullable|string|max:100',
            'target_type' => 'required|in:all,vip,level',
            'target_value' => 'nullable|string|max:50',
        ]);

        $holidayEvent->update($data);

        return redirect()->route('admin.holiday-events.index')->with('success', '活动已更新！');
    }

    /**
     * 切换活动启用/禁用状态。
     */
    public function toggle(HolidayEvent $holidayEvent): JsonResponse
    {
        $holidayEvent->update(['enabled' => ! $holidayEvent->enabled]);

        return response()->json([
            'ok' => true,
            'enabled' => $holidayEvent->enabled,
            'message' => $holidayEvent->enabled ? '已启用' : '已禁用',
        ]);
    }

    /**
     * 手动立即触发活动（管理员操作）。
     */
    public function triggerNow(HolidayEvent $holidayEvent): RedirectResponse
    {
        if ($holidayEvent->status !== 'pending') {
            return back()->with('error', '只有待触发状态的活动才能手动触发。');
        }

        // 设置触发时间为当前，立即入队
        $holidayEvent->update(['send_at' => now()]);
        TriggerHolidayEventJob::dispatch($holidayEvent);

        return back()->with('success', '活动已触发，请稍后刷新查看状态。');
    }

    /**
     * 删除活动。
     */
    public function destroy(HolidayEvent $holidayEvent): RedirectResponse
    {
        $holidayEvent->delete();

        return redirect()->route('admin.holiday-events.index')->with('success', '活动已删除。');
    }
}
