<?php

use Joomla\CMS\Form\Form;

defined('_JEXEC') or die;

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

class JFormFieldManufacturercategories extends JFormFieldList {
    protected $type = 'Manufacturercategories';
    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' => "",
                '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')}/manufacturer_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 = json_decode($response);

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

        return $data;
    }
}
