<?php

declare(strict_types=1);


namespace Plugins\Neatstudio\Membership;

use App\Blog\Support\PluginManager;
use App\Blog\Support\PluginServiceProvider;
use Illuminate\Support\Str;
use Plugins\Neatstudio\Membership\Models\MembershipPlan;
use Plugins\Neatstudio\Membership\Models\Subscription;
use Plugins\Neatstudio\Payment\Models\Payment;

class ServiceProvider extends PluginServiceProvider
{
    protected function boot(PluginManager $manager): void
    {
        $this->loadRoutes(__DIR__.'/../routes/web.php');

        // 支付成功：激活会员订阅 / 解锁单篇付费文章
        $manager->addAction('payment.paid', function (Payment $payment) {
            $description = (string) $payment->description;
            $user = $payment->user;

            if (! $user) {
                return;
            }

            if (str_starts_with($description, 'MembershipPlan#')) {
                $planId = (int) substr($description, strlen('MembershipPlan#'));
                $plan = MembershipPlan::find($planId);

                if ($plan) {
                    $now = now();
                    Subscription::create([
                        'user_id' => $user->id,
                        'membership_plan_id' => $plan->id,
                        'status' => 'active',
                        'starts_at' => $now,
                        'ends_at' => $now->copy()->addDays($plan->duration_days),
                    ]);
                }
            }

            if (str_starts_with($description, 'PostUnlock#')) {
                $postId = (int) substr($description, strlen('PostUnlock#'));
                $post = \App\Models\Post::find($postId);

                if ($post) {
                    $meta = $post->meta ?? [];
                    $unlocked = $meta['unlocked_user_ids'] ?? [];
                    $unlocked[] = $user->id;
                    $post->update(['meta' => array_merge($meta, ['unlocked_user_ids' => array_values(array_unique($unlocked))])]);
                }
            }
        }, 10);

        // 付费文章：[paid]...[/paid] 对无权限访客隐藏
        $manager->addFilter('post.rendered', function (string $html, \App\Models\Post $post) {
            $service = app(Services\MembershipService::class);
            $user = auth()->user();

            if (preg_match('/\[paid\](.*?)\[\/paid\]/s', $html) && ! $service->canReadPaidContent($user, $post)) {
                $html = preg_replace(
                    '/\[paid\](.*?)\[\/paid\]/s',
                    '<div class="paid-teaser">（付费内容已隐藏，开通会员或单篇解锁后可见）</div>',
                    $html
                );
            }

            if (! $service->canReadPost($user, $post)) {
                return '<div class="paid-teaser">（本文章为会员专享，开通会员后可见）</div>';
            }

            return $html;
        }, 10);
    }
}
