<?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 buildTree(array $items, $parentId = null) {
        $branch = [];

        $filtered = array_filter($items, function($item) use ($parentId) {
            $p = empty($item['parentid']) ? null : (int)$item['parentid'];
            return $p === $parentId;
        });
        usort($filtered, function($a, $b) {
            $posA = isset($a['position']) ? (int)$a['position'] : 0;
            $posB = isset($b['position']) ? (int)$b['position'] : 0;
            return $posA <=> $posB;
        });

        foreach ($filtered as $item) {
            $item['children'] = buildTree($items, (int)$item['id']);
            $branch[] = $item;
        }

        return $branch;
    }
