<?php

namespace Services\dtos;

class CategoryChildrenDto
{
    public readonly int $id;
    public readonly int $parent_id;
    public readonly string $link;
    public readonly string $title;
    public array $children;

    public function __construct(int $id, int $parent_id, string $link, string $title)
    {
        $this->id = $id;
        $this->link = $link;
        $this->title = $title;
        $this->parent_id = $parent_id;
        $this->children = [];
    }

    /**
     * @param CategoryChildrenDto[] $all_categories
     * @return CategoryChildrenDto[]
     */
    public static function buildHierarchy(array $all_categories, int $category_id = 0): array
    {
        $parents = [];
        foreach ($all_categories as $category) {
            if ($category->parent_id === 0)
                $parents[] = $category;
            foreach ($all_categories as $child) {
                if ($child->parent_id == $category->id) {
                    $category->children[] = $child;
                }
            }
        }

        if (!empty($category_id)) {
            // Remove none related section of tree
            $find_id = $category_id;
            $child = null;
            for ($i = 0; $i < sizeof($all_categories); $i++) {
                if ($all_categories[$i]->id === $find_id) {
                    if (!empty($child)){
                        $all_categories[$i]->children = [$child];
                    }
                    $child = $all_categories[$i];

                    if (!empty($all_categories[$i]->parent_id)) {
                        $find_id = $all_categories[$i]->parent_id;
                        $i = -1;
                    }
                    else {
                        return [$child];
                    }
                }
            }
        }

        return $parents;
    }
}