<?php

namespace App\Services;

use App\Services\LiquidTags\LiquidTagProduct;
use App\Services\LiquidTags\LiquidTagVideo;
use App\Services\LiquidTags\LiquidTagBanner;
use App\Services\LiquidTags\LiquidTagContactUs;
use Liquid\Liquid;
use Liquid\Template;
use Liquid\Cache\File as FileCache;


use App\Services\LiquidTags\LiquidTagPage;  // 添加对自定义标签的引用


use App\Services\LiquidFilters\Filters;
use App\Helpers\SiteCache;

class LiquidRenderer
{
    protected static ?string $baseTemplatePath = null;

    // 渲染 Liquid 模板
    public static function render(string $templateName, array $data = []): string
    {

        self::initializeLiquidSettings();
        self::initializeBaseTemplatePath();

        $template = self::createTemplateInstance();

        $template->registerTag('page', LiquidTagPage::class);
        $template->registerTag('product', LiquidTagProduct::class);
        $template->registerTag('video', LiquidTagVideo::class);
        $template->registerTag('contact', LiquidTagContactUs::class);
        $template->registerTag('banner', LiquidTagBanner::class);
        $template->registerTag('contactus', LiquidTagContactUs::class);
        $template->registerFilter(Filters::class);


        //获取全局配置,合并到当前配置
        $config = self::getGlobalConfig();
        $data['site'] = array_merge($data['site'] ?? [], $config);


        try {
            $parsedTemplate = $template->parseFile($templateName);
        } catch (\Exception $e) {
            throw new \RuntimeException("Template not found: {$templateName}", 0, $e);
        }

        return $parsedTemplate->render($data);
    }


    // 初始化基础模板路径
    private static function initializeBaseTemplatePath(): void
    {

        // 获取分销
        $dist=app('dist');


        // 使用默认值的函数封装，避免重复逻辑
        $template_dist_id = $dist->id ?? trim(config('liquid.template_dist_id'));
        $template_name = $dist->template_name ?? trim(config('liquid.template_name'));

        if (self::$baseTemplatePath === null) {
            self::$baseTemplatePath = rtrim(config('liquid.template_path'), '/') . '/' .
                trim($template_dist_id). '/' .
                ltrim($template_name, '/');
        }
    }

    // 创建模板实例
    private static function createTemplateInstance(): Template
    {
        $template = new Template(self::$baseTemplatePath);
        //$template->setCache(new FileCache(['cache_dir' => storage_path('framework/cache/data')]));
        return $template;
    }

    public static function getBaseTemplatePath(): string
    {
        // 确保路径已经初始化
        if (self::$baseTemplatePath === null) {
            self::initializeBaseTemplatePath();
        }

        return self::$baseTemplatePath;
    }

    // 设置 Liquid 渲染的全局配置
    private static function initializeLiquidSettings(): void
    {
        Liquid::set('INCLUDE_SUFFIX', '');
        Liquid::set('INCLUDE_PREFIX', '');
        Liquid::set('INCLUDE_ALLOW_EXT', true);
        Liquid::set('ESCAPE_BY_DEFAULT', true);
    }

    /**
     * 获取全局配置
     */
    private static function getGlobalConfig(): array
    {
        return [
            'site_title' => config('app.name'),
            'image_base_url' => config('liquid.image_base_url'),
            'asset_base_url' =>config('liquid.asset_base_url'),
            'font_base_url' => config('liquid.font_base_url'),
            'dist' => app('dist'),
            'menus_header'=>app('menus_header'),
            'menus_footer'=>app('menus_footer'),
        ];
    }
}
