<?php

declare(strict_types=1);

namespace App\Services;

use Illuminate\Support\Facades\DB;

class CategoryService
{
    public function getCategoryParents($category)
    {
        $categories = [];

        while ($category) {
            $categories[] = $category;
            $category = $category->parent;
        }

        return array_reverse($categories);
    }

    public function getCategoryChildrenIds($children)
    {
        $childIds = [];
        foreach ($children as $child) {
            $childIds[] = $child->id;
            $childIds = array_merge($childIds, $this->getCategoryChildrenIds($child->children));
        }

        return $childIds;
    }

    public function getChildrenByParent($parent_id)
    {
        $childIds = [];
        $children = DB::table('categories')->where('parent_id', $parent_id)->get();
        foreach ($children as $child) {
            $childIds[] = $child->id;
            $childIds = array_merge($childIds, $this->getChildrenByParent($child->id));
        }

        return $childIds;
    }
}
