<?php

namespace MGS\FakeOrder\Block\Adminhtml\System\Config\Form\Field;

use Magento\Backend\Block\Template\Context;
use Magento\Config\Block\System\Config\Form\Field;
use Magento\Framework\Data\Form\Element\AbstractElement;
use Magento\Framework\UrlInterface;

class TomSelectProduct extends Field
{
    protected $urlBuilder;

    public function __construct(
        Context $context,
        array   $data = []
    )
    {
        $this->urlBuilder = $context->getUrlBuilder();
        parent::__construct($context, $data);
    }


    protected function _getElementHtml(AbstractElement $element)
    {
        $element->addClass('tom-select');
        $html = parent::_getElementHtml($element);
        $baseUrl = $this->urlBuilder->getBaseUrl(['_type' => UrlInterface::URL_TYPE_WEB]);

        ob_start();
        ?>
        <script type="text/javascript">
            require(["jquery", "tom-select"], function ($, TomSelect) {
                $(document).ready(function () {
                    new TomSelect("#<?=$element->getHtmlId()?>", {
                        valueField: "value",
                        labelField: "label",
                        searchField: "label",
                        plugins: ["remove_button"],
                        render: {
                            option: function(item, escape) {
                                return '<div class="tom-select-option">' +
                                    '<span class="tom-select-option-name">' + escape(item.label) + '</span>' +
                                    '</div>';
                            },
                            item: function(item, escape) {
                                return '<div class="tom-select-item">' +
                                    '<span class="tom-select-item-name">' + escape(item.label) + '</span>' +
                                    '</div>';
                            }
                        },
                        load: function (query, callback) {
                            if (!query.length) return callback();
                            $.ajax({
                                url: "<?=$baseUrl?>rest/V1/mgs/fake-order/products",
                                type: 'GET',
                                dataType: 'json',
                                data: {
                                    q: query
                                },
                                success: function(response) {
                                    response=response[0];
                                    if (response.status === 'success') {
                                        callback(response.data);
                                    } else {
                                        callback();
                                    }
                                },
                                error: function() {
                                    console.error('Error fetching data from API.');
                                    callback();
                                }
                            });
                        }
                    });
                });
            });
        </script>

        <?php
        $content = ob_get_contents();
        ob_end_clean();
        $html .= $content;
        return $html;
    }

}
