<?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.                                                      *
    *****************************************************************************
*/

$tplDirectory = $_GET["path"] ?? str_replace("/main.tpl", "", $_GET["tpl_file"] ?? "");

$subAction = isset($_GET['sub_action']) ? $_GET['sub_action'] : '';
if ($subAction === 'edit') {
    $tplFile = isset($_GET['tpl_file']) ? $_GET['tpl_file'] : '';

    if (!empty($tplFile)) {
        $tplContent = file_get_contents($tplFile);
        $tplContentEscaped = htmlspecialchars($tplContent, ENT_QUOTES, 'UTF-8');
        $smarty->assign('tpl_file', $tplFile);
        $smarty->assign('tpl_content', $tplContentEscaped);
    }
} elseif ($subAction === 'save') {
    $tplFile = isset($_POST['tpl_file']) ? $_POST['tpl_file'] : '';
    $tplContent = isset($_POST['tpl_content']) ? $_POST['tpl_content'] : '';
    if (!empty($tplFile)) {
        $tplFilePath = $_SERVER["DOCUMENT_ROOT"] . "/" . $tplDirectory . $tplFile;
        if (!is_writable($tplFilePath)) {
            if (!chmod($tplFilePath, 0666)) {
                echo "Не удалось изменить права на файл.";
                exit;
            }
        }

        if (!is_writable($tplFilePath)) {
            echo "Нет прав на запись в директорию: $tplFilePath";
            exit;
        }

        if (!file_put_contents($tplFilePath, htmlspecialchars_decode($tplContent, ENT_QUOTES))) {
            echo "Не удалось записать в файл: $tplFilePath\n";

            // Дополнительная информация о причине ошибки
            $error = error_get_last();
            echo "Ошибка: " . $error['message'] . "\n";
            exit;
        }
        // Отправляем сообщение об успешном сохранении
        echo 'Файл успешно сохранен.';
        exit;
    }
}

function getTplFilesRecursive($directory, $baseDir = '', $excludedFolders = []) {
    $items = [
        'folders' => [],
        'files' => []
    ];
    $files = scandir($directory);
    foreach ($files as $file) {
        if (in_array($file, $excludedFolders, true)) {
            continue;
        }
        $filePath = $directory . '/' . $file;
        $relativePath = ltrim($baseDir . '/' . $file, '/');
        if (is_dir($filePath)) {
            // Добавляем папки
            $items['folders'][$file] = getTplFilesRecursive($filePath, $relativePath, $excludedFolders);
        } elseif (pathinfo($file, PATHINFO_EXTENSION) === 'tpl' || pathinfo($file, PATHINFO_EXTENSION) == "js" || pathinfo($file, PATHINFO_EXTENSION) == "css") {
            // Добавляем файлы
            $items['files'][] = $relativePath;
        }
    }

    // Сортируем папки и файлы
    ksort($items['folders']);
    sort($items['files']);

    return $items;
}

// Получение структуры шаблонов
$tplFiles = getTplFilesRecursive($_GET["path"] ?? str_replace(["/main.tpl", "/css/main.css", "/js/main.js"], "", $_GET["tpl_file"]), '', [".", ".."]);
$smarty->assign('tpl_files', $tplFiles);
$smarty->assign('tplDirectory', $tplDirectory);
$yourData = array('title' => "Редактирование email шаблона" . ' - ' . $config['title']);
$smarty->assign('data', $yourData);
$smarty->assign('page_name', '
        <li class="breadcrumb-item active">' . $lang['nav']['websitetemplates'] . '</li>
    ');