<?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 backupSelectedFiles($backupName, $filesAndFolders) {
        $zip = new ZipArchive();
        $zipFile = __DIR__ . '/' . $backupName;

        if ($zip->open($zipFile, ZipArchive::CREATE | ZipArchive::OVERWRITE) !== true) {
            die("Не удалось создать архив: " . $zip->getStatusString());
        }

        $thisScript = realpath(__FILE__);
        $basePath = realpath($_SERVER["DOCUMENT_ROOT"]) . DIRECTORY_SEPARATOR; // Базовый путь проекта

        foreach ($filesAndFolders as $item) {
            $realPath = realpath($item);
            if (!$realPath || $realPath === $thisScript || $realPath === $zipFile) continue;

            if (is_dir($realPath)) {
                addFolderToZip($realPath, $zip, $basePath);
            } elseif (is_file($realPath)) {
                $localPath = substr($realPath, strlen($basePath)); // Сохраняем полный путь относительно корня проекта
                $zip->addFile($realPath, $localPath);
            }
        }

        $zip->close();

        if (file_exists($zipFile)) {
            header('Content-Type: application/zip');
            header('Content-Disposition: attachment; filename="' . basename($zipFile) . '"');
            header('Content-Length: ' . filesize($zipFile));
            readfile($zipFile);
            unlink($zipFile);
            exit;
        } else {
            die("Ошибка создания архива");
        }
    }

    function addFolderToZip($folder, $zip, $basePath) {
        $files = new RecursiveIteratorIterator(
            new RecursiveDirectoryIterator($folder, RecursiveDirectoryIterator::SKIP_DOTS),
            RecursiveIteratorIterator::SELF_FIRST
        );

        foreach ($files as $file) {
            $realPath = $file->getRealPath();
            if ($realPath === false) continue;

            $localPath = substr($realPath, strlen($basePath)); // Полный путь относительно корня проекта

            if ($file->isDir()) {
                $zip->addEmptyDir($localPath);
            } else {
                $zip->addFile($realPath, $localPath);
            }
        }
    }



// Использование
    $backupName = 'backup_' . date('Y-m-d_H-i-s') . '.zip';
    $filesAndFolders = [
        "demo", "docs", "engine", "system", "templates", "uploads", ".htaccess",
        "admin.php", "Autoloader.php", "check_license.php", "composer.json", "composer.lock",
        "index.php", "install.php", "robots.txt"
    ];
    backupSelectedFiles($backupName, $filesAndFolders);
