<?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\FormField;
use Joomla\CMS\HTML\HTMLHelper;
use Joomla\CMS\Language\Text;
use Joomla\Component\Modules\Administrator\Service\HTML\Modules;

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

/**
 * Provides module position selection field.
 */
class ModpositionField extends FormField
{
    /**
     * The form field type.
     *
     * @var    string
     */
    protected $type = 'modposition';

    /**
     * Method to get the field input markup.
     *
     * @return  string   The field input markup.
     */
    public function getInput()
    {
        HTMLHelper::addIncludePath(JPATH_ADMINISTRATOR . '/components/com_modules/src/Service/HTML/Modules.php');

        /** @var \Joomla\CMS\Application\AdministratorApplication $app */
        $app = Factory::getApplication();
        // Load language files
        $language = $app->getLanguage();
        // Loads the current language-tag
        $language_tag = $language->getTag();
        $language->load('com_modules', JPATH_ADMINISTRATOR, $language_tag, true);

        $clientId          = 0;
        $state             = 1;
        $selectedPosition  = $this->value;
        $modules           = new Modules();
        $positions         = $modules->positions($clientId, $state, $selectedPosition);

        // Add custom position to options
        $customGroupText = Text::_('COM_MODULES_CUSTOM_POSITION');

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

        // Build field
        $attr = array(
            'id'          => $this->id,
            'list.select' => $this->value,
            'list.attr'   => 'class="chzn-custom-value" '
                          . 'data-custom_group_text="' . $customGroupText . '" '
                          . 'data-no_results_text="' . Text::_('COM_MODULES_ADD_CUSTOM_POSITION') . '" '
                          . 'data-placeholder="' . Text::_('COM_MODULES_TYPE_OR_SELECT_POSITION') . '" '
        );

        $html  = '<joomla-field-fancy-select class="" allow-custom placeholder="' . Text::_('COM_MODULES_TYPE_OR_SELECT_POSITION') . '" search-placeholder="' . Text::_('COM_MODULES_TYPE_OR_SELECT_POSITION') . '" >';
        $html .= HTMLHelper::_('select.groupedlist', $positions, $this->name, $attr);
        $html .= '</joomla-field-fancy-select>';

        return $html;
    }
}
