<?php

declare(strict_types=1);

namespace App\Providers;

use Filament\Facades\Filament;
use Filament\View\PanelsRenderHook;
use Illuminate\Support\Facades\Blade;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     */
    public function register(): void
    {
        //
    }

    private function registerMarketPurchaseListener(): void
    {
        $manager = app(\App\Blog\Support\PluginManager::class);

        if (! $manager->isEnabled('neatstudio.payment')) {
            return;
        }

        $manager->addAction('payment.paid', function (\Plugins\Neatstudio\Payment\Models\Payment $payment) {
            $payable = $payment->payable;

            if ($payable instanceof \App\Models\MarketPackage) {
                $payable->markPaid($payment);
            }
        }, 10);
    }

    /**
     * Bootstrap any application services.
     */
    public function boot(): void
    {
        // 自动加载所有插件的迁移（插件目录下 database/migrations）
        foreach (glob(base_path('plugins/*/database/migrations')) ?: [] as $path) {
            $this->loadMigrationsFrom($path);
        }

        // 商城付费：支付成功标记市场商品已购（仅当支付插件启用时注册）
        $this->registerMarketPurchaseListener();

        // 前台页面缓存（匿名 GET，缓存含 SEO 注入后的最终 HTML）
        app('router')->pushMiddlewareToGroup('web', \App\Blog\Support\PageCacheMiddleware::class);

        // 后台紧凑化：侧边栏 + 表格行 + 筛选区（Filament 无官方全局紧凑开关，用 CSS 收紧）
        Filament::serving(function () {
            Filament::registerRenderHook(
                PanelsRenderHook::STYLES_AFTER,
                fn () => Blade::render(<<<'HTML'
<style>
    .fi-sidebar { padding-inline: 0.75rem; }
    .fi-sidebar-nav { padding-inline: 0; }
    .fi-sidebar-nav-groups { margin-inline: 0; }
    .fi-sidebar-nav .fi-sidebar-item-button { padding-inline: 0.6rem; border-radius: 0.5rem; }
    .fi-sidebar-nav .fi-sidebar-item-label { font-size: 0.82rem; }
    .fi-sidebar-nav .fi-sidebar-group-label { font-size: 0.68rem; letter-spacing: 0.04em; }
    .fi-sidebar-brand { padding-block: 0.9rem; }

    /* 表格行紧凑：行高由选择列/表头驱动，数据单元格默认无 padding 不要加 */
    .fi-ta-header-cell { padding-block: calc(var(--spacing) * 2) !important; }
    .fi-ta-selection-cell { padding-block: calc(var(--spacing) * 1.75) !important; }
    .fi-ta-header-toolbar { padding-block: 0.5rem !important; }

    /* 筛选条件区（Above 布局）收紧为一行：隐藏标题、压缩留白 */
    .fi-ta-filters-above-content-ctn { padding: 0.4rem 0.9rem !important; }
    .fi-ta-filters-heading { display: none !important; }
    .fi-ta-filters-header { margin-bottom: 0.2rem !important; }
</style>
HTML)
            );
        });
    }
}
