<?php

/**
 * @package     VP Prime Framework
 *
 * @author      Abhishek Das <info@virtueplanet.com>
 * @link        https://www.virtueplanet.com
 * @copyright   Copyright (C) 2012-2025 Virtueplanet Services LLP. All Rights Reserved.
 * @license     GNU General Public License version 2 or later; see LICENSE.txt
 */

namespace Virtueplanet\Plugin\System\Prime\Field;

use Joomla\CMS\Factory;
use Joomla\CMS\Form\Field\ListField;
use Joomla\CMS\HTML\HTMLHelper;
use Joomla\CMS\Language\Text;
use Joomla\CMS\Uri\Uri;

// phpcs:disable PSR1.Files.SideEffects
\defined('_JEXEC') or die;
// phpcs:enable PSR1.Files.SideEffects

class VmproductField extends ListField
{
    /**
     * The form field type.
     *
     * @var    string
     */
    protected $type = 'vmproduct';

    public function getInput()
    {
        if (is_string($this->value)) {
            $this->value = explode(',', $this->value);
        }

        /** @var \Joomla\CMS\Application\AdministratorApplication $app */
        $app           = Factory::getApplication();
        $data          = $this->getLayoutData();
        $hint          = !empty($data['hint']) ? $data['hint'] : '';
        $allowCustom   = !empty($data['allowcustom']) ? $data['allowcustom'] : false;
        $required      = !empty($data['required']) ? $data['required'] : false;
        $minTermLength = !empty($data['mintermlength']) ? $data['mintermlength'] : 2;
        $dataAttribute = !empty($data['data']) ? $data['data'] : '';

        $attr  = '';
        $attr .= !empty($data['class']) ? ' class="' . $data['class'] . '"' : '';
        $attr .= ' placeholder="' . htmlspecialchars($hint ?: Text::_('PLG_SYSTEM_VPPRIME_TYPE_OR_SELECT_SOME_PRODUCTS'), ENT_COMPAT, 'UTF-8', false) . '" ';
        $attr .= $dataAttribute;

        if ($allowCustom) {
            $attr .= $allowCustom ? ' allow-custom' : '';
            $attr .= $allowCustom ? ' new-item-prefix="#new#"' : '';
        }

        $attr .= ' remote-search';
        $attr .= ' url="' . Uri::base(true) . '/index.php?option=com_ajax&plugin=vpprime&format=json&method=getVirtuemartProducts"';
        $attr .= ' term-key="like"';
        $attr .= ' min-term-length="' . $minTermLength . '"';

        if ($required) {
            $attr .= ' required';
        }

        Text::script('JGLOBAL_SELECT_PRESS_TO_SELECT');

        $app->getDocument()->getWebAssetManager()
            ->usePreset('choicesjs')
            ->useScript('webcomponent.field-fancy-select');

        $html = parent::getInput();

        return '<joomla-field-fancy-select ' . $attr . '>' . $html . '</joomla-field-fancy-select>';
    }

    public function getOptions()
    {
        \JLoader::register('VmConfig', JPATH_ADMINISTRATOR . '/components/com_virtuemart/helpers/config.php');

        \VmConfig::loadConfig();

        $options = [];

        if (!empty($this->value)) {
            \VmConfig::loadJLang('com_virtuemart', true);

            $model       = \VmModel::getModel('Product');
            $product_ids = array_map('intval', $this->value);
            $products    = $model->getProducts($product_ids);

            if (!empty($products)) {
                foreach ($products as $product) {
                    $value = (int) $product->virtuemart_product_id;
                    $text  = htmlspecialchars($product->product_name, ENT_COMPAT, 'UTF-8', false);

                    $options[] = HTMLHelper::_('select.option', $value, $text);
                }
            }
        }

        return array_merge(parent::getOptions(), $options);
    }
}
