<?php

namespace App\Services;

use App\Models\DistAppearancePublishList;
use App\Models\DistAppearanceTemplate;

class PreviewTemplateUpdater
{
    protected static ?string $baseTemplatePath = null;
    /**
     * 预览更新模板文件并更新数据库记录
     *
     * @param int $dist_id
     * @param int $appearance_id
     * @return string
     */
    public static function updateTemplates($dist): string
    {

        if(!$dist->appearance_id)
        {
            return "No appearance found for dist_id: $dist->id.";
        }

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

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


        // 查询 dist_appearance_template 表，获取与该 dist_id 和 appearance_id 对应的所有模板文件
        $templates = DistAppearanceTemplate::where('dist_id', $dist->id)
            ->where('appearance_id', $dist->appearance_id)
            ->get();


        if ($templates->isEmpty()) {
            return "No templates found in dist_appearance_template for dist_id: $dist->id, appearance_id: $dist->appearance_id.";
        }


        // 循环处理每个模板文件
        foreach ($templates as $template) {
            $content = self::contentChange($template->content,$template->template_code);
            // 如果文件名和路径不存在，生成默认值
            //$fileName = $template->file_name ?: "template_{$dist_id}_{$appearance_id}_{$template->id}.txt";
            $filePath = self::$baseTemplatePath.'/'.formatDirectory($template->file_path).$template->file_name;

            // 写入文件内容
            formatAndCreateAbsoluteDirectory($filePath);
            //// 强制转换内容为 UTF-8 编码
            $contentUtf8 = mb_convert_encoding($content, 'UTF-8', 'auto');

            // 写入文件内容，带 BOM
            file_put_contents($filePath, $contentUtf8);
        }
        return "";
    }

    /*
     * TODO: 模板内容增加 mtb_id 属性，用于区分不同模板
     */
    public static function contentChange($content,$templateCode)
    {

        $count = 1;
        $newContent = preg_replace_callback(
            '/(<[^>]+?mtb_edit=[\'"][^\'"]+[\'"][^>]*>)/',
            function ($matches) use (&$count, $templateCode) {
                // 在匹配到的 HTML 元素后添加 mtb_id 属性
                return preg_replace('/(mtb_edit=[\'"][^\'"]+[\'"])([^>]*)>/', '$1 mtb_id="' . $templateCode .'_'. $count++ . '"$2>', $matches[0]);
            },
            $content
        );


        return $newContent;
    }
}
