<?php

use Joomla\CMS\Form\Form;

defined('_JEXEC') or die;

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

class JFormFieldManufacturers extends JFormFieldList {
    protected $type = 'Manufacturers';
    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')}/manufacturers?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);

        $manufacturers = json_decode($response);

        return array_reduce($manufacturers, function($arr, $manufacturer) {
            return array_merge($arr, array_map(function($link) use ($manufacturer) {
                return (object) [
                    'value' => $link->id,
                    'text' => "$manufacturer->title $link->title",
                ];
            }, $manufacturer->links));
        }, []);
    }
}
