<?php
namespace App\Models;

class Category extends Model {
    protected static function getTable(): string {
        return 'categories';
    }

    public function getParent() {
        if (!$this->parent_slug) {
            return null;
        }
        return self::findBy(['slug' => $this->parent_slug]);
    }

    public function getSubcategories() {
        return self::all(['parent_slug' => $this->slug]);
    }

    public function getProducts() {
        $allProducts = Product::all();

        $slugs = $this->getAllDescendantSlugs();

        return array_values(array_filter($allProducts, function($product) use ($slugs) {
            $cats = $product->categories;
            if (is_string($cats)) {
                $cats = json_decode($cats, true) ?? [];
            }
            return is_array($cats) && !empty(array_intersect($slugs, $cats));
        }));
    }

    protected function getAllDescendantSlugs() {
        $slugs = [$this->slug];
        foreach ($this->getSubcategories() as $sub) {
            $slugs = array_merge($slugs, $sub->getAllDescendantSlugs());
        }
        return $slugs;
    }
}
