<?php

class Feed
{
    private $type;
    private $cache;

    /***** Supported types feed addresses ******/

    private $feeds = [
        'heureka' => 'http://www.heureka.cz/direct/xml-export/shops/heureka-sekce.xml',
        'google' => 'http://shared.kupshop.cz/tmp/google_ctegories.xml',
    ];

    /**** Interface ***/

    public function __construct($type = 'heureka')
    {
        $this->type = $type;
    }

    public function getHeurekaCategories()
    {
        return $this->getCategories();
    }

    public function getCategories()
    {
        if (!empty($this->cache)) {
            return $this->cache;
        }

        global $cfg;

        $cacheFile = $cfg['Path']['shared_dirs']."tmp/categories_{$this->type}";

        if (file_exists($cacheFile)) {
            return unserialize(file_get_contents($cacheFile));
        }

        $xml = simplexml_load_file($this->feeds[$this->type]);

        $categories = $this->parseCategories($xml);

        $fileHandle = fopen($cacheFile, 'wb');
        fwrite($fileHandle, serialize($categories));
        fflush($fileHandle);
        fclose($fileHandle);

        $this->cache = $categories;

        return $categories;
    }

    public function getCategoryTree(&$tree)
    {
        $this->formatCategory($tree, $this->getCategories(), 0);

        return $tree;
    }

    public function getFullCategory($cat_id)
    {
        return $this->findCategory($this->getCategories(), $cat_id);
    }

    /**** Non-Interface function *****/

    private function parseCategories(&$parent)
    {
        $categories = [];

        foreach ($parent->CATEGORY as $category) {
            $id = intval(strval($category->CATEGORY_ID));
            $name = strval($category->CATEGORY_NAME);
            $categories[$id] = ['name' => $name];

            if (!empty($category->CATEGORY)) {
                $categories[$id]['children'] = $this->parseCategories($category);
            }
        }

        return $categories;
    }

    private function formatCategory(&$tree, $categories, $level)
    {
        foreach ($categories as $id => $category) {
            $tree[strval($id)] = str_pad('', $level, '-').' '.$category['name'];

            if (!empty($category['children'])) {
                $this->formatCategory($tree, $category['children'], $level + 1);
            }
        }

        return $categories;
    }

    private function findCategory($categories, $cat_id)
    {
        foreach ($categories as $id => $category) {
            if ($id == $cat_id) {
                return [$category['name']];
            }

            if (!empty($category['children'])) {
                $ret = $this->findCategory($category['children'], $cat_id);

                if ($ret !== false) {
                    array_unshift($ret, $category['name']);

                    return $ret;
                }
            }
        }

        return false;
    }
}
