<?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");

$sourceList = $_POST['selectedData'] ?? '';

foreach ($sourceList as $sourceAssoc) {
    $source = $_SERVER["DOCUMENT_ROOT"] . "/" . $sourceAssoc["dataPath"];

    if (!file_exists($source)) {
        echo json_encode(['success' => false, "message" => "Путь $source не найден"], JSON_UNESCAPED_UNICODE);
        exit;
    }

    if (restoreFromTrash($source)) {
        echo json_encode(['success' => true, "message" => "Обект $source успешно востановлен"], JSON_UNESCAPED_UNICODE);
    } else {
        echo json_encode(['success' => false, "message" => "Ошибка при востановления обекта"], JSON_UNESCAPED_UNICODE);
    }

}

function restoreFromTrash($path) {
    $trashDir = $_SERVER["DOCUMENT_ROOT"] . '/.trash';  // Папка корзины
    $metadataFile = $trashDir . DIRECTORY_SEPARATOR . basename($path) . '.metadata';

    if (!file_exists($metadataFile)) {
        return false;
    }

    $metadata = json_decode(file_get_contents($metadataFile), true);
    $originalPath = $metadata['original_path'];

    if (file_exists($originalPath)) {
        return false;
    }

    $originalDir = dirname($originalPath);
    if (!is_dir($originalDir)) {
        mkdir($originalDir, 0777, true);
    }

    $restorePath = $originalDir . DIRECTORY_SEPARATOR . basename($path);

    if (is_dir($trashDir . DIRECTORY_SEPARATOR . basename($path))) {
        renameDirectoryRecursive($trashDir . DIRECTORY_SEPARATOR . basename($path), $restorePath);
    } else {
        rename($trashDir . DIRECTORY_SEPARATOR . basename($path), $restorePath);
    }

    unlink($metadataFile);

    return true;
}

function renameDirectoryRecursive($sourceDir, $targetDir) {
    if (!is_dir($sourceDir)) {
        return false;
    }

    if (!@mkdir($targetDir, 0777, true)) {
        return false;
    }

    $items = scandir($sourceDir);
    foreach ($items as $item) {
        if ($item === '.' || $item === '..') continue;

        $sourcePath = $sourceDir . DIRECTORY_SEPARATOR . $item;
        $targetPath = $targetDir . DIRECTORY_SEPARATOR . $item;

        if (is_dir($sourcePath)) {
            renameDirectoryRecursive($sourcePath, $targetPath);
        } else {
            rename($sourcePath, $targetPath);
        }
    }

    return rmdir($sourceDir);
}
