<?php

namespace App\Services\Models;

use App\Models\Category;
use Illuminate\Support\Collection;

class CategoryService
{
    public static function buildTree($categories = null, $parentId = 0): array
    {
        if ($categories == null)
            $categories = Category::all();

        $branch = [];

        foreach ($categories as $category) {
            if ($category->parent_id == $parentId) {
                $category->image = $category->image_url;
                $children = self::buildTree($categories, $category->id);
                if ($children) {
                    $category->children = $children;
                } else {
                    $category->children = null;
                }
                $branch[] = $category;
            }
        }

        return $branch;
    }
    public static function getChildrenById($tree, $id): array
    {
        foreach ($tree as $node) {
            if ($node->id == $id) {
                return self::flattenTree($node->children);
            }

            if (!empty($node->children)) {
                $result = self::getChildrenById($node->children, $id);
                if (!empty($result)) {
                    return $result;
                }
            }
        }

        return [];
    }

    private static function flattenTree($tree): array
    {
        $result = [];

        if ($tree === null) {
            return $result;
        }

        foreach ($tree as $node) {
            $result[] = $node;
            if (!empty($node->children)) {
                $result = array_merge($result, self::flattenTree($node->children));
            }
        }

        return $result;
    }

    public static function getCategoriesParents(Category|int $category): Collection
    {
        $category = $category instanceof Category ? $category : Category::find($category);

        $parents = collect();
        $parents->push($category);
        $currentCategory = $category;

        while ($currentCategory->parent_id) {
            $parent = Category::find($currentCategory->parent_id);
            if ($parent) {
                $parents->push($parent);
                $currentCategory = $parent;
            } else {
                break;
            }
        }

        return $parents;
    }
}
