<?php

use Joomla\CMS\Form\Form;

defined('_JEXEC') or die;

jimport( 'joomla.form.fields.list' );
JFormHelper::loadFieldClass('list');

class JFormFieldCategories extends JFormFieldList {
    protected $type = 'Categories';
    protected $params;

    public function __construct(?Form $form = null)
    {
        parent::__construct($form);
        $this->params = JComponentHelper::getParams('com_pixelcms_articles');
    }

    protected function getOptions()
    {
        $data = [
            0 => (object) [
                'value' => 0,
                'text' => '---  Alle  ---',
            ],
        ];

        $api_token = $this->params->get('pixel_cms_token');

        $curl = curl_init();

        curl_setopt_array($curl, array(
            CURLOPT_URL => "{$this->params->get('pixel_cms_url')}/api/{$this->params->get('pixel_cms_version')}/categories?api_token=$api_token",
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => "",
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 2,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => "GET",
            CURLOPT_POSTFIELDS => "",
            CURLOPT_HTTPHEADER => array(
                "accept: application/json"
            ),
        ));

        $response = curl_exec($curl);

        curl_close($curl);

        $pixel_articles = $this->flatCategory(json_decode($response));

        foreach ($pixel_articles as $article) {
            $data[] = (object) [
                'value' => $article->id,
                'text' => "$article->title",
            ];
        }

        return $data;
    }

    private function prefixCat($cat, $index) {
        $cat->title = str_repeat(' - ', $index) . $cat->title;
        return $cat;
    }

    private function flat($carry, $cat, $index = 0) {
        array_push($carry, $this->prefixCat($cat, $index));

        if (is_array($cat->children) && count($cat->children) > 0) {
            $carry = array_merge($carry, $this->flatCategory($cat->children, $index + 1));
        }

        return $carry;
    }

    private function flatCategory($cat, $index = 0) {
        return array_reduce($cat, function($carry, $item) use ($index) {
            return $this->flat($carry, $item, $index);
        }, []);
    }
}
