<?php
/*
    *****************************************************************************
    * MEGA Digital Space - by MEGA Digital Studio                               *
    * ------------------------------------------------------------------------- *
    * CMS Website:  https://megadigital.space                                   *
    * License:  https://megadigital.space/license                               *
    * Owner:  Giorgi Basharuli                                                  *
    * Contact:  online@megadigital.studio                                       *
    * MEGA Digital Studio – Official Development Studio for MEGA Digital Space  *
    * Website:  https://megadigital.studio                                      *
    * ------------------------------------------------------------------------- *
    * Description: This file is a part of the MEGA Digital Space CMS system.    *
    * Unauthorized distribution, modification, or commercial use is strictly -  *
    * prohibited without prior written permission.                              *
    * ------------------------------------------------------------------------- *
    * Copyright (c) 2023-2025 MEGA Digital Studio.                              *
    * All rights reserved.                                                      *
    *****************************************************************************
*/

function renderTempTpl($smarty, $content, $isFile = false) {
    global $user_id, $db_connect, $config, $ps_config, $smarty, $dispatcher, $lang;
    // Создаем временный файл в директории системы
    $tempFile = tempnam(sys_get_temp_dir(), 'tpl_') . '.tpl';

    // Извлекаем все include
    preg_match_all('/\{include file="([^"]+)"(.*?)\}/', $content, $matches, PREG_SET_ORDER);

    $includes = [];
    foreach ($matches as $match) {
        $includes[] = trim($match[0]);
    }
    $smarty->assign('lang', $lang);

    foreach ($includes as $include) {
        if (!preg_match('/customUniqName="([^"]+)"/', $include, $uniqNames)) {
            continue; // Если не найдено uniqName, пропускаем
        }

        $widgets = ["payment_widgets", "counters", "participations", "quiz", "walls"];
        $widgetData = [];

        foreach ($widgets as $widgetName) {
            $data = $db_connect->get($widgetName, "*", ["uniq_name" => $uniqNames[1]]);
            if (!empty($data)) {
                if ($widgetName == "payment_widgets" && !empty($data["price"])) {
                    $data["price"] = convertAmount($data["price"], $config["payment_info"]["default_currency"], getCurrentCurrency());
                }

                $data = $dispatcher->dispatch("smarty.render.$widgetName", $data) ?? $data;
                $data = $data["widgetData"] ?? $data;

                $widgetData = $data;
                if (!empty($widgetData)) {
                    $smarty->assign("widgetData", $widgetData);

                    $timingFile = tempnam(sys_get_temp_dir(), 'tpl_') . '.tpl';
                    file_put_contents($timingFile, $include);

                    try {
                        $smarty->assign('disableFilter', true); // Отключаем фильтр

                        $widgetHtml = $smarty->fetch($timingFile);
                        $smarty->clearAssign('disableFilter'); // Включаем обратно

                        $content = str_replace($include, $widgetHtml, $content);

                    } finally {
                        unlink($timingFile);
                    }
                }
            } // Нашли данные – выходим из цикла
            }
        }



    // Записываем переданный контент в файл
    file_put_contents($tempFile, $content);


    if ($isFile === true) {
        return $content;
    }
    if (isset($_GET["status"])) {
        $smarty->assign("status", $_GET["status"]);
    } else {
        $smarty->assign("status", "");
    }
    $smarty->assign("config", $config);
    $smarty->assign("payment_configs", $ps_config);
    $smarty->assign('userId', $user_id);
    $smarty->assign('disableFilter', true); // Отключаем фильтр

    $html = $smarty->fetch($tempFile);
    $smarty->clearAssign('disableFilter'); // Включаем обратно

    // Удаляем временный файл
    unlink($tempFile);

    // Возвращаем сгенерированный HTML и список include
    return $html;
}
