<?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");
    require_once($_SERVER["DOCUMENT_ROOT"] . '/engine/data/ws_config.php');

    session_start();

    global $db_connect, $ws_config;

    header('Content-Type: application/json');

    function saveStructure(array $items,$db, $parentId = 0) {
        foreach ($items as $position => $item) {
            $id = (int)$item['id'];

            // Обновляем parentid и позицию
            $db->update($_POST["moduleName"].'_categories', [
                'parentid' => $parentId,
                'position' => $position
            ], [
                'id' => $id
            ]);

            // Рекурсивно обрабатываем детей
            if (!empty($item['children'])) {
                saveStructure($item['children'], $db, $id);
            }
        }
    }

    // Получаем JSON от JS
    $structure = json_decode($_POST['structure'], true);

    saveStructure($structure, $db_connect);

    echo json_encode(['success' => true]);