<?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 (deleteFileOrFolder($source)) {
        echo json_encode(['success' => true, "message" => "Обект $source успешно удален из корзины"], JSON_UNESCAPED_UNICODE);
    } else {
        echo json_encode(['success' => false, "message" => "Ошибка при удалении обекта"], JSON_UNESCAPED_UNICODE);
    }

}

function deleteFileOrFolder(string $path): bool {
    if (!file_exists($path)) {
        error_log("Путь не найден: $path");
        return false;
    }
    $trashDir = $_SERVER["DOCUMENT_ROOT"] . '/.trash';
    $metadataFile = $trashDir . DIRECTORY_SEPARATOR . basename($path) . '.metadata';

    if (file_exists($metadataFile)) {
        unlink($metadataFile);
    }

    if (is_dir($path)) {
        $items = array_diff(scandir($path), ['.', '..']);
        foreach ($items as $item) {
            $itemPath = $path . DIRECTORY_SEPARATOR . $item;
            if (!deleteFileOrFolder($itemPath)) {
                error_log("Не удалось удалить: $itemPath");
                return false;
            }
        }

        return rmdir($path);
    } else {
        return unlink($path);
    }

    return false;
}
