<?php

/**
 * 文件功能：前台婚礼控制器
 *
 * 处理婚礼设置（档位选择/时间/付款方）、婚礼触发、红包领取。
 * 所有操作通过 WeddingService 执行。
 *
 * @author  ChatRoom Laravel
 *
 * @version 1.0.0
 */

namespace App\Http\Controllers;

use App\Events\WeddingCelebration;
use App\Models\Marriage;
use App\Models\WeddingCeremony;
use App\Services\WeddingService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class WeddingController extends Controller
{
    public function __construct(
        private readonly WeddingService $wedding,
    ) {}

    /**
     * 获取可用的婚礼档位列表（前台设置弹窗用）。
     */
    public function tiers(): JsonResponse
    {
        return response()->json([
            'tiers' => $this->wedding->activeTiers()->map(fn ($t) => [
                'id' => $t->id,
                'tier' => $t->tier,
                'name' => $t->name,
                'icon' => $t->icon,
                'amount' => $t->amount,
                'description' => $t->description,
            ]),
        ]);
    }

    /**
     * 设置并发起婚礼（结婚后由接受方配置）。
     */
    public function setup(Request $request, Marriage $marriage): JsonResponse
    {
        $user = $request->user();

        // 只有婚姻双方可设置
        if (! $marriage->involves($user->id)) {
            return response()->json(['ok' => false, 'message' => '无权操作此婚姻。'], 403);
        }
        if ($marriage->status !== 'married') {
            return response()->json(['ok' => false, 'message' => '婚姻状态异常。'], 422);
        }

        $data = $request->validate([
            'tier_id' => 'required|integer|exists:wedding_tiers,id',
            'payer_type' => 'required|in:groom,joint',
        ]);

        // 固定立即举办，不再接受 scheduled 选项
        $result = $this->wedding->setup(
            $marriage,
            $data['tier_id'],
            $data['payer_type'],
            'immediate',
            null,
        );

        // 立即触发婚礼庆典并广播
        if ($result['ok']) {
            $ceremony = WeddingCeremony::find($result['ceremony_id']);
            if ($ceremony) {
                $this->wedding->trigger($ceremony);
                broadcast(new WeddingCelebration($ceremony, $marriage));
            }
        }

        return response()->json($result);
    }

    /**
     * 领取婚礼红包。
     */
    public function claim(Request $request, WeddingCeremony $ceremony): JsonResponse
    {
        $result = $this->wedding->claim($ceremony, $request->user());

        return response()->json($result);
    }

    /**
     * 查询用户在婚礼中是否有待领取红包。
     */
    public function envelopeStatus(Request $request, WeddingCeremony $ceremony): JsonResponse
    {
        $claim = $this->wedding->getUnclaimedEnvelope($ceremony, $request->user()->id);

        return response()->json([
            'has_envelope' => $claim !== null,
            'amount' => $claim?->amount ?? 0,
            'expires_at' => $ceremony->expires_at,
        ]);
    }

    /**
     * 查询当前用户所有未领取且未过期的婚礼红包（页面刷新后恢复领取按钮用）。
     */
    public function pendingEnvelopes(Request $request): JsonResponse
    {
        $userId = $request->user()->id;

        // 查询有未领取 claim 的 active 婚礼（未过期）
        $claims = \App\Models\WeddingEnvelopeClaim::query()
            ->where('user_id', $userId)
            ->where('claimed', false)
            ->with(['ceremony.marriage.user', 'ceremony.marriage.partner', 'ceremony.tier'])
            ->get()
            ->filter(fn ($c) => $c->ceremony
                && in_array($c->ceremony->status, ['active'])
                && (! $c->ceremony->expires_at || $c->ceremony->expires_at->isFuture()))
            ->values();

        return response()->json([
            'envelopes' => $claims->map(fn ($c) => [
                'ceremony_id' => $c->ceremony_id,
                'amount' => $c->amount,
                'total_amount' => $c->ceremony->total_amount,
                'groom' => $c->ceremony->marriage->user->username ?? '—',
                'bride' => $c->ceremony->marriage->partner->username ?? '—',
                'tier_name' => $c->ceremony->tier?->name ?? '婚礼',
                'tier_icon' => $c->ceremony->tier?->icon ?? '🎊',
                'expires_at' => $c->ceremony->expires_at?->toDateTimeString(),
            ]),
        ]);
    }
}
