<?php

namespace DropshippingExportFreeVendor\WPDesk\Library\DropshippingExport\PriceCompare\Categories;

use DropshippingExportFreeVendor\WPDesk\Library\DropshippingExport\Infrastructure\Config\Config;
use SimpleXMLElement;
use DropshippingExportFreeVendor\WPDesk\Library\DropshippingExport\PriceCompare\PriceCompareCategory;
class NokautCategories implements PriceCompareCategory
{
    private Config $config;
    private SimpleXMLElement $xml_categories;
    public function __construct(Config $config)
    {
        $this->config = $config;
    }
    public function get_category_full_name(int $category_id): string
    {
        $categories = $this->get_categories();
        return isset($categories[$category_id]) ? $categories[$category_id] : '';
    }
    public function get_categories(): array
    {
        $options = [];
        $this->load_array_of_category();
        $children = $this->xml_categories->xpath('//category');
        foreach ($children as $child) {
            $options[(string) $child->attributes()->id] = (string) $child;
        }
        return $options;
    }
    public function find_category_by_name(string $term): array
    {
        $result = [];
        $categories_options = $this->get_categories();
        foreach ($categories_options as $category_id => $category_name) {
            if (stripos($category_name, $term) !== \false) {
                $result[] = ['value' => $category_id, 'text' => $category_name];
            }
        }
        return $result;
    }
    private function load_array_of_category(): void
    {
        if (empty($this->xml_categories)) {
            $data = file_get_contents(str_replace(['/class', '\class'], '', $this->config->get_param('assets.data.nokaut')->getAsString()));
            $this->xml_categories = new \SimpleXMLElement(trim($data));
        }
    }
}
