<?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();

        // 已有该套餐的有效订阅：直接返回我的订阅页，避免重复支付
        $active = Subscription::query()
            ->where('user_id', $user->id)
            ->where('membership_plan_id', $plan->id)
            ->where('status', 'active')
            ->where('ends_at', '>', now())
            ->exists();

        if ($active) {
            return redirect()->route('membership.mine');
        }

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

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

        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)
    {
        $user = $request->user();

        // 已能读付费内容（会员 / 作者 / 已解锁）：直接查看文章，避免重复支付。
        // 注意：付费块文章的整篇是公开的，不能用 canReadPost 判断（否则永远"已有权限"）
        if ($this->service->canReadPaidContent($user, $post)) {
            return redirect()->route('posts.show', $post->slug ?? $post->id);
        }

        // 单篇付费解锁：创建一笔定向支付
        $price = (int) ($post->meta['price'] ?? 0);

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

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

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

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

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