<?php

namespace App\Services;

use App\Services\LiquidTags\LiquidTagCollection;
use Illuminate\Support\Facades\Cache;
use App\Http\Controllers\ProductController;
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 $cacheKey = null): string
    {

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



        // 如果提供了缓存键,则检查和设置缓存
        if (config('liquid.cache_enabled')&&$cacheKey) {
            $cacheDuration = config('liquid.cache_duration', 300); // 默认缓存时间为 300 秒

            // 检查缓存是否存在
            $domain=app('dist')->domain;
            if(!$domain)
            {
                abort('403');
            }
            return Cache::tags([$domain, 'dist'])->remember("liquid_{$cacheKey}", $cacheDuration, function () use ($templateName, $data) {
                return self::processTemplate($templateName, $data);
            });
        }

        // 如果没有提供缓存键,直接渲染模板
        return self::processTemplate($templateName, $data);


    }


    // 处理模板渲染逻辑
    private static function processTemplate(string $templateName, array $data): string
    {
        $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->registerTag('collection', LiquidTagCollection::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);
        }

        $now_string=date('Y-m-d H:i:s');
        return $parsedTemplate->render($data);//."<!-- CACHE {$now_string}-->";
    }

    // 初始化基础模板路径
    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) {
            $preview = isset($_GET['mtb-preview']) ? $_GET['mtb-preview'] : false;
            if ($preview) {
                self::$baseTemplatePath = rtrim(config('liquid.preview_template_path'), '/') . '/' .
                    trim($template_dist_id). '/' .
                    ltrim($template_name, '/');
            } else {
                self::$baseTemplatePath = rtrim(config('liquid.template_path'), '/') . '/' .
                    trim($template_dist_id). '/' .
                    ltrim($template_name, '/');
            }
        }
    }

    // 创建模板实例
    private static function createTemplateInstance(): Template
    {
        $template = new Template(self::$baseTemplatePath);
        // 检查配置文件是否启用缓存
        $enableCache = config('liquid.cache_enabled', false); // 默认不开启缓存
        if ($enableCache) {
            $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
    {
        $preview = isset($_GET['mtb-preview']) ? intval($_GET['mtb-preview']) : 0;
        //dd($preview);
        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'),
            'current_url'=>app('current_url'),
            'mtb_preview' => $preview,
        ];
    }
}