<?php

declare(strict_types=1);


namespace Plugins\Neatstudio\Membership\Http;

use App\Models\Post;
use App\Models\User;
use Illuminate\Http\Request;
use Plugins\Neatstudio\Membership\Models\MembershipPlan;
use Plugins\Neatstudio\Membership\Models\Subscription;
use Plugins\Neatstudio\Membership\Services\MembershipService;
use Plugins\Neatstudio\Payment\Models\Payment;
use Plugins\Neatstudio\Payment\Services\PaymentManager;

class MembershipController
{
    public function __construct(private MembershipService $service, private PaymentManager $payment)
    {
    }

    public function index()
    {
        $plans = MembershipPlan::query()->where('active', true)->orderBy('sort')->get();

        return theme_view('membership.index', compact('plans'));
    }

    /**
     * 购买套餐：创建支付订单并跳转支付。
     */
    public function subscribe(Request $request, MembershipPlan $plan)
    {
        if (! $plan->active) {
            abort(404);
        }

        $user = $request->user();
        $channel = $request->input('channel', 'alipay');

        $payment = $this->payment->createOrder(
            $user,
            '会员套餐：'.$plan->name,
            $plan->price,
            $channel,
            'MembershipPlan#'.$plan->id
        );

        return redirect()->route('pay.checkout', $payment);
    }

    public function mine(Request $request)
    {
        $subscriptions = Subscription::query()
            ->where('user_id', $request->user()->id)
            ->with('plan')
            ->latest()
            ->get();

        return theme_view('membership.mine', compact('subscriptions'));
    }

    public function unlockPost(Request $request, Post $post)
    {
        // 单篇付费解锁：创建一笔定向支付
        $price = (int) ($post->meta['price'] ?? 0);

        if ($price <= 0) {
            abort(404);
        }

        $user = $request->user();
        $channel = $request->input('channel', 'alipay');

        $payment = $this->payment->createOrder(
            $user,
            '解锁文章：'.$post->title,
            $price,
            $channel,
            'PostUnlock#'.$post->id
        );

        return redirect()->route('pay.checkout', $payment);
    }

    public function userIsMember(?User $user = null): bool
    {
        return $this->service->isMember($user ?? auth()->user());
    }
}
