<?php

/**
 * @package     VP Prime Framework
 *
 * @author      Abhishek Das <info@virtueplanet.com>
 * @link        https://www.virtueplanet.com
 * @copyright   Copyright (C) 2023 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\Database\DatabaseInterface;

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

/**
 * Provides VirtueMart custom fields selection field.
 */
class VirtuemartcustomfieldField extends ListField
{
    protected $type = 'virtuemartcustomfield';

    protected static $customfields = [];

    protected function getOptions()
    {
        $fieldType       = !empty($this->element['field_type']) ? (string) $this->element['field_type'] : null;
        $isCartAttribute = !empty($this->element['is_cart_attribute']) ? (int) $this->element['is_cart_attribute'] : null;
        $isInput         = !empty($this->element['is_input']) ? (int) $this->element['is_input'] : null;
        $layoutPosition  = !empty($this->element['layout_pos']) ? (string) $this->element['layout_pos'] : null;
        $published       = !empty($this->element['published']) ? (int) $this->element['published'] : 1;
        $hash            = md5('field_type:' . $fieldType . '.is_cart_attribute:' . $isCartAttribute . '.is_input:' . $isInput . '.layout_pos:' . $layoutPosition . '.published:' . $published);

        if (!isset(static::$customfields[$hash])) {
            $db    = Factory::getContainer()->get(DatabaseInterface::class);
            $query = $db->getQuery(true);

            $query->select($db->quoteName(['custom_title', 'virtuemart_custom_id', 'field_type', 'custom_params']))
                ->from($db->quoteName('#__virtuemart_customs'));

            if (!empty($fieldType)) {
                if (strpos($fieldType, ',') !== false) {
                    $fieldType = explode(',', $fieldType);
                } else {
                    $fieldType = array($fieldType);
                }

                $fieldType = array_filter(array_map('trim', $fieldType));

                if (!empty($fieldType)) {
                    if (count($fieldType) === 1) {
                        $query->where($db->quoteName('field_type') . ' = ' . $db->quote($fieldType[0]));
                    } else {
                        $query->where($db->quoteName('field_type') . ' IN (' . implode(',', $db->quote($fieldType)) . ')');
                    }
                }
            }

            if (!empty($isCartAttribute)) {
                $query->where($db->quoteName('is_cart_attribute') . ' = ' . $isCartAttribute);
            }

            if (!empty($isInput)) {
                $query->where($db->quoteName('is_input') . ' = ' . $isInput);
            }

            if (!empty($layoutPosition)) {
                $query->where($db->quoteName('layout_pos') . ' = ' . $db->quote($layoutPosition));
            }

            if (!empty($published)) {
                $query->where($db->quoteName('published') . ' = ' . $published);
            }

            $db->setQuery($query);

            try {
                $items = $db->loadObjectList();
            } catch (\Exception $e) {
                Factory::getApplication()->enqueueMessage($e->getMessage(), 'error');
                return false;
            }

            if (empty($items)) {
                static::$customfields[$hash] = [];
            } else {
                static::$customfields[$hash] = $items;
            }
        }

        $options = [];

        if (!empty(static::$customfields[$hash])) {
            foreach (static::$customfields[$hash] as $item) {
                $options[] = HTMLHelper::_('select.option', $item->virtuemart_custom_id, Text::_($item->custom_title));
            }
        }

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