<?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\Database\DatabaseInterface;

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

/**
 * Provides module selection field.
 */
class ModuleField extends ListField
{
    /**
     * The form field type.
     *
     * @var    string
     */
    protected $type = 'module';

    /**
     * Method to get the field input markup.
     *
     * @return  string   The field input markup.
     */
    protected function getOptions()
    {
        if ($this->multiple) {
            $this->layout = 'joomla.form.field.list-fancy-select';
        }

        $db    = Factory::getContainer()->get(DatabaseInterface::class);
        $query = $db->getQuery(true);

        $query->select('e.extension_id, a.id, a.title, a.note, a.position, a.module, a.language,a.checked_out, ' .
                     'a.checked_out_time, a.published, a.access, a.ordering, a.publish_up, a.publish_down, ' .
                     'l.title AS language_title,uc.name AS editor,ag.title AS access_level, ' .
                     'MIN(mm.menuid) AS pages,e.name AS name')
            ->from('#__modules AS a')
            ->join('LEFT', '#__languages AS l ON l.lang_code = a.language')
            ->join('LEFT', '#__users AS uc ON uc.id = a.checked_out')
            ->join('LEFT', '#__viewlevels AS ag ON ag.id = a.access')
            ->join('LEFT', '#__modules_menu AS mm ON mm.moduleid = a.id')
            ->join('LEFT', '#__extensions AS e ON e.element = a.module')
            ->where('a.published IN (0, 1)')
            ->where('a.client_id = 0')
            ->group('a.id');

        $db->setQuery($query);

        $groups  = $db->loadObjectList();
        $options = [];

        if ($groups && count($groups)) {
            foreach ($groups as $v => $t) {
                $options[] = HTMLHelper::_('select.option', $t->id, $t->title);
            }
        }

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