<?php

declare(strict_types=1);

namespace Plugins\Demo\HelloWorld;

use App\Blog\Support\PluginManager;
use App\Blog\Support\PluginServiceProvider;
use App\Models\Comment;
use App\Models\Post;
use App\Models\Setting;
use Filament\Forms\Components\TextInput;
use Filament\Schemas\Components\Section;
use Filament\Schemas\Schema;
use Illuminate\Support\Facades\Log;
use Plugins\Demo\HelloWorld\Models\HelloWorldLog;

class ServiceProvider extends PluginServiceProvider
{
    protected function boot(PluginManager $manager): void
    {
        // 1. 加载前台路由（可选）
        $this->loadRoutes(__DIR__.'/../routes/web.php');

        // 2. 注册视图命名空间（可选）：views/ -> demo-hello::xxx
        $this->loadViews(__DIR__.'/../views', 'demo-hello');

        // 3. 过滤器示例：文章渲染时把 [hello xxx] 短代码替换为问候语
        $manager->addFilter('post.rendered', function (string $html, Post $post) {
            $greeting = (string) Setting::get('hello_world_greeting', '你好');

            return preg_replace_callback(
                '/\[hello\s+([^\]]+)\]/',
                fn (array $m) => '<span class="hello-world">'.$greeting.'，'.e($m[1]).'！</span>',
                $html
            );
        }, 20);

        // 4. 动作示例：新评论创建时写日志（演示数据关联 + 钩子监听）
        $manager->addAction('comment.created', function (Comment $comment) {
            HelloWorldLog::create([
                'comment_id' => $comment->id,
                'note' => '捕获新评论：'.mb_substr($comment->content, 0, 30),
            ]);
            Log::info('HelloWorld: 捕获新评论 #'.$comment->id);
        });

        // 5. 后台表单注入示例：给文章编辑页加一个演示字段（meta.demo_note）
        $manager->addAction('filament.post_form', function (Schema $schema) {
            $schema->components([
                ...$schema->getComponents(),
                Section::make('Hello World 演示')
                    ->collapsible()
                    ->schema([
                        TextInput::make('meta.demo_note')
                            ->label('演示字段（存到文章 meta）')
                            ->helperText('这是插件注入的字段，停用插件后消失'),
                    ]),
            ]);
        });
    }
}
