<?php
namespace Dashboard\Services;

class CategoryService
{
  public static function buildTree($categories, $parent_id = 0): array
  {
    $tree = [];

    foreach ($categories as $category) {
      if ($category['parentID'] == $parent_id) {
        $categoryNode = $category;

        $categoryNode["subcategories"] = self::buildTree($categories, $category['id']);

        $tree[] = $categoryNode;
      }
    }

    return $tree;
  }

  public static function getCategoryList($products = [], $categoryIDs = [], $separator = " / ")
  {
    global $categoryList;
    foreach ($categoryIDs as $categoryID) {
      if (isset($categoryList[$categoryID])) continue;

      $categoryList[$categoryID] = implode($separator, array_reverse(getCategoryListRecursive($categoryID)));
    }

    return array_map(function ($product) use ($categoryList) {
      $product["categoryList"] = $categoryList[$product["categoryID"]];
      return $product;
    }, $products);
  }
}