<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
use App\Helpers\SiteCache;
use App\Services\TemplateUpdater;
use App\Services\LiquidRenderer;
/**
 * Class LoadDistData 用中间件来获取distm网店信息
 */
class LoadDistData
{
    /**
     * Handle an incoming request.
     *
     * @param
     */
    public function handle(Request $request, Closure $next): Response
    {


        // 获取请求的域名
        $domain = getHost();

        // 从缓存中获取站点配置并反序列化
        $dist = SiteCache::getDist($domain);
        $dist = $dist ? unserialize($dist) : null;

        // 如果找不到匹配的数据，直接返回404响应
        if (!$dist) {
            abort(404, 'site not found.');
        }

        // 检查模板是否需要更新
        if(!empty($dist?->publishList?->template_update_code)) {
            if (
                !$dist?->publishList?->template_local_code ||
                $dist?->publishList?->template_update_code !== $dist?->publishList?->template_local_code
            ) {

                // dd('update template');
                // 更新模板
                TemplateUpdater::updateTemplates($dist);

                // 清除缓存并重新获取
                SiteCache::clearDistCache($domain);
                $dist = SiteCache::getDist($domain);
                $dist = $dist ? unserialize($dist) : null;

                if (!$dist) {
                    abort(404, 'site not found.');
                }
            }
        }


        // 全局共享  数据
        app()->instance('dist', $dist);
        // 将找到的 dist 数据添加到请求中，方便后续使用
        //$request->attributes->set('dist', $dist);

        $menus_header=SiteCache::getMenu($domain,0,$dist->id);
        $menus_footer=SiteCache::getMenu($domain,1,$dist->id);

        app()->instance('menus_header', $menus_header);// 头部菜单
        app()->instance('menus_footer', $menus_footer);// 底部菜单

        return $next($request);
    }
}
