<?php

namespace App\Services;

use App\Models\DistAppearancePublishList;
use App\Models\SiteAppearanceTemplate;
use Illuminate\Support\Facades\Storage;

class TemplateUpdater
{
    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 ?? trim(config('liquid.template_name'));

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


        // 查询 dist_appearance_publish_list 表的记录
        $publishList = DistAppearancePublishList::where('dist_id', $dist->id)
            ->where('appearance_id', $dist->appearance_id)
            ->first();



        if (!$publishList) {
            return "No publishList templates found in dist_appearance_template for dist_id: $dist?->id, appearance_id: $dist?->appearance_id.";
        }
        // 获取 template_update_code
        $updateCode = $publishList->template_update_code;

        // 查询 dist_appearance_template 表,获取与该 dist_id 和 appearance_id 对应的所有模板文件
        $templates = SiteAppearanceTemplate::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) {
            // 如果文件名和路径不存在,生成默认值
            //$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($template->content, 'UTF-8', 'auto');


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

        }

        // 更新 dist_appearance_publish_list 的 template_local_code
        $publishList->template_local_code = $updateCode;
        $publishList->save();

        return "Templates updated successfully for dist_id: $dist->id and appearance_id: $dist->appearance_id.";
    }
}