<?php

/**
 * @package     Joomla.Administrator
 * @subpackage  com_formea
 *
 * @copyright   Copyright (C) 2010-2025 Feseur Sdn Bhd. All rights reserved.
 * @license     GNU General Public License version 2 or later; see LICENSE.txt
 * @version     1.3.0
 */

namespace Joomla\Component\Formea\Administrator\Field;

defined('_JEXEC') or die('Restricted access');

use Joomla\CMS\Factory;
use Joomla\CMS\Form\Field\ListField;
use Joomla\CMS\HTML\HTMLHelper;
use Joomla\Database\DatabaseDriver;

/**
 * name Form Field class for the Genejunction component
 */
class FormeaElementListField extends ListField
{
  /**
   * The name field type.
   *
   * @var    string
   */
  protected $type = 'formeaElementList';


  /**
   * Method to get a list of options for a list input.
   *
   * @return  array    An array of JHtml options.
   */
  protected function getOptions()
  {
    $dataAttr    = $this->getDataAttributes();
    $valueType   = $this->getAttribute('data-value-type');
    $eltype      = $this->getAttribute('eltype');
    $layoutData  = $this->getLayoutData();
    $currentElId = $layoutData['field']->form->getData()->get('id', 0);


    $container = Factory::getContainer();
    /** @var DatabaseDriver $db */
    $db    = $container->get('DatabaseDriver');
    $query = $db->getQuery(true);
    $query->select(['a.id', 'a.title', 'b.value_type']);
    $query->from($db->quoteName('#__formea_elements', 'a'))->innerJoin(
      $db->quoteName('#__formea_eltypes', 'b') . ' ON ' . $db->quoteName('a.type') . ' = ' .
        $db->quoteName('b.name')
    );

    $query->where($db->quoteName('a.state') . ' = 1');
    $query->where($db->quoteName('b.state') . ' = 1');
    $orWhere = false;
    if (!empty($valueType)) {
      $query->where($db->quoteName('b.value_type') . ' IN (' . $valueType . ')');
      $orWhere = true;
    }

    if (!empty($eltype)) {
      $eltypeLists      = explode(',', $eltype);
      $totalElTypeLists = count($eltypeLists);
      for ($i = 0; $i < $totalElTypeLists; $i++) {
        if ($i == 0) {
          if ($orWhere) {
            $query->orWhere($db->quoteName('b.name') . ' LIKE ' . $db->quote('%' . $eltypeLists[$i] . '%'));
          } else {
            $query->where($db->quoteName('b.name') . ' LIKE ' . $db->quote('%' . $eltypeLists[$i] . '%'));
          }
        } else {
          $query->orWhere($db->quoteName('b.name') . ' LIKE ' . $db->quote('%' . $eltypeLists[$i] . '%'));
        }
      }
    }
    $query->andWhere($db->quoteName('a.id') . ' != ' . $currentElId);

    $query->order('a.id DESC');
    $db->setQuery($query);
    $items   = $db->loadObjectList();
    $options = array();
    if ($items) {
      foreach ($items as $item) {
        $options[] = HTMLHelper::_('select.option', $item->id, ucwords($item->title));
      }
    }
    $options = array_merge(parent::getOptions(), $options);

    return $options;
  }
}
