<?php

namespace apexl\Utils\Arrays;

final readonly class Tree
{
    public static function create(
        array $flat,
        string $idField = 'id',
        int $root = 0
    ): array {
        $parents = [];
        foreach ($flat as $a) {
            $parents[$a->parent][] = $a;
        }

        return self::branch($parents, $parents[$root] ?? [], $idField);
    }

    private static function branch(array &$parents, array $children, string $idField): array
    {
        $tree = [];
        foreach ($children as $child) {
            $child = (array) $child;

            if (isset($parents[$child[$idField]])) {
                $child['children'] = self::branch(
                    $parents,
                    $parents[$child[$idField]],
                    $idField,
                );
            }
            $tree[] = $child;
        }

        return $tree;
    }
}
