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

    require_once($_SERVER["DOCUMENT_ROOT"] . '/engine/data/config.php');
    require_once($_SERVER["DOCUMENT_ROOT"] . "/engine/data/dbconfig.php");

    global $db_connect;

    $updateApi = "https://megadigital.space/engine/api/current_version/check_new_version.php?check";
    $response = file_get_contents($updateApi);
    $data = json_decode($response, true);

    if ($data && isset($data['update_url'])) {
        $zipUrl = $data['update_url'];
        $zipFile = "update.zip";

        $excludeList = [];
        if ($_POST["excludeLang"] == "true") {
            $excludeList = [
                "admin.lng", "fields.lng", "help.lng", "install.lng", "website.lng"
            ];
        }
        $excludeList = array_merge($excludeList, [".env"]);

        if ($_POST["excludeConfigFile"] == "true") {
            $excludeList = array_merge($excludeList, ["config.php", ".env", "ws_config.php"]);
        }
        if ($_POST["excludeTemplates"] == "true") {
            $excludeList = array_merge($excludeList, ["templates"]);
        }

        echo "Скачивание обновления...<br>";
        file_put_contents($zipFile, file_get_contents($zipUrl));

        echo "Распаковка...<br>";
        $zip = new ZipArchive;
        if ($zip->open($zipFile) === TRUE) {
            $zip->extractTo("update_tmp");
            $zip->close();
            unlink($zipFile);

            echo "Обновление файлов...<br>";

            copyFiles("update_tmp", $_SERVER["DOCUMENT_ROOT"], $excludeList);
            deleteFolder("update_tmp");

            $db_connect->update("client_version", [
                "version" => $data["version"]
            ], ["client_url[~]" => $_SERVER["HTTP_HOST"]]);

            echo "Обновление завершено!";
        } else {
            echo "Ошибка распаковки ZIP!";
        }
    }

    function deleteFolder($folder) {
        if (!is_dir($folder)) return false;

        foreach (scandir($folder) as $file) {
            if ($file === '.' || $file === '..') continue;

            $filePath = $folder . DIRECTORY_SEPARATOR . $file;

            if (is_dir($filePath)) {
                deleteFolder($filePath); // Рекурсивное удаление подпапок
            } else {
                unlink($filePath); // Удаляем файл
            }
        }

        return rmdir($folder); // Удаляем саму папку
    }

    function copyFiles($src, $dest, $excluded = []) {
        if (!is_dir($src)) return copy($src, $dest);

        if (!file_exists($dest)) mkdir($dest, 0755, true);

        foreach (scandir($src) as $file) {
            if ($file === '.' || $file === '..') continue;
            $srcPath = "$src/$file";
            $destPath = "$dest/$file";

            // Если файл или папка в списке исключений, пропускаем
            if (in_array($file, $excluded, true)) {
                echo "Пропущено: $srcPath<br>";
                continue;
            }

            // Проверяем, является ли путь папкой
            if (is_dir($srcPath)) {
                // Если папка в списке исключений, пропускаем
                if (in_array($file, $excluded, true)) {
                    echo "Пропущена папка: $srcPath<br>";
                    continue;
                }
                copyFiles($srcPath, $destPath, $excluded);
            } else {
                copy($srcPath, $destPath);
            }
        }
    }


